The problem with which you are finding is that the button is not yet loaded in the DOM when the javascript is executed.
In the jsFiddle that was provided in the comment this does not happen, since jsFiddle is already responsible for loading the javascript in the corresponding event.
There are many ways to get the code executed when the DOM has finished loading.
Put the code at the end of the body.
We reverse the order and put the script tag at the end of the body tag:
<html>
<head>
<style type="text/css">
#boton{
width: 50px;
height: 30px;
display: block;
margin:30px;
}
img{
width: 300px;
height: 200px;
margin:30px;
}
</style>
</head>
<body>
<button id="boton">Click</button>
<img src="header.jpg" id="foto">
<script type="text/javascript">
var boton = document.getElementById('boton');
boton.onclick = function(){
var imagen = document.getElementById('foto');
imagen.style.display ='none';
}
</script>
</body>
</html>
We use the event 'DOMContentLoaded' of object document
:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var boton = document.getElementById('boton');
boton.onclick = function(){
var imagen = document.getElementById('foto');
imagen.style.display ='none';
}
}, false);
</script>
We use the 'load' event of object window
:
<script type="text/javascript">
window.addEventListener('load', function() {
var boton = document.getElementById('boton');
boton.onclick = function(){
var imagen = document.getElementById('foto');
imagen.style.display ='none';
}
}, false);
</script>
U
let's see the 'onreadystatechange' event of object document
:
<script type="text/javascript">
document.attachEvent('load', function() {
var boton = document.getElementById('boton');
boton.onclick = function(){
var imagen = document.getElementById('foto');
imagen.style.display ='none';
}
});
</script>
We use the 'onload' event of object window
:
<script type="text/javascript">
window.attachEvent('onload', function() {
var boton = document.getElementById('boton');
boton.onclick = function(){
var imagen = document.getElementById('foto');
imagen.style.display ='none';
}
});
</script>
Why are there so many events and so many possibilities? Is not that something more confusing?
The main reason is due to a compatibility issue. For example DOMContentLoaded
is the event that is most widespread, but nevertheless it does not work in IE8 and earlier.