Dobob Dobob - 4 months ago 11
CSS Question

How would you separate the Javascript for modals from the html?

I am learning HTML and CSS with Javascript. I am currently trying to separate the Javascript code from the html file for modal pop-up functionality. I haven't learned jquery yet, so if there is a way to solve this without it, it would be greatly appreciated.

The complete code can be found here: http://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img

HTML code:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="modal.css">
<script type="text/javascript" src="modal.js" ></script>
</head>
<body>
<h2>Image Modal</h2>
<img id="myImg" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">

<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>

</body>
</html>


External Javascript code:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}


The above method doesn't work. When I click on the picture, there is no modal pop-up. I am guessing simply linking the script is not enough, but I am not fluent enough in the language to solve this.

Answer

you can put your script tag inside the body.like this.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="modal.css">
</head>
<body>
    <h2>Image Modal</h2>
    <img id="myImg" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">

    <!-- The Modal -->
    <div id="myModal" class="modal">
        <span class="close">×</span>
        <img class="modal-content" id="img01">
        <div id="caption"></div>
    </div>
    <script src="your url"></script>
</body>
</html>
Comments