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?