javascriptimage-replacement

Image change on link click without hardcoding locations?


What I'm trying to do is let a visitor change an image by clicking through a set of thumbnails. However, the problem I'm running into is that I really want to get away from hardcoding the image locations into the script. I want the script to be portable enough to run on any old page and set of images as long as the IDs used match. Is there a way I can change the following to do substitute X's src for A, B or C's src?

JS

function clickSwitch() {
  var element = document.getElementById("bigscreen");
  element.setAttribute("src", "/img/projects/jamison/j2.jpg");
}

HTML

<img class="project-img" src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" id="bigscreen" />

<ul class="project-thumbnails">
<li><a href="#n" onclick="clickSwitch();"><img src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" /></a></li> 
<li><a href="#n" onclick="clickSwitch();"><img src="/img/projects/jamison/j2.jpg" alt="Jamison: View Two" /></a></li>
</ul>

Solution

  • I would load the elements into an array, add an event to each of them outside of the inlin html, blah blah blah ... but here you go:

    Add "this" to your onclick event, that passes the tag into clickSwitch. From there you can get what you need for bigscreen.

    html

    <a href="#n" onclick="clickSwitch(this);"><img src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" /></a>
    

    javascript

    function clickSwitch(el){
        var src = el.firstChild.getAttribute('src');
        var bigscreen = document.getElementById("bigscreen"); 
        bigscreen.setAttribute("src", src);
    }