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
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    Possible duplicate of [How to add/update an attribute to an HTML element using JavaScript?](http://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript) – Peter G Feb 25 '17 at 23:34

3 Answers3

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>
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

Kemal Yalcinkaya
  • 1,818
  • 1
  • 13
  • 25
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.

alichur
  • 925
  • 7
  • 19