Differences in Behavior of jQuery Element Styles in Firefox and Chrome When Modals Are Visible

I'm new to working with jQuery and JavaScript. Currently, on my website, I have implemented several unique modal/popups that are activated using a CSS :target selector, which changes their display property to block. Additionally, I am attempting to use jQuery to hide a separate element based on certain conditions.

The scenario is as follows: If a modal is visible, then the element should be hidden. Otherwise, it should be shown. To handle this functionality, I am utilizing the popstate event in my jQuery code. This ensures that the modals can also close when the user navigates back using the browser's back button, without relying on click events. Most aspects of my implementation are functioning correctly; however, I've noticed an issue with the if/else statements detecting modal visibility behaving differently between Firefox and Chrome browsers. In Firefox, the element appears when it should be hidden, while in Chrome, it disappears when it should show. Why is this opposite behavior occurring, and how can I rectify it?

$(window).on('popstate', function(event) {
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});
.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="extra_element">This element should hide when modal is open</div>

<div>
  <a href="#content">Click Me To Open Modal</a>
  <div id="content" class="modal">I'm a Modal. Press browser back button to close 
  </div>
</div>

Alternate jQuery:

When setting length to 1, the code works correctly in Firefox but behaves oppositely in Chrome.
When setting length to 0, it functions properly in Chrome but exhibits different behavior in Firefox.

$(window).on('popstate', function(event) {
    if ( $('.modal-overlay:visible').length === 1 ) {
        console.log("Modal ON");
        $('#wrapper').css('overflow-y', 'hidden');
        $('#extra_element').css('display', 'none');
    }
    else {
        console.log("Modal OFF");
        $('#wrapper').css('overflow-y', 'scroll');
        $('#extra_element').css('display', 'block');
    }
});

Are there any alternative approaches to address this issue accurately?

Answer №1

It appears that there is a bug in Chrome related to the handling of fragments according to the specifications. During step 10 of the History traversal algorithm, Chrome should call the "scroll to fragment" algorithm to update the document's target element (:target). However, instead of following this order, Chrome fires the popstate event before updating the target element, causing issues with CSS selectors like :target. I have already reported this issue here for resolution.

To work around this problem until it is fixed, you can add a short delay after the event is triggered:

$(window).on('popstate', async function(event) {
  await new Promise(res => setTimeout(() => res()));
  if ($('.modal').is(':visible')) {
    console.log("Modal ON");
    $('#wrapper').css('overflow-y', 'hidden');
    $('#extra_element').css('display', 'none');
  } else {
    console.log("Modal OFF");
    $('#wrapper').css('overflow-y', 'scroll');
    $('#extra_element').css('display', 'block');
  }
});
.modal {
  display: none;
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto;
}

.modal:target {
  display: block;
}

#extra_element {
  width: 100vw;
  height: 20vh;
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="extra_element">This element should hide when modal is open</div>

<div>
  <a href="#content">Click Me To Open Modal</a>
  <div id="content" class="modal">Press browser back button to close
  </div>
</div>

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

Limit the maximum column gap on the grid and stop it from expanding further

I'm currently facing an issue with some columns/rows on my website that are keeping content locked in the top left corner, reminiscent of early 00's web design. The site was originally designed for smaller screens like 1024x764, so when viewed on ...

Are the links drifting to the left?

Some of the links on my website seem to be misbehaving and not following the CSS rules, floating to the left unexpectedly. Strangely, it's only the links that are affected; the rest of the text appears fine. For example, you can observe this issue at ...

Tips for creating a responsive div that contains both an image and description, including automatically resizing the image to fit the

#content { background-color: #ACAE4C; float: right; display: inline-block; padding: 0; } <div id="content"> <div class="pic"></div> <div class="desc"></div> </div> I need assistan ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

CSS: using syntax to target element by its unique identifier

Check out this guide: I followed the instructions and used an external stylesheet. I added #menu before each CSS item, for example: #menu ul{ font-family: Arial, Verdana; font-size: 14px; margin: 0; padding: 0; list-style: none;} or: #menu ul li{ displ ...

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

Loading MySQL data into different div compartments using AJAX

Apologies for creating this topic, I tried searching for the answer but couldn't find the solution. Currently, I am fetching data from MySQL using AJAX and it's working fine with one div. However, I'm having trouble loading each variable in ...

Adjusting canvas context position after resizing

I've been experimenting with using a canvas as a texture in three.js. Since three.js requires textures to have dimensions that are powers of two, I initially set the canvas width and height to [512, 512]. However, I want the final canvas to have non-p ...

alerting the user of any modifications made to a table within the database

In my current Spring project, I am seeking the optimal solution to improve system performance. Should I implement a solution using Javascript or create a custom method in Java? ...

CommentsController#new encountered a NoMethodError due to an undefined method called 'text' for the Comment with the following attributes: id: nil, author: nil, created_at: nil, updated_at: nil

I'm currently integrating rails with react to include a comments section in the app I am developing. While the /comments page is functional, I encountered an error when attempting to create a new comment. Despite consulting the guide I am following, t ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

Ways to improve the quality of a blurred photo

I've recently put together a test landing page using bootstrap: Upon visiting the site and viewing the iPhone screenshot, it's clear that the text on the screen is quite blurry. Interestingly, by simply resizing the browser window and then maxi ...

Looking for assistance with JQuery and JavaScript?

I oversee a team of employees, each with a 7-day work schedule. To streamline the process, I have developed a PHP form that I would like to use to collect data for verification in JavaScript before submitting it to an SQL database using AJAX. My main cha ...

Tips for removing the download prompt in Firefox when using Selenium in Typescript

While attempting to download a file in Firefox, a download dialog box pops up. I am looking to disable the download dialog box specifically for zip files so that they are downloaded automatically. Despite trying various preferences settings, the dialog box ...

Removing the currently selected item from the OwlCarousel

I am trying to enable users to delete the item that is currently active or centered in an OwlCarousel. I have come across some code related to deleting items, but it seems to be a rare question: $(".owl-carousel").trigger('remove.owl.carous ...

Django static files reference

sample code snippet tooltip reference navigating to the correct file path FILES: settings.py STATICFILES_DIRS = [ BASE_DIR / "static" , ] base.html {% load static %} How can I properly link my static files in the html line below?... &l ...

Why use getElementById(id) to obtain an element in JavaScript when it already exists in the JS?

Recently, I have observed that a reference to an HTML element with an id can be easily accessed in JavaScript by using a variable named after that id (jsbin). What is the reason for this behavior? Why do we need to use getElementById(id) when we could sim ...

Get rid of the drop-down shadow effect

Currently working on a website project for a client and looking to remove the blue "shadow" effect from the dropdown menus. I believe the code that needs editing is as shown below: .main_nav ul.sub-menu { position: absolute; top: 65px; width: ...

Creating a dropdown menu in Bootstrap 4 using JSON information

I am trying to create a dynamic drop-down menu using an input field with a drop-down button inside a form. Currently, I am attempting to populate the drop-down menu with static JSON data. However, I am encountering issues with getting it to function proper ...

Looking to retrieve a specific portion of HTML data returned from an AJAX request

Looking to extract specific HTML content from the response received from an ajax call made to the controller. This task will involve utilizing an ID reference. I am encountering difficulty in employing the find function directly on the data as it is curre ...