I'm trying to code a simple game in an HTML document just for fun. In it, there is an image which adds to your score when clicked.
I created a simple if
statement within the score-adding function which should change the image and what its onClick
value is...
if (foo == 1) { document.getElementById("test").src = "images/test2.png"; document.getElementById("test").onClick = "foo2()"; }
...but it doesn't work. The image will be successfully changed, but the actual onClick remains the same. Checking the console, it throws no errors, either.
click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
HTML DOM Element click()The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.
It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
In JavaScript functions are objects.
document.getElementById('foo').onclick = function(){ prompt('Hello world'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With