Juárez
Juárez

Reputation: 131

Jquery Selector Dynamic IDs and children classes

I'm trying to add some scroll effects (adding classes through jQuery) to some dynamic elements. I only get it to work on the first one (code below), or all of them at the same time (without :first selector).

Is it possible to make it work on all #col-3-XXXX elements and their children only when a unique element is on view?

thank you in advance

jQuery(function() {
    jQuery(window).scroll(function() {
        var scroll = jQuery(window).scrollTop();
        if (scroll >= jQuery('[id^=col3]').offset().top - jQuery(window).height()/2.5) {
            jQuery(".col-left:first").addClass("lefter");
            jQuery(".col-right:first").addClass("righter");
        } else {
            jQuery(".col-left:first").removeClass("lefter");
            jQuery(".col-right:first").removeClass("righter");
        }
    });
});

Upvotes: 0

Views: 89

Answers (1)

alireza yazdandoost
alireza yazdandoost

Reputation: 774

you can use:

jQuery("[attribute^='value']")

it selects elements that their attribute's value starts with value, in your code:

$("[id^='col-3']")

UPDATE:

you have to determine if element is visible, if so apply the classes: this method for checking if an elemnt is in viewport:

$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

Sample usage:

$(window).on('resize scroll', function() {
    if ($('#Something').isInViewport()) {
        // add your classes
    } else {
        // remove old classes
    }
})

UPDATE 2: based on your comments you can do this:

$(window).on('resize scroll', function() {
    $(".col-left").each(function(index) {
        if ($(this).isInViewport()) {
            $(this).addClass("lefter");
        } else {
            $(this).removeClass("lefter");
        }
    });
    $(".col-right").each(function(index) {
        if ($(this).isInViewport()) {
            $(this).addClass("righter");
        } else {
            $(this).removeClass("righter");
        }
    });
});

Upvotes: 1

Related Questions