Thais
Thais

Reputation: 150

Hiding/Showing images jQuery

Alright. What I want to do is create a few buttons up top, which will hide/show elements.
If the user presses "350x150" it will hide all the images except for the "350x150" images.

1). User presses "350x150"
2). All images hide except for the two "350x150"

I tried using some jQuery to hide images but it did not work.
How would I do this?

What I want it to look like The images are done like this:

                <div class="Collage">
                    <img class="boom" src="http://placehold.it/1000x150">
                    <img class="ei" src="http://placehold.it/150x150">
                    <img class="boom" src="http://placehold.it/200x150">
                    <img class="ei" src="http://placehold.it/200x350">
                    <img class="350x150" src="http://placehold.it/350x150">
                    <img class="350x150" src="http://placehold.it/350x150">
                    <img class="boom" src="http://placehold.it/500x150">
                    <img class="ei" src="http://placehold.it/50x200">
                    <img class="boom" src="http://placehold.it/350x200">
                    <img class="ei" src="http://placehold.it/600x200">
                </div>

Upvotes: 2

Views: 1191

Answers (2)

Oleksii Artiukh
Oleksii Artiukh

Reputation: 384

Try to use class name, which starts not with a number. I had a lot of troubles in case of it.
For example <img class="res350x150" src="" />

Upvotes: 0

Zoran P.
Zoran P.

Reputation: 880

You can add to your filter btns class let's say "filter-btn" and then their id's could be the same as the class you want to show, for example id="350x150" or id="boom" or id="ei"... I think you get the point :)

$(".filter-btn").click(function(){
var filterVal = "." + $(this).attr("id");
  $(".Collage img").show();
  $(".Collage img").not(filterVal).hide();
});

Or you can first hide all and then show those that you need:

$(".filter-btn").click(function(){
var filterVal = "." + $(this).attr("id");
  $(".Collage img").hide();
  $(".Collage img").filter(filterVal).show();
});

EDIT or better cache your elements:

var $collageImages = $(".Collage").find("img"); // cache your elements!
$("#filter350x150").click(function(){
  $collageImages.hide();  // Hide all
  $(".350x150").show();   // Show desired ones
});
// other buttons here...

or with a more versatile code:

var $collageImages = $(".Collage").find("img"); // cache your elements!
$("[id^=filter]").click(function(){  // any button which ID starts with "filter"
  var class = this.id.split("filter")[1]; // get the filterXYZ suffix
  $collageImages.hide();                  // Hide all
  $collageImages.is("."+ class ).show()   // Show desired ones
});

Upvotes: 4

Related Questions