0

I'm using Javascript to change HTML attributes,in my case I have 2 photos of the same light bulb that is switched on/off and I'm using 2 buttons in order to "switch on" and "switch off" the light bulb,but now I want to displace these 2 buttons into 2 images of the same switch that is on in the first pic and the second pic that the switch is off,how to do it?

<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p>JavaScript can change HTML attributes.</p>

<p>In this case JavaScript changes the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>
enter image description here

1

3 Answers 3

1

Kemal above demonstrated you way to solve your problem above, although you said it didn't work. Well, here's prove it actually has to be working.

<img id="myImage" src="http://placehold.it/150/000/fff" style="width:100px">

<button onclick='document.getElementById("myImage").setAttribute("src", "http://placehold.it/150/E8117F/000")'>PINK</button>
<button onclick='document.getElementById("myImage").setAttribute("src", "http://placehold.it/150/000/fff")'>BLACK</button>

Sign up to request clarification or add additional context in comments.

Comments

0

Try changing these

document.getElementById('myImage').src='pic_bulbon.gif'

into those

document.getElementById('myImage').setAttribute("src", "pic_bulbon.gif");

More info: https://www.w3schools.com/jsref/met_element_setattribute.asp

1 Comment

@Kujtim Hajdini it has to be working. Use setAttribute function. jsfiddle.net/rd9d2a2q/1
0

If I understand your question you want the 'turn on' button to be an image of an on switch, and the turn off button to be an image of an off switch.

You could add a background-image property to each button.

<button style="background:url('lightSwitchOn.gif'); background-size: 100px 100px;">Turn on the light</button>

<button style="background:url('lightSwitchOff.gif'); background-size: 100px 100px;">Turn off the light</button>

You would need more css to resize the button to the size of the image. Taking the css out of the html and into a css file will help keep things organised.

A second option would be to display the light bulbs as images and handle their 'onClick' event.

Comments

Your Answer

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