The concept of Modal being undefined

Upon opening my page, I am attempting to create a modal dialog that displays an image. Strangely, I keep receiving an error stating the image is undefined when trying to display it without using the onclick function. I am working with a modified version of a script from W3Schools. Any suggestions on how to fix this issue would be greatly appreciated! Below is the code snippet:

 HTML:                  
    <img id="myImg" src="http://192.185.4.115/~hitclubar/images/prueba.png" alt="" width="300" height="200" style="display:none;">
    <div id="myModal" class="modal">
        <a href="http://facebook.com/Hitclubar">Click Evento Facebook</a>
        <span class="close">×</span>
        <img class="modal-content" id="img01">
        <div id="caption"></div>
    </div> 

Javascript:

// 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");

$(function(){ 
    modal.style.display = "block";
    modalImg.src = document.getElementById('myImg');
    modalImg.alt = "HELLO";
    captionText.innerHTML = "HELLO";
});

// 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";
}

CSS:

#myImg {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

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

.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

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

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

/* Additional CSS styles are included in the provided code */

Answer №1

Your code placement is crucial.

var modal = document.getElementById('myModal');

Moving this line to the beginning of the script causes issues as the modal doesn't exist yet during page load.

Consider reordering your code like this:

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

    // Access the image and display it within the modal, using its "alt" text as a caption
    var img = document.getElementById('myImg');
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption"); 

    modal.style.display = "block";
    modalImg.src = document.getElementById('myImg').src;
    modalImg.alt = "Hello World";
    captionText.innerHTML = "Hello World";
});

This adjustment ensures that the modal is referenced after the page has fully loaded, allowing it to function correctly.

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

Steps to execute a download function in jQuery for retrieving an audio file

I am facing a challenge in creating a download button that should, upon clicking, locate the URL of the current playing song and initiate the download process. However, pressing the button currently opens the file location instead of downloading it. I am a ...

Execute JavaScript script once when route changes

I'm currently working on a system where I want to ensure that my animation-based JavaScript code only runs once after the route changes. The issue I'm facing is that when switching between pages and returning to the about page, the scripts are ca ...

Are there any JS/jQuery plugins available for sliding animations that include slideLeft and slideRight functions, similar to the slideUp and slideDown functions?

Does anyone know of a jQuery/JS plugin that combines fading and sliding effects, specifically with slideLeft and slideRight functions similar to jQuery's slideUp and slideDown? I'm hoping to find something ready-made rather than having to build i ...

Bootstrap Framework 3 causing horizontal scroll due to header styling

Here is the link you requested: This is the HTML Code: <header id="header-10"> </div><!-- /.header-10-top --> <!-- MAIN NAVIGATION --> <div class="header-10-main"> <div class="container"> ...

Can CSS content be used to showcase an .html document or .html fragment?

Referencing the MDN documentation for css content: /* <uri> value */ content: url(http://www.example.com/test.html); Inquiry: Can an image be displayed using the url() value of the content property in a css html element? .content { conte ...

Is sourcing materials globally, whether from a virtual repository or the web's foundation, the best approach?

Imagine having an MVC/WebAPI/AngularJS website running locally at localhost/Test/ and wanting to move it to www.test.com During the local setup, there are numerous references to directories (such as jsfiles) in the format below (found in JS or HTML fil ...

Is there a way to incorporate Actions into the tool-bar on the Dashboard of Jupyter Notebook?

I am currently in the process of developing a customized front-end extension for Jupyter Notebook. I plan to have buttons on both the Notebook Dashboard and Editor that will trigger various actions. Similar to the existing "Move" and "Duplicate" buttons, ...

Recording setInterval data in the console will display each number leading up to the current count

Currently, I am developing a progress bar that updates based on a counter over time. To achieve this, I opted to utilize a setInterval function which would update the counter every second, subsequently updating the progress bar. However, I encountered an ...

Counting Slides in a Slick Carousel

I am currently working with the slick carousel in React.js using ES6 and I'm having trouble getting the slide count. In my function, I can successfully retrieve the count inside the event listener but outside it returns null. Can someone point out wha ...

What is the best way to align a div and two buttons with respect to an image within an li element?

I am trying to adjust the positioning of text on top of an image with a 40px margin. Additionally, I want to place two buttons on each side of the list item (one on the right and one on the left). Despite numerous attempts with various solutions, including ...

Is it normal for the section height to disappear when a container within a <section> is floated left?

I need help creating a website section with 3 containers aligned horizontally and a footer. The containers are labeled with the class "box" and the footer is simply referred to as <footer>. The containers are nested within a section with the id "box ...

Determine the number of distinct property values within a JSON API response

Running on a Ruby on Rails backend, I have a JSON API that serves an array of objects with the following structure: { "title_slug": "16-gaijin-games-bittrip-beat-linux-tar-gz", "platform": "Linux", "format": ".tar.gz", "title": "BIT.TRIP BEAT", ...

Creating a hierarchical structure for the Category Model in Sequelize using self-referencing

My database has a Category Table that uses a "parent" column: +----+--------------+--------+ | id | name | parent | +----+--------------+--------+ | 1 | Service | null | | 2 | Lifestyle | null | | 3 | Food & Drink | 2 | | ...

Learning to implement Angular's two-way binding with the directionsService.route() function in Google Maps

Check out my Angular Component export class MapsComponent implements OnInit { @ViewChild('googleMap') gmapElement: any; map: google.maps.Map; data = "initialized"; ngOnInit() { var directionsService = new google.maps.DirectionsSe ...

Learn how to implement RSS into your Next.js MDX Blog by integrating the `rss` module for Node JS. Discover the process of converting MDX content to HTML effortlessly

Having trouble converting MDX to HTML at the moment. This task is for Tailwind Blog You can find the complete code on Github here → https://github.com/tailwindlabs/blog.tailwindcss.com Below is the relevant code snippet: scripts/build-rss.js import fs ...

Which file type is universally compatible with the majority of web browsers?

After adding an mp3 audio file to my website, I noticed that it may not be supported by some browsers or Operating Systems due to its format. What is the most widely supported audio format by browsers so I can convert my audio to that? ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Tips for resolving rendering page issues in an express app

My application is a straightforward blog platform that showcases a schema for the title, entry, and date of each blog post. There is also an edit/delete feature that is currently under development. When attempting to use the edit/delete button on a selecte ...

Unique lightbox effect with multiple layers

Currently, I am working on implementing a lightbox effect to showcase images to the user using a GridView. Upon clicking an image, a new layer should appear above the current page displaying a larger version of the image along with some description. Althou ...

Internet Explorer Failing to Capture Blur Event (jQuery)

After doing a rapid search, I couldn't find an exact solution to this issue (I'm sure it has been addressed before), but I really need to get to the bottom of this... Does anyone have any insight into why this code snippet doesn't function ...