Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery prevent removing class if first or last child?

Tags:

jquery

I have a class 'active' that is constantly being removed and added to other divs. But I don't want it removed if it is applied to a first or last child...

JSFiddle: http://jsfiddle.net/YuDDK/1/

HTML:

<div id="container">
<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>

JS:

$('#container').mousewheel(function(event, delta) {
    var active = $('.active');

    if (delta > 0) {
        if (active.not(":first-child")) {
            active.removeClass('active').prev().addClass('active');
        }

    } else {
        if (active.not(":last-child")) {
            active.removeClass('active').next().addClass('active');
        }
    }

    $(this).scrollTo( $('.active'),100);
    return false;
});
like image 961
Nathan Waters Avatar asked Dec 15 '25 06:12

Nathan Waters


1 Answers

active.not(":first-child") returns a jQuery object which is always true, you can use is method instead that returns a boolean value.

if ( !active.is(":first-child") )
like image 177
undefined Avatar answered Dec 16 '25 22:12

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!