Reputation: 311
I am trying to do an onclick event where when a light bulb image is clicked it goes from a light bulb off to a light bulb on image and vice versa. I am using an external javascript file. when I click on the image nothing happens.
I cant figure out whats wrong,
my html portion:
<head>
<link rel="stylesheet" href="css/program-01.css" />
<script type="text/javascript" src="javascript/program-01.js"></script>
<title>
<h1>Program-01</h1>
</title>
</head>
<body>
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulbFunction()" />
</div>
</body>
my js file function:
function LightBulb() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change = "images/light_on.png";
} else {
image_change = "images/light_off.png";
}
}
Upvotes: 1
Views: 624
Reputation: 87203
Suggestions/Problems:
You function names are different.
You're using the function LightBulbFunction
on the onclick
event. But, you don't have the function of that name in your script. You'll get
ReferenceError: LightBulbFunction() is not defined.
src
attribute value, use image_change.src
inside the event handler.To solve the problem change the name of onclick
attribute value to LightBulb
.
function LightBulb() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change.src = "images/light_on.png";
// ^^^^
} else {
image_change.src = "images/light_off.png";
// ^^^^
}
}
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" />
<!-- ^^^^^^^^^^^ -->
</div>
Better approach will be to use addEventListener
to bind events on the elements.
document.getElementById('light_off').addEventListener('click', function() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change.src = "images/light_on.png";
} else {
image_change.src = "images/light_off.png";
}
}, false);
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" />
<!-- ^^^^^^^^^^^ -->
</div>
Upvotes: 2
Reputation: 10627
You are not redefining the .src
. Change
image_change =
to
image_change.src =
And your function needs to have the same LightBulb
function name.
Upvotes: 0
Reputation: 2033
Well in your html, the code is onclick="LightBulbFunction()"
while in javascript it is LightBulb
. Change either of them and make them match
Upvotes: 0