Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - document.getElementByID with onClick

Tags:

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.

like image 784
Poyo Avatar asked Jan 06 '14 00:01

Poyo


People also ask

How to do click event in JavaScript?

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.

How to click a dom element?

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.

Can we use Onclick in anchor tag?

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.


2 Answers

The onclick property is all lower-case, and accepts a function, not a string.

document.getElementById("test").onclick = foo2; 

See also addEventListener.

like image 65
Quentin Avatar answered Sep 20 '22 23:09

Quentin


In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){     prompt('Hello world'); } 
like image 34
Who iscoo Avatar answered Sep 19 '22 23:09

Who iscoo