My current project involves the following tasks:
- When the window's width is less than 700px and a user clicks on the gray bar at the bottom, a red menu should slide up and remain visible.
- If the window's width exceeds 700px, clicking on the gray bar should have no effect.
To ensure these functionalities work seamlessly even when the window is resized after the page has loaded, I have attached a resize() event listener to the browser window.
If you want to test the behavior yourself, here is the link to my Codepen: http://codepen.io/Chiz/pen/xwrpWG (Please read the instructions below before clicking!)
To replicate a strange issue:
1) Resize your window to less than 700px, then click on the provided Codepen link above (if unsure about the dimensions, simply make it very small).
2) Click on the gray bar at the bottom. You should see a red rectangle sliding up and stopping. Click again to see it slide back down. Repeating this action should cause the red rectangle to slide up and down each time, which is the expected behavior.
3) Now, resize the browser window without reloading the Codepen page. You can make the window wider or narrower - it doesn't matter as long as there is a change in the window size. Click the gray bar again. A bug will appear where the red rectangle slides up and down multiple times!
Sometimes, the number of slides matches the number of resizes! :-O
How can I resolve this issue?
//bind click event to the gray bar on page's first load
showMenuIfWidthSmallerThanSevenHundred();
//detect window resizes
$(window).resize(function() {
showMenuIfWidthSmallerThanSevenHundred();
});
function showMenuIfWidthSmallerThanSevenHundred() {
if ($(window).innerWidth() <= 700) {
$("div").on("click", function() {
/* make menu fill the entire screen that is
not occupied by the gray bar */
var nMenuHeight = $(window).height() - $(this).height();
$(".menu").height(nMenuHeight);
/* position the menu so that the bottom of the menu
touches the top of the gray bar */
$(".menu").css("bottom", $(this).height());
//make menu slide upwards / downwards
$(".menu").slideToggle();
});
}
}
div {
width: 100%;
height: 53px;
background-color: gray;
position: absolute;
bottom: 0;
}
.menu {
width: 100%;
height: 100px;
background-color: #F08080;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div class="menu"></div>