June 18, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Filter Image Types Using jQuery"
  1. Jesús María said...
    June 22, 2009 9:18 PM

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

  2. jaredmellentine said...
    July 20, 2009 7:40 AM

    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');

  3. Suprotim Agarwal said...
    July 22, 2009 5:19 AM

    Nice!

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions