The Div overlay vanishes once the Javascript function is finished running

Initially, take a look at this fiddle: http://jsfiddle.net/ribbs2521/Q7C3m/1/

My attempt to run JS on the fiddle has been unsuccessful, but all my code is present there, so we should be fine.

I was creating my own custom image viewer, and everything was going smoothly until I tried to incorporate PREV and NEXT functionalities (in the fiddle, they are text but should be images). When I click on next, the picture in the viewer changes, but then my overlay div disappears.

I can confirm that the picture actually changes because if I add an alert at the end of prevImage() and/or nextImage(), I can see the updated picture. However, once I click OK, everything disappears.

I'm not sure what's causing this issue. It could be my JS or CSS causing the problem, as I'm relatively new to JS, CSS, and HTML.

Could someone explain why my div disappears after this function is executed?

Below is the JS code:

var images = Array();
var cursor = 0;

function showHide(obj) {
    alert("Working");
    var overlay = document.getElementById("ImgOverlay");
    if (obj instanceof HTMLImageElement) {
        var gallery = document.getElementById("gallery");
        images = gallery.getElementsByTagName("img");
        cursor = -1;
        while (images[++cursor].src != obj.src) {}

        putImageInViewer(obj);
        overlay.style.display = "block";

    } else if (overlay.style.display !== "none" && overlay.style.display !== "") {
        hideElement(overlay);
    }
}

function hideElement(element) {
    element.style.display = "none";
}

function putImageInViewer(obj) {
    var img = new Image();
    img.src = obj.src;
    var size = 600;
    var h = img.height;
    var w = img.width;
    
    if (h <= 600 && w <= 600) {
        if (h > w) {
            size = h;
        } else {
            size = w;
        }
    }
    if (h > w) {
        document.getElementById("overlay-img").innerHTML = "<img src=\"" + img.src + "\" height=\"" + size + "\">";
    } else {
        document.getElementById("overlay-img").innerHTML = "<img src=\"" + img.src + "\" width=\"" + size + "\">";
    }
}

function nextImage() {
    if (cursor < images.length) {
        cursor++;
    } else {
        cursor = 0;
    }
    putImageInViewer(images[cursor]);
}

function prevImage() {
    if (cursor > 0) {
        cursor--;
    } else {
        cursor = images.length;
    }
    putImageInViewer(images[cursor]);
}

Here is the CSS:

#wrap {
    margin: 0 auto;
}
#wrap li {
    float:left;
    position:relative;
    display:inline-block;
    width:240px;
    height:240px;
    margin:10px;
    padding:10px;
    background:#fff;
    box-shadow:0 0 5px rgba(0, 0, 0, .35);
    overflow: hidden;
}
#wrap li div {
    position:absolute;
    height:0;
    width:220px;
    background:rgba(0, 0, 0, .45);
    overflow:hidden;
    bottom:10px;
    left:10px;
    padding: 0 10px;
    line-height:50px;
    color:#fff;
    transition:height 1s;
}
#wrap li:hover div {
    height:50px;
}
#wrap li img {
    width: 240px;
    height: 240px;
    margin: 0px 0 0 0px;
    cursor: pointer;
}
#ImgOverlay {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.6);
    display: none;
}
#imgnav {
    position: fixed;
    top: 38%;
    left: 50%;
    margin: -15px 0 0 -363px;
    width: 730px;
    height: 60px;
}
#overlay-img {
    position: fixed;
    top: 50%;
    left: 50%;
    margin: -300px 0 0 -300px;
    width: 600px;
    height: 600px;
}
#overlay-img img {
    border: 2px solid white;
    display: block;
    margin: auto;
}

Lastly, the HTML code:

<div id="wrap">
    <h1>An Image Gallery</h1>
    <ul id="gallery">
        <li>
            <img src="w" onclick="showHide(this);">
            <div>Image 1</div>
        </li>
        <li>
            <img src="w" onclick="showHide(this);">
            <div>Image 2</div>
        </li>
    </ul>
    <div id="clear"></div>
</div>

<div id="ImgOverlay" onclick="showHide(this);">
    <div id="imgnav"> <span style="color: white; cursor: pointer; float: left" height="60px" width="60px" onclick="prevImage();">PREV</span>
        <div id="overlay-img">
            
        </div>  <span style="color: white; cursor: pointer; float: left" height="60px" width="60px" onclick="prevImage();">NEXT</span>

    </div>
</div>

Answer №1

It seems like your issue may be related to JavaScript event propagation. Essentially, events that are triggered on DOM elements (like the "click" event on your "PREV" and "NEXT" buttons) propagate up the DOM tree, triggering again on each parent element. So, when you click the "NEXT" button, it first triggers prevImage() and then as the event bubbles up to ImgOverlay, it triggers showHide(this).

To fix this, you'll need to adjust your event handlers to stop the event from propagating further. Change your button markup to something similar to the following:

<span id="nextButton" style="color: white; cursor: pointer; float: left" height="60px" width="60px">NEXT</span>

Then, use the following code to handle the click event:

var nextButton = document.getElementById('nextButton');
nextButton.onclick = function (ev) {
  nextImage();

  if (!ev) {
    // Older versions of Internet Explorer may not pass the event to handlers.
    ev = window.event;
  }
  ev.cancelBubble = true;
  if (ev.stopPropagation) {
    // W3C standard, supported in Chrome, Firefox, Safari, etc.
    ev.stopPropagation();
  }
};

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

The spacing between elements in Flexbox is too excessive, creating an overly wide gap

How can I maintain a fixed 40 pixel gap between columns in flexbox without it increasing as the screen width widens? (I apologize for the brevity of this description, but there are no additional details to provide at this time) .browser-box { max-wid ...

What is a more efficient way to avoid duplicating code in javascript?

Is there a way to avoid repeating the same code for different feeds? I have 8 feeds that I would like to use and currently, I am just incrementing variable names and feed URLs. <script type="text/javascript> function showFeed(data, content ...

Utilizing CSS float with dynamic height

Is there a way to achieve height:auto; for a parent element even when child elements are using float:left; or float:right? Solution for the Parent Element: #parent { width:100px; height:auto; padding-bottom:10px; background:#0F0; ...

What is preventing me from successfully sending form data using axios?

I've encountered an issue while consuming an API that requires a filter series to be sent within a formData. When I test it with Postman, everything works smoothly. I also tried using other libraries and had no problems. However, when attempting to do ...

What sets the Test Deployment and Actual Deployment apart from each other?

I have been developing a web application using Google App Script and I currently have multiple versions of the same web app with various fields. Interestingly, when I run one version through a test deployment, it displays correctly as expected based on th ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

An issue arose upon scanning the QR code for whatsapp-web.js, indicating a potential

My WhatsApp web bot encountered issues this week. C:\pinkmeupwabot\node_modules\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:221 throw new Error('Eval ...

Tips for recognizing the div element housing the selected text chosen by the user

I am currently working on a feature that enables placing a button next to the text selected by the user. Here's what I want to achieve: However, I would like this functionality to apply only when the selected text is inside divs with the class floatb ...

Is it possible to trigger a modal to open automatically after a 3-second delay?

code: <script> $(document).ready(function() { setInterval(function() { $('#contact').modal(); }, 3000); }); </script> html code: <a href="#contact"><h4><i class="fa f ...

Attempting to retrieve assets from an incorrect directory in a rush

Within my express project, I have encountered an issue when rendering the product route with a specific id. It seems that the assets are attempting to load from /products in the public folder (even though this directory does not exist). However, when I ren ...

Is there a way to retrieve a label's text using their class name within a loop?

I have multiple labels sharing the same classname, each with different text. My goal is to iterate through them and extract the text they contain. Here is the example markup: <label class="mylabel pull-left"> Hello </label> <label class="m ...

Tips for connecting to multiple items in an md-select element from within a directive

Looking to develop a straightforward directive that displays either a textbox or dropdown based on whether an array is provided for the model property on the scope. Any value other than explicitly setting false in the directive markup such as multiple="fa ...

When faced with the scenario of having the hashtag in the href attribute and a browser's back button, it

Hello everyone, I've encountered an issue with the "back" action in my browser. When I click on a link, it takes me to a specific page due to a JavaScript function being called. However, when I hit the back button, it simply removes the "#" from the U ...

Adding spacing breakpoints in Material-UI 5 sx properties

Currently in the process of updating my components to utilize the latest MUI version. I have been converting old classes into the sx props and I find this new styling method to be more readable in my opinion. However, one thing that concerns me is handl ...

Adjustable Greybox Overlay Resizes Window Dimensions

Utilizing greybox on my business website allows users to easily log in and access their accounts. View an example of my site However, when the login or sign up window is activated at the top of the page, the page or window size changes, causing scroll bar ...

Begin by introducing a fresh attribute to a JSON entity

Looking for help with modifying JSON data: var myVar = { "9":"Automotive & Industrial", "1":"Books", "7":"Clothing" }; I need to insert a new element at the beginning of the array, resulting in this: var myVar = { "5":"Electroni ...

ASP.NET CodeBehind Fails to Recognize Changes in TinyMCE Textarea

I have multiple <asp:TextBox TextMode="MultiLine"> elements on a webpage. Initially, I populate them using VB code behind and then convert them into TinyMCE editors with the help of the jQuery TinyMCE plugin. Each text box has an associated button fo ...

Is it possible to modify the icon displayed in an AJax response?

I have a link with an icon inside that I need to change when it is clicked. To achieve this, I attempted to use Ajax in the following manner: HTML <a id="#pl-esong234" class="social-button-song" title="Add in playlist" onclick="addInPlaylistSongs(234, ...

Display an "add to cart" button and a discount image when hovering over

Currently, I am in the process of developing an Online Shopping website using PHP. To enhance the design of my website, I have implemented bootstrap. One specific query I have is how to display an 'add to cart' button and a discount image when a ...

Using JQuery to load a table and inject it with html()

I am looking to populate an HTML table within a specific div element. The HTML code is being loaded using the following jQuery function: $("#table_wrapper").hide(); $.get("<?echo base_url();?>schichtplan/employee_fields/"+plan_id+"true",function(da ...