"Unfortunately, the JavaScript external function failed to function properly, but miraculously the inline function

Struggling to create a fullscreen image modal on the web? I was able to get it working fine when embedding the script directly into my HTML file, but as soon as I moved it to an external JS file, things fell apart. I've double-checked all the variables and everything seems right. The issue might be with the function that displays the modal, but so far, no luck finding a solution. As a JavaScript beginner, any help would be greatly appreciated.

var modal = document.getElementById("myModal");
var img = document.getElementById("image01");
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";
}
.image {
  cursor: pointer;
  transition: 0.3s;
}

.image:hover {
  opacity: 0.7;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0 !important;
  top: 0 !important;
  width: 100% !important;
  height: 100% !important;
  overflow: auto !important;
  background-color: rgb(0, 0, 0) !important;
  background-color: rgba(0, 0, 0, 0.9) !important;
}


/* Modal Content (Image) */

.modal-content {
  margin: auto;
  display: block;
  width: 100% !important;
  max-width: 500px;
}


/* Caption of Modal Image (Image Text) - Same Width as the Image */

#caption {
  margin: auto;
  display: block;
  width: 100%;
  max-width: 500px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}


/* Add Animation - Zoom in the Modal */

.modal-content,
#caption {
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}


/* The Close Button */

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771518180304030516073742594759475a1512031646">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="mb-3 row justify-content-center">
    <div class="col-6 col-md-4 col-lg-3">
      <div class="p-2"><img src="https://dummyimage.com/500" class="img-fluid image" id="image01" alt="Example">
      </div>
    </div>
  </div>
</div>
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

Answer №1

In case this represents the entirety of your HTML document, the inclusion of an external JavaScript file can be done as follows:

<script src="yourjs.js"></script>

Answer №2

Store your JavaScript code in a file named custom.js and include the file at the bottom of your HTML document.

.
.
.
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cac7c7dcdbdcdac9d8e89d8698869885cacddcc999">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="mb-3 row justify-content-center">
    <div class="col-6 col-md-4 col-lg-3">
      <div class="p-2"><img src="https://dummyimage.com/500" class="img-fluid image" id="image01" alt="Example">
      </div>
    </div>
  </div>
</div>
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>

.
.
.
<script src="custom.js"></script>

</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Label dynamically generated from user input for radio button option

In my attempt to develop a radio group component, I encountered an issue where the value of one radio option needs to be dynamically set by an input serving as a label. While I have successfully created similar components before without React, integrating ...

Retrieve text content using jQuery from two different classes

HTML & jQuery Example <div class="box-a">1 <input type="button" value="Click Me" class="btn-click"> </div> <div class="box-a">2 <input type="button" value="Click Me" class="btn-click"> </div> jQuery Script $(".btn-cli ...

WordPress Ignoring PHP Generated Elements When Processing Divs

Whenever I attempt to utilize the get_date function, it seems to disregard all div elements and instead places itself right after the header, at the beginning of the <div class="entry-content">. <div class="entry-content"> May 16, ...

Creating unit tests for linked functions in Node.js using Jest

Hey there! I'm looking to test a function using Jest that involves token verification and requires 3 parameters. Here's the code for the function: const verifyToken = (req, res, next) => { // Checking for token in header or URL parameter ...

What is the best way to achieve a Clamp-To-Border effect on a Texture loaded onto an Image in the THREE.js?

My scene includes a plane with an image loaded onto the texture. I've found that there is no Clamp-To-Border option for textures, only Clamp-To-Edge, Repeat Wrapping, and Mirrored Wrapping. Below is an image displaying the default ClampToEdge effect. ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

The hamburger menu is malfunctioning and spilling over

// App.js import './App.css'; function App() { return ( <div className='navbar'> <label className="hamburger-menu"> <input type="checkbox" /> </label> <div class ...

What is the process of extracting attribute values from child elements in XPath for HTML documents?

Initially, I searched for all the necessary elements, but now I am encountering errors while trying to retrieve attribute values from the child elements - title, URL, and image. What could be the mistake in my approach? function getContent($value) { ...

Is it possible to turn off the shadow on just one side?

Is there a way to remove the shadow in the red area below? I have come across similar questions but unsure how to implement those solutions here. Live Demo: http://jsfiddle.net/xFa9M/ CSS:- #list li{ border: 2px solid black; border-top-width: 1px; borde ...

Retrieve the Data from Input Fields with Matching Classes and Transmit to a Script Using AJAX Request

I am working on a form that includes multiple input fields: <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="date[]" onkeyup="showHint()" /> <input type="text" class="date" name="da ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

Tips for enabling item draggability following AJAX filtering operations

I have a draggable list of names that can be filtered using checkboxes. When a checkbox is checked, an ajax call is made to filter the names. The list is displayed in an accordion format as shown below: <div id="myAccordion"> <?ph ...

Employing delegate for switching roles between classes

I'm having trouble using the jQuery delegate function to toggle classes. What I want to achieve is toggling the class of <li class="unselected-values"> to <li class="<li class="unselected-values"> when the client clicks on the label ...

Adding elements to my state array - Utilizing Nextjs/React/Javascript

After fetching data from 2 different APIs that each return an object, I have stored them in separate states. Now, I want to merge these two objects into a single state that contains both of them as an array. However, when I try to do this, the second obj ...

Having trouble getting PHP to display an image on the webpage

When attempting to output a simple image using PHP, I noticed that it only displayed a white square. This led me to believe that the IMG file could not be found. However, when I used a basic HTML IMG tag, the file was located without any issues. Even try ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

The Vue.js application is experiencing issues with the v-for functionality

I am working on a Vue.js application where I am fetching a list using ajax: $.ajax({ method: 'POST', dataType: 'json', url: this.base_info.url + 'getavailability?token=' + this.token, data: this.search_inf ...

Obtain the location of the image source from a text file within an HTML document

I need to create a slideshow displaying a sequence of images. The path to these images will be stored in a text file. How can I read the image paths from the text file? Currently, I have hardcoded code like the example below: <div class="mySlides fade" ...