Reputation: 45
I'm using Isotope (with Packery) to create some fancy responsive grid on my website. With jQuery I'm trying to get all elements in the first row and give them some styles:
$('.grid .grid-item').filter(function() {
return $(this).css('top') == '0px';
}).css("opacity", "0.5");
On large screens there are two grid-elements in a row. On small screens there is only one. To make my script responsive I've added $windows.on('resize')
around my script.
$(window).on('resize', function(){
$('.grid .grid-item').filter(function() {
return $(this).css('top') == '0px';
}).css("opacity", "0.5");
});
The script works quite fine, but if I resize the screen to get the small-version (grid-items with 100% width) the second grid-item still has the css-property. Is there a way to get rid of the css-style on resize?
Check it out (and resize the screen)!
Upvotes: 0
Views: 251
Reputation: 16184
The problem with the method you have implemented is that Isotope takes time to reposition each .grid-item
, so at the time you are checking for items with a top of 0 they may not have finished moving into their final position.
In addition, you are not resetting the items' opacity so once an item has been given the style it doesn't change back.
And finally, the resize event is called many times during the resize and should be debounced to only actually execute the changes once the resize event has stopped. Something like:
var debouncer;
$(window).on('resize', function(){
clearTimeout(debouncer);
debouncer=setTimeout(function(){
$('.grid .grid-item').css("opacity", "1").filter(function() {
return $(this).css('top') == '0px';
}).css("opacity", "0.5");
},200);
});
https://codepen.io/anon/pen/oYMKRj
So even with the above amends you will struggle to determine which .grid-item
s are at the top unless you wait for Isotope to complete its animation (which is a clue to how we solve this)...
Luckily Isotope and Packery have their own custom events you can listen for. So instead of the above you can just listen for the layoutComplete
event which is triggered (as you might expect) when the layout is completed...
$grid.on('layoutComplete', function(event,items){// when the layout completes
$('.grid .grid-item')// get all grid-items
.css("opacity", "1")// reset their opacity
.filter(function() {// filter to return
return $(this).css('top') == '0px'; // the items with a top of 0
})
.css("opacity", "0.5");//set the opacity of the matched items
});
https://codepen.io/anon/pen/vyzBYy
Upvotes: 1