lolio lolio - 9 months ago 33
CSS Question

how to fire window.resize only once?

Here is my code;



$(window).resize(function() {
if ($(window).width() >= 760) {
$('.sidebar-left').one().css("display", "block")
} else if ($(window).width() <= 760) {
$('.sidebar-left').one().css("display", "none")

}

});

var m = $(".menu");

m.addClass('fa-bars');

m.on('click', function() {
if (m.hasClass('fa-bars')) {
m
.removeClass('fa-bars')
.addClass('fa-times');
$(".sidebar-left").css("display", "block")
} else {
m
.removeClass('fa-times')
.addClass('fa-bars');
$(".sidebar-left").css("display", "none")

}
});

.sidebar-left {
width: 100px;
position: fixed;
background-color: black;
height: 100%;
}
.menu.fa {
display: none;
}
@media handheld,
screen and (max-width: 760px) {
.sidebar-left {
display: none;
width: 100%;
background-color: black;
height: 100px;
}
.menu.fa {
display: inline-block;
font-size: 35px;
color: black;
}
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu fa"></div>
<div class="sidebar-left"></div>





And a plunk. (may be easier to test here)

So it's just a simple menu. The issue I have is that currently the resize event will run every time the page is resized, so if I have the menu displayed under 760 pixels it will automatically disappear on resize if I have it opened.

If I take the javascript resize function out completely and leave it to the css, the problem is if I open and close the menu in a smaller window, the display will be set to none when I make the window larger again.

I've tried a few other things, but can't seem to think of a way of doing this. The aim is to just to replicate what the $(window).resize function is doing currently, but for that event to fire only once the window has resized past the points.

Hope the problem is explained clearly.

Thanks

Answer

You could use jQuery's one() method, which gets activated exactly once:

$(window).one('resize', function() {
  if ($(window).width() >= 760) {
    $('.sidebar-left').one().css("display", "block")
  } else if ($(window).width() <= 760) {
    $('.sidebar-left').one().css("display", "none")

  }

});

This will solve your question as asked, but i would actually recommend not disabling the resize event and just handling it better, i.e. checking whether it is proper to open/close the sidebar.