J82
J82

Reputation: 8457

Only run code if body has class of X?

I want this code to only run if the body has a class of home. So I've created a variable called isHome and I'm trying to wrap the code around it. However, I think there's something wrong with the code. Can someone point out what is wrong?

var isHome = $('body.home');

if (isHome) {
    $('.wp-polls-form input.Buttons').click(function( e ){
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $("#top-section").offset().top - (
              $(window).width() < 450 ? 112 : 60
            )
        }, 500);
    });
}

Upvotes: 1

Views: 1137

Answers (4)

collab-with-tushar-raj
collab-with-tushar-raj

Reputation: 1287

you should try .hasClass() as it returns boolean

   var isHome = $('body').hasClass('home');
   if(isHome) { //your code }

Thanks !!

Upvotes: 0

Amit
Amit

Reputation: 15387

Use as

if($('body').hasClass("home"))

Upvotes: 3

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Use .hasClass() as shown:

var isHome = $('body').hasClass('home');

If body has a class home then $('body').hasClass('home'); statement will return true otherwise false.

Or directly use if($('body').hasClass("home"))

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337580

Your if condition will always be true because a jQuery object, even if it's empty, will equate to true.

Instead, you can use the length property to check if a selector found a match:

var $isHome = $('body.home');
if ($isHome.length) {
    // your code...
}

Or you can use hasClass to check if the element has the required class:

if ($('body').hasClass('home')) {
    // your code...
}

Upvotes: 5

Related Questions