Search code examples
javascriptimagesrc

Change src with javascript only one in a group of images


i am really new with JavaScript. I new to click an image, that image will change SRC and the others too.

This is the code:

<a href="#pduno"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pduno.png" width="13" height="11" /></a> 
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a>
<a href="#pddos"><img onclick="this.src='img/pduno.png';document.getElementsByClassName('imgdp').src='img/pddos.png'" class="imgdp" src="img/pddos.png" width="13" height="11" /></a>

pduno.png is the "active" image and pddos.png is the "desactive" image.

Let's image I have 3 images pduno - pddos - pddos

When I click one of the 2 pddos, it change to pduno and the one that was pduno change to pddos. I mean, there will be only one image with pduno while the rest are pddos.

I am using this to create a scroll gallery. The pduno works to show what gallery is being showed.


Solution

  • I would use the jQuery library for that (because you need to use some not-so-simple functions)

    You can include it writing this code (no need to download anything):

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
    

    And then, I would do this:

    <a href="#pddos"><img class="pdimg" src="img/pduno.png" width="13" height="11" /></a>
    <a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a>
    <a href="#pddos"><img class="pdimg" src="img/pddos.png" width="13" height="11" /></a>
    

    In the HTML, I removed all the scripts, and moved them here:

    <script>
    $('.pdimg').click(function(){ //This registers the function with the click event
        $('.pdimg').attr('src', 'img/pddos.png'); //This resets the image to pddos
        $(this).attr('src', 'img/pddos.png'); //This sets the image to uno, 
                                 // "this" will be the img that you clicked on.
    }
    </script>