How To Change The Src Attribute Of An Image Tag In Jquery(Simple Accordion Example)

Introduction to Creating a Custom Accordion with an Image 


While walking through web design, you may wonder for sometime that how to change the a image source on clicking on it. It is a basic requirement when there is something you want to hide on clicking the image, and to unhidden by clicking on it again.

Let me explain this in a simple way;
There is a div which has a "+" image and another div below it. Our goal is to show that div when we click on the "+" image and to change the image from "+" to  "-"
Again  when we click on the "-" image then the div will be hidden with the image changed from  "-" to "+".
Now I think the requirement is clear. Lets acheive this with Jquery.

Here is a screen shot how it will look like
Image On Off
   Download Source Code Here
   

Let's Create an Accordion and Replace the Image source on clicking it


Lets take a div with class headerList and an image tag inside it like below
        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 1
        </div>
        <div class="childGrd">
            Body Part 1
        </div>

        <div class="headerList">
            <img src="image/PLUS.gif" alt="xyz" class="ImageOnOff" style="cursor: pointer" />
            Header Section 2
        </div>
        <div class="childGrd">
            Body Part 2
        </div>
From the above design you can see that there are two identical divs those have the same structure. And this will look like below.
Now, you can predict what I want to show you here. Yes I am going to click the "+" sign and that will open the slightly green div ( shown in the top screen shot ). Along with the showing the div the "+" sign will be converted to "-".

To acheive this you need to put the below JQuery code in your page.
<script type="text/javascript">

  $(function () {
   //Hide the green divs initially
   var id =  $(".headerList").closest('div');
   $(id).next('div.childGrd').hide();
    });
    // Change the image source when the image is clicked
    $("img.ImageOnOff").live('click', function () {
    
   if ($(this).attr("src").toString().indexOf('PLUS.gif') != -1) 
     {
    this.src = this.src.replace("PLUS.gif", "MINUS.gif");
     }
     else 
     {
    this.src = this.src.replace("MINUS.gif", "PLUS.gif");
     }
   
   // Toggle the green div when the image is clicked
   var currentRow = $(this).closest('div');
   var tr = $(currentRow).next('div');
   $(tr).toggle();
  }); 
 
 </script>
The above jquery code explains how to replace the image source on the click of the image and how to find the next div which has to be hidden.

Happy Coding...

No comments:

Post a Comment