Using JavaScript to Add CSS Classes and Listeners

| No Comments | No TrackBacks
I've been doing some refactoring on a website this week, including replacing Javascript that uses the YUI library. The task was to replace YUI with JQuery, if it was needed, but all of the Javascript code was fairly simple, and no external Javascript libraries were necessary. Many of the tasks included adding listeners and adding classes to style the elements. This is easy to do in Javascript.

Obviously, there are a few tricks to get some Javascript to work on different browsers, and multiple-browser testing should not be forgotten. (If it was not for Internet Explorer, I am sure that quite a few developers and testers would be out of a job!)

Take the following code, which adds a class to an element in the HTML page by using the setAttribute function:
document.getElementById("wrapper").setAttribute("class""newClass");

However, this setAttribute function does not work in Internet Explorer, so developers should use the following method instead, which works in all browsers. This example targets the className in the DOM, directly:
document.getElementById("wrapper").className="newClass";

In addition, adding a listener to an element to see if the element has changed or is in focus, is different in versions of Internet Explorer 8 and previous versions of Internet Explorer. To add a listener to an element to work in all browsers, the following must be done:

var myelement= document.getElementById("element");
if (myelement.addEventListener){
    myelement.addEventListener("change",myFunction, false);
 } else if (langSelect.attachEvent){ // For IE8 and below
     myelement.attachEvent("onchange",myFunction, false); }

In short, the 'addEventListener' function will be recognised in all browsers (except most versions of IE), and the 'attachEvent' function will work in most versions of IE. On the event, which is the first parameter, the function (second parameter) will be called. Note that for the IE 'attachEvent' function, the event will normally have the word 'on' appended to the event: onchange, onmouseover, etc. The 'addEventListener' function will simply take the word 'change'.

On that note, I've got to get back to some work. Happy coding and making your websites work in all browsers!

No TrackBacks

TrackBack URL: http://jenikya.com/cgi-bin/mt5/mt-tb.cgi/263

Leave a comment

Archives

OpenID accepted here Learn more about OpenID