I wrote an answer for this question: New background according to url, the code I posted in my answer was to check a URL for the presence of a particular string and, if it was there, change the background-image of a given element.
So! Me being me, I thought I’d try and avoid jQuery and go for a more traditional vanilla JavaScript approach with the following:
var images = {
'halloween' : '/images/newbackground.jpg',
'christmas' : '/images/xmasbackground.jpg'
};
var url = document.location.href,
elem = document.getElementById('elementThatYouWantToStyle');
for (var keyword in images){
if (images.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
elem.style.backgroundImage = images[keyword];
}
}
Which I then thought I’d convert to a functional approach, so it became this:
var images = {
'halloween': 'http://davidrhysthomas.co.uk/img/dexter.png',
'christmas': 'http://davidrhysthomas.co.uk/img/mandark.png'
};
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
var url = url || document.location.href,
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = encodeURIComponent(map[keyword]);
}
}
}
}
setBG('one', images, 'http://some.domain.com/with/halloween.jpg');
setBG(document.getElementById('two'), images, 'http://some.domain.com/with/christmas.jpg');
Now, if I add a console.log() to the if assessment within the for...in loop it shows that we’re getting into the loop, and the console suggests that I have an accurate reference to the DOM node, the images object, the URL (as passed into the function) and am getting the correct value from the object.
The following line, however, in which I attempt to set the el.style.backgroundImage property, does not work (this is true whether or not I wrap the map[keyword] in the encodeURIComponent() or not albeit I’ve linked only to the attempt in which I did. So: what’s the obvious flaw in my logic? Why is el.style.backgroundImage not being set?
(Incidentally JS Lint, at JS Fiddle, seems happy with it (other than the redefinition of existing variables (url and el) done in order to have a fall-back/default).
You are declaring a local variable
urlwithvar urlthat already defined as an argumenturland you also need to use the formurl(http:/xxxx).Change to this (removed
varin front ofurland added theurl()around the url):