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.
This question is related to
javascript
html
onclick
In JavaScript functions are objects.
document.getElementById('foo').onclick = function(){
prompt('Hello world');
}
Perhaps you might want to use "addEventListener"
document.getElementById("test").addEventListener('click',function ()
{
foo2();
} );
Hope it's still useful for you
window.onload = prepareButton;
function prepareButton()
{
document.getElementById('foo').onclick = function()
{
alert('you clicked me');
}
}
<input id="foo" value="Click Me!" type="button" />
Sometimes JavaScript is not activated. Try something like:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"> <!--
function jActivator() {
document.getElementById("demo").onclick = function() {myFunction()};
document.getElementById("demo1").addEventListener("click", myFunction);
}
function myFunction( s ) {
document.getElementById("myresult").innerHTML = s;
}
// --> </script>
<noscript>JavaScript deactivated.</noscript>
<style type="text/css">
</style>
</head>
<body onload="jActivator()">
<ul>
<li id="demo">Click me -> onclick.</li>
<li id="demo1">Click me -> click event.</li>
<li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
</ul>
<div id="myresult"> </div>
</body>
</html>
If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '
Source: Stackoverflow.com