user7154249
user7154249

Reputation:

JavaScript: change HTML attributes

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

Upvotes: 0

Views: 610

Answers (3)

Patryk Cieszkowski
Patryk Cieszkowski

Reputation: 751

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>

Upvotes: 1

alichur
alichur

Reputation: 963

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.

Upvotes: 0

Kemal Yalcinkaya
Kemal Yalcinkaya

Reputation: 1958

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

Upvotes: 0

Related Questions