Reputation: 189
I want to use some jquery but only on smaller screens, like mobile, and also when user resizes the browser. If I use resize function the code works only on resize, if I use code on its own, it work only on page load, how to combine the two? (I am using css class rather than checking the window size in my condition as I found it works better)
$(window).resize(function(){
if ($(".sampleClass").css("float") == "none" ){
$('#nav').slideToggle();
}
});
Also there is small problem that when the toggle is in this conditional, then it animates constantly and doesn't want to stop. If I just place it without the condition and resize function, it works like a charm. What am I missing here?
if ($(".sampleClass").css("float") == "none" ){
$('#nav').slideToggle();
}
Upvotes: 0
Views: 370
Reputation: 11
i would call the function twice: - when the DOM is fully loaded - inside a resize function
concerning your animation problem: just call a new function after the resize event has finished, e.g. 500 ms later.
$(function(){
if ($(".sampleClass").css("float") == "none" ){
$('#nav').slideToggle();
}
var myVar;
function myNewFunction(){
if ($(".sampleClass").css("float") == "none" ){
$('#nav').slideToggle();
}
}
window.onresize = function() {
clearTimeout(myVar);
myVar = setTimeout(function() {
myNewFunction();
}, 500);
};
});
Upvotes: 1
Reputation: 9262
As guest271314 suggests in their comment, you can attach an event handler to multiple events by specifying a space-separated list of event names in your call to on
. http://api.jquery.com/on/
As far as the repeated animation goes, it's possible that your animation is actually resizing the document view (since it's sliding content into and out of view), which triggers another resize event, which triggers another animation, and so on.
If that's the case, either adjust your layout and animation so that the slideToggle()
call doesn't resize your content, or consider another solution.
Upvotes: 0