0

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.

4
  • 3
    That code should work fine Commented Sep 5, 2017 at 15:23
  • 1
    Yes, is it a right way to do it. Commented Sep 5, 2017 at 15:24
  • 1
    This code looks fine, please check if you have this class enabled or not. Commented Sep 5, 2017 at 15:25
  • This might be happening because the class existed initially and the window scroll logic got bound at that time. You also have to unbind it when the class is missing Commented Sep 5, 2017 at 15:27

3 Answers 3

2

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}
Sign up to request clarification or add additional context in comments.

1 Comment

Although that's the same as my original code, it worked. I must've had something else clashing. I can't delete the question so I'll just accept this as it's correct
0

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");
}

Comments

0

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');  
        }
    }); 

}

1 Comment

hasClass(".full-screen") will check if the element has the class .full-screen and not if it has the class full-screen. Beside that this would not do what the OP is asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.