Reputation: 3
I was developing a program in JavaScript, when each time the button is pressed the image should alternate on each press- if it is currently the "box open" image, it should switch to the "box closed" image.Similarly, if it is currently on closed, it should witch to the "box open". I am however facing an "illegal invocation" error How can this be solves?
var jackbox = document.getElementById("jackbox");
function click()
{
if (this.id == "Jump out,Jack!")
{
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
}
else(this.id == "Jump out,Jack")
{
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
}
}
document.getElementById("toggle").onclick = open;
<div style="text-align: center; height: 280px;">
<img id="jackbox" src="https://www.paulneve.com/pp/jackbox-closed.jpg" />
<br/>
<button id="toggle">Jump out, Jack!</button>
</div>
Upvotes: 0
Views: 284
Reputation: 3921
document.getElementById("toggle").onclick = open;
should be document.getElementById("toggle").onclick = click;
because the function that you want to execute on click is the click
function.
Note:
As mentioned by Dai in the comments, you should prefer using
addEventListener
. Like this:document.getElementById("toggle").addEventListener("click", click);
This else(this.id == "Jump out,Jack")
is invalid javascript, in else
statement you do not have to provide a condition. Either remove the condition or change else
to else if
. Like this:
if (this.id == "Jump out,Jack!") {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
} else {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
}
OR
if (this.id == "Jump out,Jack!") {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
} else if (this.id == "Jump out,Jack") {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
}
const jackbox = document.getElementById("jackbox");
function click() {
if (this.id == "Jump out,Jack!") {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
} else {
document.getElementById("jackbox").src = "https://www.paulneve.com/pp/jackbox-open.jpg";
}
}
document.getElementById("toggle").addEventListener("click", click);
<div style="text-align: center; height: 280px;">
<img id="jackbox" src="https://www.paulneve.com/pp/jackbox-closed.jpg" />
<br />
<button id="toggle">Jump out, Jack!</button>
</div>
Upvotes: 1