I really don't know why this isn't working. In my HTML, if I put my script in the head section, I get the following error in my console:
Uncaught TypeError: Cannot read property 'addEventListener' of null
If I put my script in the bottom part of the body, it's working fine.
HTML :
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"> </script>
</head>
<body>
<ul>
<li><a href="#" data-img="img1" id="img1"> Shahin </a></li>
<li><a href="#" data-img="img2" id="img2"> Lina </a></li>
<li><a href="#" data-img="img3" id="img3"> Adrita </a></li>
</ul>
<img src="./img/1.jpg" class="hidden">
<img src="./img/2.png" class="hidden">
<img src="./img/3.jpg" class="hidden">
</body>
JavaScript :
var shahin = document.getElementById('img1');
var lina = document.getElementById('img2');
var adrita = document.getElementById("img3");
shahin.addEventListener('click',picShow);
lina.addEventListener('click',picShow);
adrita.addEventListener('click',picShow);
function picShow() {
console.log(this);
}
Can anybody tell me what I'm doing wrong and where is the proper place to put the script tag? Also, what change should I make to run my script from head section? I will be glad for your answer. Thanks in advance
Your script is loading and being executed prior to the rest of the body HTML, so naturally, document.getElementById is going to return null.
You should be running your event listener subscription code on or after the document.ready event.
Wrap the code you posted into a JS function, then set that function as the callback to be executed on document.ready:
document.addEventListener('load', initFn);
<script type="text/javascript" defer src="script.js"> </script>
Add key word defer, script runs when all DOM elements will loaded
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