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.
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
Tweet
2 comments:
tis is a wonderful tip i can use in my image viewer. thank you million times.
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');
Post a Comment