views:

53

answers:

2

Hi All, I need to change the images on every click using jQuery, lets say while the page loads for the first time it will be img1 and when i click on img1 it will be img2 and again if i click on img2 it will b img 1, and this should go on... code:

          <div>
           <span class="myimage">
          <img class="img1"src="8A7FA0A1FFEC5443785B9B29AF7629.jpg" alt="" />
         <img class="img2"src="abcd.jpg" alt="" />
           </span>
            <div>
              <span>
                Hello
            </span>
           <ul class="myul">
              <li>one</li>
          <li>Two</li>
              </ul>
           </div>
           <span class="myimage">
          <img class="img1"src="8A7FA0A1FFEC5443785B9B29AF7629.jpg" alt="" />
          <img class="img2"src="abcd.jpg" alt="" />
          </span>
            <div>
              <span>
               r u there
           </span>
          <ul class="myul">
            <li>three</li>
                <li>four</li>
                </ul>
             </div>
             </div>

jQuery:

 $(document).ready(function() {

        $(".myul").hide();

        $(".myimage").click(function() {

            if ($(".img2").is(":hidden")) {
                $(this).next("div").find(".myul").slideToggle(600);

                $(".img1").hide();
                $(".img2").show();
            }
            else {

               $(this).next("div").find(".myul").slideToggle(600);
               $(".img2").hide();
                $(".img1").show();

            }

        });
    });

but the probelm is as the class is same both the sections are taking same image.when i am clicking on the first section, only the image for the first section should be changed, how to do taht..any suggestions

+4  A: 

You can add the context into your selectors.

For example $(".img1") becomes $(".img1", this)

$(document).ready(function() {

    $(".myul").hide();

    $(".myimage").click(function() {

        if ($(".img2", this).is(":hidden")) {
            $(this).next("div").find(".myul").slideToggle(600);

            $(".img1", this).hide();
            $(".img2", this).show();
        }
        else {

           $(this).next("div").find(".myul").slideToggle(600);
           $(".img2", this).hide();
            $(".img1", this).show();

        }

    });
});
Greg
thanks its working..
Wondering
+3  A: 

You can use selectors to find DOM elements relative to the element that the event was originally fired on.

For example, in this case you can find the children of the span you have attached the 'click' event to:

 $(".myimage").click(function() {
           if ($(this).children(".img2").is(":hidden")) {
              // do something
           }
Roy