Filter Image Types Using jQuery

I came across an interesting requirement recently. The application was similar to an image viewer and allowed users to filter out different image types on the click on a button. For eg: If the page contained .jpeg, .gif and .png’s, you could on the click on a button, hide the images with the .gif extension. Here’s how I solved the requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>

<
script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$('#btn').click(function() {
$('img').each(function() {
if ($(this).is('[src$=.gif],[src$=.Gif],[src$=.GIF]'))
$(this).hide();
});
});
});

</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
img alt="" src="images/emo.jpg" />
<
img alt="" src="images/icon068.gif" />
<
img alt="" src="images/icon260.jpg" />
<
input id="btn" type="button" value="Hide Gif's" />
</
div>
</
form>

</
body>
</
html>

Initially all the images will be displayed.

image

On the click of the ‘Hide Gif’s’ button, all the gif’s will get hidden. In our case, the 2nd image is a .gif

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Jesús María said...

tis is a wonderful tip i can use in my image viewer. thank you million times.

jaredmellentine said...

Seems like using jQuery's filter() and regex is a little simpler and more extensible:

$('img').filter(function(){ return this.src.match(/.gif$/i); }).hide();

Or if you plan on hiding different extensions:
function hideImagesByExt(ext) {
$('img').filter(function(){ return this.src.match(new RegExp('.' + ext + '$', 'i'); }).hide();
}

hideImagesByExt('gif');
hideImagesByExt('jpg');

Suprotim Agarwal said...

Nice!