user2662723
user2662723

Reputation: 103

Confused with jQuery show/hide for images

I have seven images lined up on one of my pages. I have the show/hide functionality working where it shows the odd images with an "odd" button and shows even images with an "even" button. The way it works now is that if you click on the odd button, it only shows the odd. And vise versa for the even ones.

However, if the odd images are shown and I click on the even button, I want them all shown, so it adds them to what is already shown. If nothing is already shown, clicking on the even button should just show the even images? Same thing for the odd images.

But if all images are currently shown, clicking even should show the even images and hide the odd ... clicking odd should show the odd and hide the even.

I hope that makes sense. I am not sure how to get that to work. Do I need a conditional statement? I just don't know what I would check for.

Here is the working code, but not how I want it to work.

<script>
$(function () {
    $("#evenButton").click(function () {
        $("img").show("slow");
        $("img:even").show("slow");
    });
})
</script>

<script>
$(function () {
    $("#oddButton").click(function () {
        $("img").show("slow");
        $("img:even").hide("slow");
        $("img:odd").show("slow");
    });
})
</script>

Upvotes: 1

Views: 413

Answers (2)

Beno
Beno

Reputation: 4753

I'm finding it hard to understand your question but to you want the images to just toggle between hidden and shown when the button is pressed?

I've updated based on another read through of your question

$("#evenButton").click(function () {
    if($("img:even").is(':visible') && $("img:odd").is(':visible')) {
        $("img:odd").toggle("slow");        
    } else {
        $("img:even").show("slow");
    }
});

$("#oddButton").click(function () {
    if($("img:odd").is(':visible') && $("img:even").is(':visible')) {
        $("img:even").toggle("slow");        
    } else {
        $("img:odd").show("slow");
    }
});

http://jsfiddle.net/HXycX/2/

Upvotes: 1

Ivan Chub
Ivan Chub

Reputation: 442

If I'm getting your question correctly, you want your buttons to toggle the state of either the even ones or the odd ones, not just show them. To do that you need to store whether or not the button's corresponding images are shown or not in a variable. Something like this could work:

var evenImagesVisible = false;

function toggleEvenImages() {
    evenImagesVisible = !evenImagesVisible // flip the state of the even images

    if (evenImagesVisible) {
         $("img:even").show("slow");
    }
    else {
         $("img:even").hide("slow");
    }
}

That's the method for toggling only the even images. Toggling the odd images is exactly the same, just change some variable names and the selector.

Upvotes: 0

Related Questions