www.webdeveloper.com
Results 1 to 3 of 3

Thread: [RESOLVED] How to change an image by its id using javascript

Hybrid View

  1. #1
    Join Date
    Mar 2012
    Posts
    2

    resolved [RESOLVED] How to change an image by its id using javascript

    Hi all,
    I'm a bit of a noob with javascript and was wondering if someone could take a look at my code and tell me how I can apply this to individual objects on a page.
    What it is trying to do is swap out a plus symbol with a minus symbol when a div is clicked on. I can get this to work for one instance but I was wondering how I could apply this to multiple images (each working seperately)?

    intImage = 2;

    function swapImage() {
    switch (intImage) {
    case 1:
    IMG1.src = "Images/minussymbol.gif"
    intImage = 2
    return(false);
    case 2:
    IMG1.src = "Images/plussymbol.gif"
    intImage = 1
    return(false);
    }
    }

    This works for one instance in my html code:

    <div class="mH" onclick="toggleMenu('menu1')"><IMG id="IMG1" name="IMG1" src="plussymbol.gif" onclick="swapImage();" ></img> UT2004:</div>

    How can I roll this out (I'm guessing using getElementById) to lots of elements similar to this so that if any one of the symbols is clicked on that instance alone will change to a minus symbol?

    Sorry if this is unclear.

    Thanks in advance.

  2. #2
    Join Date
    Feb 2012
    Posts
    218
    Try this code. As you can see, you can use it multiple times, for many images.
    Code:
    <script type="text/javascript">
    function swapImage(elm) {
    	var possibleValues = ['minussymbol.gif', 'plussymbol.gif']
    	if(elm.dataUser){
    		elm.src = possibleValues[1]
    		elm.dataUser = 0;
    	}
    	else{
    		elm.src = possibleValues[0]
    		elm.dataUser = 1;
    	}
    }
    </script>
    <div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage(this)" />UT2004:</div>
    <div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage(this)" />UT2004:</div>
    <div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage(this)" />UT2004:</div>
    dataUser is an arbitrary attribute, not a standard, used just to help you achieve your goal.

  3. #3
    Join Date
    Mar 2012
    Posts
    2
    Thanks Hyperion,
    that worked perfectly!
    Best wishes!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles