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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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!