Jason G.
Jason G.

Reputation: 67

Compound if statement is being ignored in JQuery (Javascript)

I am totally stumped on this. I am putting together a script that checks if two stylesheets are loaded into the head part of a WordPress theme, then load an internal stylesheet only if both external stylesheets are loaded first. But, the final if statement that checks if both external stylesheets "exist" runs as if there is no if statement wrapped around it. In the code, I mention the website where I got this idea from. Below is my code:

jQuery(document).ready(function() {
/* Place smaller widget design behind .widgettitle only on 3-column layout */
/* adapted from http://churchm.ag/dynamically-applying-stylesheets-using-jquery/ */
//templateDir is defined in functions.php and placed into this theme's head tag
var threeColExists = false;

    // check for blue stylesheet with 3-column stylesheets
    var blueExists = false;
    jQuery('link').each(function() {
        if(jQuery(this).attr('href') === 
        templateDir + '/layouts/3-column-right.css' ||
        templateDir + '/layouts/3-column-left.css' ||
        templateDir + '/layouts/3-column-right-magazine.css' ||
        templateDir + '/layouts/3-column-left-magazine.css') {
            threeColExists = true;
        }
        if(jQuery(this).attr('href') === templateDir + '/styles/blue.css') {
            blueExists = true;      
        }
    });

    // This is what is getting executed regardless of whether the two conditions below evaluate to true
    if((threeColExists === true) && (blueExists === true)) {
        jQuery('head').append('<style type="text/css"> .widgettitle { background: url(' + templateDir + '/images/widget-design-smaller-blue.png) bottom left no-repeat #FFFFFF; } </style>');   
    }
});

Upvotes: 0

Views: 513

Answers (1)

jfriend00
jfriend00

Reputation: 707218

You can't do a compound comparision the way you are doing it. It would have to be like this where you spell out each individual equality test:

if(jQuery(this).attr('href') === (templateDir + '/layouts/3-column-right.css') ||
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-left.css') ||
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-right-magazine.css') ||
    jQuery(this).attr('href') === (templateDir + '/layouts/3-column-left-magazine.css')) 

or more efficiently without a jQuery object and without recreating the href value each time:

var href = this.href;
if (href === (templateDir + '/layouts/3-column-right.css') ||
    href === (templateDir + '/layouts/3-column-left.css') ||
    href === (templateDir + '/layouts/3-column-right-magazine.css') ||
    href === (templateDir + '/layouts/3-column-left-magazine.css')) 

or perhaps even this would work to test them all with one regular expression:

if (this.href.match(new RegExp(templateDir + "/layouts/3-column-(right|left)(-magazine)?\\.css$")))

Upvotes: 2

Related Questions