J82
J82

Reputation: 8457

Is there a way to add a conditional statement within a variable declaration?

I want to add + 450 to var threshold only if the page is body.home. So something like this:

var headHeight = jQuery('#masthead-space').height() + 23; 
var threshold =  jQuery('.PopularTabsWidget').offset().top - headHeight (if body.home) + 450;

jQuery(window).scroll(function () {
    if (jQuery(window).scrollTop() >= threshold)
        jQuery('.PopularTabsWidget').addClass('fixed');
    else
        jQuery('.PopularTabsWidget').removeClass('fixed');
});

Upvotes: 0

Views: 62

Answers (4)

Kiril
Kiril

Reputation: 2963

You may use ternary operation (?:)

var threshold =  jQuery('.PopularTabsWidget').offset().top - headHeight + (jQuery('body').hasClass('home') ? 450 : 0);

If I understand correctly body.home means body element has a CSS class 'home'.

To avoid performance impact use jQuery(document.body)

Upvotes: 1

vivek_nk
vivek_nk

Reputation: 1600

var threshold =  jQuery('.PopularTabsWidget').offset().top - headHeight +(body.home?450:0);

Upvotes: 0

Abdou Tahiri
Abdou Tahiri

Reputation: 4408

try this

var headHeight = jQuery('#masthead-space').height() + 23; 
var threshold =  jQuery('.PopularTabsWidget').offset().top - headHeight + body.home ? 450 : 0 ;

jQuery(window).scroll(function () {
    if (jQuery(window).scrollTop() >= threshold)
        jQuery('.PopularTabsWidget').addClass('fixed');
    else
        jQuery('.PopularTabsWidget').removeClass('fixed');
});

Upvotes: 0

Oliver
Oliver

Reputation: 9002

You could try using conditional/ternary operator:

var headHeight = jQuery('#masthead-space').height() + 23; 
var threshold =  jQuery('.PopularTabsWidget').offset().top - headHeight + (body.home ? 450 : 0);

Upvotes: 1

Related Questions