user836630
user836630

Reputation:

Changing images by clicking links - Javascript


I have tried to create a simple JavaScript which was supposed to switch images when links are clicked. This is the code of the whole site (It's not much, but it was only meant to be a test):

<html>
<head>
    <title>Slideshow</title>
    <style type="text/css">
        #wrapper {
        width: 800px;
        height: 250px;
        margin: 75px auto auto auto;
        }
    </style>
    <script type="text/javascript">
        function changeImg(x) {
        document.getElementById(presentationImg).src='x';
        }
    </script>
</head>
<body>
    <div id="wrapper">
        <div id="mainnav">
            <ul>
                <li><a href="#" onClick="changeImg(design.jpg)">Design</a></li>
                <li><a href="#" onClick="changeImg(realisation.jpg)">Realisation</a></li>
                <li><a href="#" onClick="changeImg(deployment.jpg)">Deployment</a></li>
            </ul>
        </div>
        <div id="presentation">
            <img id="presentationImg" src="design.jpg" />
        </div>
    </div>  
</body>

I was pretty sure it would work, but it doesn't, and I have no idea why... does anyone know why, and what the solution is?

Upvotes: 0

Views: 134

Answers (1)

James Allardice
James Allardice

Reputation: 165971

Get rid of the quotes around x in your function, and quote the element ID instead:

document.getElementById("presentationImg").src = x;

You will also need to quote the string you pass in to your function:

<a href="#" onclick="changeImg('design.jpg')">

The way you have it currently, presentationImg will be undefined, as you haven't declared a variable of that name. To make it work the way you had it originally you could do this:

var presentationImg = "presentationImg";
document.getElementById(presentationImg).src = x;

Upvotes: 1

Related Questions