Can’t seem to get jQuery to change my css.
In my css file this works…
.closed {
background-image: url(http://70.55.103.238/Images/menu-collapsed.gif);
}
I need to be able to change this dynamically with jQuery, so I am calling this in my $(document).ready(function()…
$('.closed').css({ 'background-image' : 'url(http://'+window.location.host+'/Images/menu-collapsed.gif)' });
If it’s not obvious, the reason I need to do this is that I cannot use a relative path to the images folder and the host is not a constant.
First question, why is the jquery call not working? If I put an alert like this…
alert('url(http://'+window.location.host+'/Images/menu-collapsed.gif)')
I can see that the URL is correct, and if I enter the url displayed in the alert directly into the address bar I do get the gif. So I am confident that the URL being passed is correct. I must assume that the css is not getting changed.
Second question, is there any way to dynamically get the host url in the .css file so that I do not have use jquery?
Thanks.
Update:
I tried the following just to make it simple..
CSS…
.closed {
background-image: url(../Images/menu-collapsed.gif);
}
javascript…
$('.closed').css({ 'background-image' : 'url(../Images/menu-expanded.gif)' });
Note that the css is set to use menu-collapsed.gif and the javascript changes it to men-expanded.gif. But the image that is displayed is the menu-collapsed.gif.
Ok I figure this out. I am not sure if this is by design, but I found that I have to reset the css any time I change a class controlled by jQuery css. In my particular case I was setting the image before I had any DOM elements with a class of .closed.
What I actually have is a Tree Menu made up of ul li elements which is created in the $(document).ready(function() with all the nodes of the tree assigned the .closed class. I moved the $(‘.closed’).css() call so that it was executed right after I added the tree to the DOM. and it worked.
The same holds true for the .open class I use for when a user clicks a closed ul. I had to put a $(‘.open’).css call right after I changed the class from .closed to .open. and again right after a change back to closed.
So, if I understand what I am seeing $(‘.closed’).css must not be a persistant change to the css like manually typing it into the script. Am I interpreting this correclty?
If any one is interested here is kind of what my jquery looks like now with the .css() calls where they are working…