Setting Element Styles with JavaScript

Since I couldn’t figure out a pure CSS method to perform the rollover effect on the navigation menus, I used JavaScript instead. Besides, it’s much more simple and easier to maintain, rather than a complex mangle of CSS. So to change the curved image from green to pink, I used something like the following to change the CSS background properties:


function naviOver(e) {
	gE('active').style.background = "url(Images/pink.png) top right no-repeat";
}

It worked of course, but I was late to realize that it worked only on the home page, with the rollover images in an Images folder located at /jnls (root folder for my blog). I tried using some alert()s to determine whether the background property was set. The result: it works.

So what could be the darn problem be? Next thing on my mind: the bloody images aren’t loading. After some probing, it turns out then when you set an element’s style with JavaScript, the relative path becomes that of the page. For example, for the page /folder/index.htm, url(Images/pic.png) would refer to /folder/Images/pic.png, and NOT where the original CSS file was located (the wordpress themes folder in my case).

Sigh, so that was what’s wrong. So my solution was to create seperate classes for the normal and hover states for the elements concerned, and use JavaScript to change their classes onmouseover.

gE('active').className = "hover";

That pretty much did the trick. Ease of maintenance ensured at the same time!

Note:

function gE(e) { return document.getElementById(e); }

Tags: , ,

Leave a Reply