Question

I have an output number of elements that are randomly generated and put into an isotope horizontal scroll, I wish to have the second row that will have a height 50% from the top have a different overlay colour.

I've got this far but it doesn't seem to work and I couldn't find anything similar on Stack Overflow.

$(function(){
    if ( parseInt($('.item').css('top'), 10) < 1 ) {        
        $(this).find('.overlay').css('background','#ff3366');
    }
    if ( parseInt($('.item').css('top'), 10) > 1 ) {
        $(this).find('.overlay').css('background','#0099ff');
    }  
});

JSFiddle example quickly put together to give an idea? http://jsfiddle.net/6tRwV/ If you could kindly assist me in making this work I will be very grateful.

Was it helpful?

Solution

You basically need to loop over all the .item elements and do pretty much the logic you had already.

$(function(){
    $('.item').each(function(){
        var $item = $(this);
        var top = parseInt($item.css('top'),10);
        if ( top < 1 ) {        
            $item.find('.overlay').css('background','#ff3366');
        }
        if ( top > 1 ) {
            $item.find('.overlay').css('background','#0099ff');
        }  
    })

});

JsFiddle: http://jsfiddle.net/6tRwV/2/

as with all things jQuery, there is usually a shorter way:

$(function(){
    $('.overlay').css('background',function(){
        var top = parseInt($(this).parent().css('top'),10);
        return top<1 ? '#ff3366' : '#0099ff';
    });
});

jsFiddle: http://jsfiddle.net/6tRwV/3/

OTHER TIPS

Use:

$('div.item').each(function(){
    if (parseInt($(this).css('top'), 10) < 1) {
        $(this).find('.overlay').css('background', '#ff3366');
    }
    if (parseInt($(this).css('top'), 10) > 1) {
        $(this).find('.overlay').css('background', '#0099ff');
    }
});

jsFiddle example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top