Shahil Khan
Shahil Khan

Reputation: 11

internal js works fine but external doesnt

JS SNIPPETS

the same code is working internally inside the <script> tag if maintaining same code in external js its not working
var modal = document.getElementById('myModal');
var img = document.getElementById('home2');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
    modal.style.display = "none";
}

Upvotes: 1

Views: 32

Answers (1)

Salman
Salman

Reputation: 333

The reason that there is a difference, In the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit furthe.So Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.

Upvotes: 1

Related Questions