Click here to Skip to main content
16,016,425 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
<!DOCTYPE html>
<html>
<head>

<script>
function on(){
document.getElementById('myImage').src='pic_bulbon.gif';
}
function off(){
document.getElementById('myImage').src='pic_bulboff.gif';
}
</script>

</head>
<body>
<h2>Turn the pulp on or off !</h2>
<button onclick="on()">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" width="100px">
<button onclick="off()">Turn off the light</button>
</body>
</html>


What I have tried:

<!DOCTYPE html>
<html>
<head>

<script>
function on(){
document.getElementById('myImage').src='pic_bulbon.gif';
}
function off(){
document.getElementById('myImage').src='pic_bulboff.gif';
}
</script>

</head>
<body>
<h2>Turn the pulp on or off !</h2>
<button onclick="on()">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" width="100px">
<button onclick="off()">Turn off the light</button>
</body>
</html>
Posted
Updated 23-May-21 22:44pm

1 solution

Document.querySelector() - Web APIs | MDN[^]
EventTarget.addEventListener() - Web APIs | MDN[^]

However, since you're attaching an event listener to a single element, it would be simpler to add an id to that element, and use getElementById instead of querySelector.

For example:
HTML
<button id="onButton" type="button">Turn on the light</button>
JavaScript
document.getElementById("on").addEventListener("click", function(){
    document.getElementById("myImage").src = "pic_bulbon.gif";
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900