In this article we will create a class handler that will add and remove classes from HTML elements. What this will do is enable you to create an “ON” and “OFF” style for any element in your HTML document. Then you can use a “click”, “focus”, or any other event to add/remove/toggle a class on an element or elements. For example, you have a series of boxes with images. Some of the images have cars, and some have planes. Above the images you could have buttons to select the type of images shown. With JavaScript you can add or remove a class to hide or show the groups of images.

Let’s start by building an HTML file that will hold our page elements and a reference to our classifier.js file that will hold our JavaScript code:

<!DOCTYPE html>
<html>
<head>
    <title>Class Adder</title>
    <style>
        .wrap {border: 2px solid green;}
    </style>
</head>
<body>
    <div id="box">Test box</div>
    <input type="button" value="Border On" id="borderon" />
    <input type="button" value="Border Off" id="borderoff" />
    <input type="button" value="Border Toggle" id="bordertoggle" />

    <script src="js/classifier.js"></script>
</body>
</html>

The following JavaScript code gives you a class checking function, an add class function, a remove class function, and finally a toggle class function.  All of the JavaScript that follows will go into the classifier.js file.

//Check for a CSS class in an element
var hasClass = function (element, classname) {
    var regex = new RegExp('(?:\\s|^)' + classname + '(?:\\s|$)')
    return !!element.className.match(regex);
}
//Add a CSS class to an element
var addClass = function (element, classname) {
    var regex = new RegExp('(?:\\s|^)' + classname + '(?:\\s|$)')
    //Stops adding a deplicate class
    if (!hasClass(element, classname)) {
        element.className += ' ' + classname;
    }
}
//Remove a CSS class from an element
var removeClass = function (element, classname) {
    var regex = new RegExp('(?:\\s|^)' + classname + '(?:\\s|$)')
    element.className = element.className.replace(regex, ' ');
}
//Toggle a CSS class on an element
var toggleClass = function (element, classname) {
    hasClass(element, classname) ? removeClass(element, classname) : addClass(element, classname);
}

This code should work in all browsers including IE8 and up.

Now we need to attach the functions to our buttons click events.  We will use the handler functions we created in “Use JavaScript to Attach Events In Older Browsers”.

var addEvent = function (element, eventType, handler) {
    if (element.attachEvent) {
        element.attachEvent('on' + eventType, handler, false);
    } else if (element.addEventListener) {
        element.addEventListener(eventType, handler, false);
    }
}
var removeEvent = function (element, eventType, handler) {
    if (element.removeEventListener) {
        element.removeEventListener(eventType, handler, false);
    } else if (element.detachEvent) {
        element.detachEvent('on' + eventType, handler);
    }
}

Now we need to grab a reference to our buttons:

var borderOn = document.getElementById('borderon');
var borderOff = document.getElementById('borderoff');
var borderToggle = document.getElementById('bordertoggle');

The following code is our handlers for each button.  I included a legacy and modern way of getting a reference to the box ID.

var onhandler = function (event) {
    //var container = document.querySelector('#box');         //IE9+
    var container = document.getElementById('box');           //Legacy
    addClass(container, 'wrap');
};
var offhandler = function (event) {
    //var container = document.querySelector('#box');         //IE9+
    var container = document.getElementById('box');           //Legacy
    removeClass(container, 'wrap');
};
var togglehandler = function (event) {
    //var container = document.querySelector('#box');         //IE9+
    var container = document.getElementById('box');           //Legacy
    toggleClass(container, 'wrap');
};

Finally we add the handlers to our buttons.

addEvent(borderOn, 'click', onhandler);
addEvent(borderOff, 'click', offhandler);
addEvent(borderToggle, 'click', togglehandler);

I hope you find this code useful in your web projects.

Categories


Most Visited