Rob
Rob

Reputation: 6380

Check if a class doesn't exist on a page

I'm trying to check if the div .full-screen doesn't exist on a page, is this the right way to do it?

if (!$(".full-screen").length) {

    $(window).scroll(function() {
        if ($(this).scrollTop() < 50) { // this refers to window
            $(".header-container").addClass('transparent-menu');
        } else {
            $(".header-container").removeClass('transparent-menu');  
        }
    }); 

}

The inner function runs regardless even though I know the class doesn't exist on the page.

Upvotes: 0

Views: 1760

Answers (3)

Hossein Oraee
Hossein Oraee

Reputation: 229

if you want your inner function run when class Not Found in your code , you must use

if (!$(".full-screen").length){inner functions}

if you want your inner function run when class Found in your code , you must use

if ($(".full-screen").length){inner functions}

Upvotes: 2

SilverSurfer
SilverSurfer

Reputation: 4365

You can try with hasClass() method over the Document:

if (!$(document).hasClass(".full-screen")) {

    $(window).scroll(function() {
        if ($(this).scrollTop() < 50) { // this refers to window
            $(".header-container").addClass('transparent-menu');
        } else {
            $(".header-container").removeClass('transparent-menu');  
        }
    }); 

}

Upvotes: 0

Abhi
Abhi

Reputation: 4261

Considering a scenario that the class existed and your logic got bound with window scroll event, but when the class is missing, it also needs to unbind, so try like:

if (!$(".full-screen").length) {
  $(window).on("scroll", function() {
    if ($(this).scrollTop() < 50) { // this refers to window
        $(".header-container").addClass('transparent-menu');
    } else {
        $(".header-container").removeClass('transparent-menu');  
    }
  }); 

} else {
    $(window).off("scroll");
}

Upvotes: 0

Related Questions