user3684162
user3684162

Reputation: 3

Ask more than one value out of an array in if-statement

I want to change the background-image of a -element depending on several strings in the URL. I could change the background on every single term like "Site1", but I want to have more than one Word. So I tried this:

var urlstring = new Array( "Site1", "Site2", "Site3" ); //When one of these words are in the URL, then change the background.

var imageUrl ="Path to image";

if(window.location.href.indexOf(urlstring) > -1) {
     $('#myelement').css('background-image', 'url(' + imageUrl + ')');
    }

I'm sure there is expert who is laughing about this, but it would be very helpful to get this work (there are more related tasks like this...)

Upvotes: 0

Views: 44

Answers (1)

Dylan
Dylan

Reputation: 1402

Iterate through each element of the array to check if it's within the URL:

urlstring.forEach(function(keyword) {
    if (window.location.href.indexOf(keyword) > -1) {
        // ...
    }
});

Upvotes: 2

Related Questions