Reputation: 2282
I need to call a function when a window is resized below the 400px breakpoint. The obvious solution to handle this would be to watch the window.resize()
event like this:
Window.Resize Solution
script:
$(window).resize(function(){
if($(window).width() < 400)
console.log("trigger");
});
However this triggers continuously as the resize happens, this can result in hundreds of calls on this function, and will trigger at unncessary times like resizing from 300px to 200px;
While trying to find a way to avoid this I came up with a solution using CSS media queries:
CSS Media Query Solution
script:
$(".foo").on('transitionend', function () {
console.log("trigger")
});
css:
.foo
{
width: 0;
height: 0;
color: white;
transition: 0.1s;
}
@media screen and (max-width: 400px) {
.foo {
color: gray;
}
}
The idea here is that the CSS watches for the window to resize to 400px then applies an arbitrary transition to an invisible element. Once done, the transitionend
event is fired and the listener calls on my function. This only happens once when the screen goes below 400px and once when it goes back above.
Now of course there are pitfalls to this solution:
But other than those downfalls I was wondering if this method would be more efficient/better use if you want to avoid the continuous calls. Or is the underlying implementation of media queries doing more work than the resize event would anyway.
Upvotes: 0
Views: 1230
Reputation: 17350
I think your main complication is splitting the code over so many places. Yes, CSS is nice and all, but now your code is reliant on two places! The easiest way to sort this is to simply store your value in JS:
var isSmall = false;
$(window).resize(function(){
if(
(window.innerWidth < 400 && !isSmall) ||
(window.innerWidth > 400 && isSmall)
){
console.log('we have passed the treshold!');
isSmall = !isSmall;
}
}).resize();
I guess using the CSS transitionend
would work, but it seems so cumbersome to keep in sync.
Upvotes: 0