Alert: JavaScript beginner here.
<!DOCTYPE HTML>
<html>
<head>
<script>
function mostraralerta() {
alert("you've clicked!");
}
function hacerclic() {
document.getElementById("boton").onClick = function(){
mostraralerta();
};
}
window.onLoad=hacerclic();
</script>
</head>
<body>
<input type="button" id="boton" value="click">
</body>
</html>
When you click on the input it doesn't shows the alert. If I remove the anonymous function and do it directly:
document.getElementById("boton").onClick = mostraralerta();
or with another selector:
document.querySelector("#boton").onClick = mostraralerta();
It shows the alert as soon as you open the webpage, instead of when clicking the button.
Also I have tried with another html tag instead of an input, but the only way I have made this code to works is to put directly the event onClick on the input, but I'd like to know how to make it works with the functions and onload.
document.getElementById("boton")return undefined here since your button is not yet in the DOM