0

How can I create multiple onclick events for my html buttons? The code I have right now only implements it for one button. How can I get the script to change the image src to different images when the other buttons are clicked. I tried using different functions for each button but that didn't work.

*

<body>
<button class="button" onclick="myFunction()" ><strong>Objectives</strong></button>
<button class="button"><strong>Mission</button></strong>
<button class="button"><strong>Chemistry Vision</strong></button>
<button class="button"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction() {
    document.getElementById("myImg").src = "http:Objectives.png"; 
}
</script>
</body>

*

4
  • Give your buttons a class and select them using getElementsByClassName();. Ids should be unqiue, so the code you provided only relates to one specific button. Commented Dec 12, 2016 at 15:39
  • "I tried using different functions for each button but that didn't work" .. it should. Any way try calling the same function with an argument instead. ex: myFunction('Objectives'); Commented Dec 12, 2016 at 15:41
  • Try posting the code where you tried different functions for each button, then you can get help debugging that. Commented Dec 12, 2016 at 15:43
  • Thanks @Daniel Shillcock , @ leonsaysHi I tried it out both ways and they do work. Commented Dec 12, 2016 at 16:34

1 Answer 1

2

You should pass parameter to the function, something like this:

<body>
<button class="button" onclick="myFunction('Objectives')" ><strong>Objectives</strong></button>
<button class="button" onclick="myFunction('Mission')"><strong>Mission</button></strong>
<button class="button" onclick="myFunction('Chemistry)"><strong>Chemistry Vision</strong></button>
<button class="button" onclick="myFunction('Environment')"><strong>Environment Vision</strong></button></br>
<img id="myImg" src="http://image.png" >
<script>
function myFunction(imgName) {
    document.getElementById("myImg").src = "http:" + imgName + ".png"; 
}
</script>
</body>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.