Evolving Styles: Add, Change Remove Classes with Prototype


This entry is part 4 of 10 in the series Prototype Tutorial

If you are a web designer or developer in 2007 (almost 2008) then chances are the majority (if not all) of your web projects are visually defined with styles. At night I pray for world peace and the death of the <font> tag.
That was an exaggeration, for the record.

There are many ways to manipulate the styles of your most dynamic pages with Prototype, you can just add inline styles, like telling an element to add an inline style of bold and italic, or you can apply [or add] a whole new class to an element. Working with classes instead of inline styles is typically an optimal solution since it helps allow for easier updates in the future and is often a more expandable way to work.

first we'll start by applying a new style to a <div>. The div in this first example already had the style featurebox applied to it and by defining a new class I called blue I can use the Prototype functions addClassName() and removeClassName() to add or remove the class blue from the element.

Example 1 - Add a Style to a DIV

Add the class blue | Remove the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Code for Example 1

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-1-listena', 'click', function(){
            $('featurebox-1').addClassName('blue');
        });
        Event.observe('featurebox-1-listenb', 'click', function(){
            $('featurebox-1').removeClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-1-listena">Add the class `blue`</span> | <span id="featurebox-1-listenb">Remove the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Now who doesn't like toggling? Answer: no one. We all like toggling! I don't know a single geek who doesn't love applying a style, and taking it off while only having to click (or code) one button, so let's use the toggleClassName() function to get that started.
* If you don't like toggling, we can't be friends, sorry that's just how it is.

Example 2 - Toggle a Style

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').down('p').toggleClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-2-listen">Toggle the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Don't forget lesson past.

Remember how we learned about changing the inner HTML of the span to reflect the action, or maybe even using an image like we did in the Simple Hide and Show with Prototype Tutorial. The only difference between the hide and show example with the image is that instead of using Visible() you'd use hasClassName() to make your decision.

Here's the sample to accompany the previous CSS and HTML to change the toggle words to 'Toggle blue on' and 'Toggle blue off'

Example 2b - Toggle Style w/ text change

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Same HTML and CSS as above just use this to replace the JavaScript:

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').toggleClassName('blue);
            if($('featurebox-2').hasClassName('blue)){
                $('featurebox-2-listen').update('Toggle blue off');
            } else {
                $('featurebox-2-listen').update('Toggle blue on');
            }
        });
    });
</script>

Now to step it up I'm going to get a little custom. Since the classNames function is depricated I wanted to make sure I had a back-up to clear all class names.

Originally with Prototype you'd do it like this:

// Depricated DO NOT USE
// Displayed for demonstration only
$('element').className = '';

Since that is now 100% unusable I had to find a better way to approach the situation or removing all the classes (known or unknown) from an element.

I tested a number of different failed ideas.

Failed one-liners

  • $('featurebox-3').className('');
  • $('featurebox-3').replaceClassNames('');
  • $('featurebox-3').writeAttribute('class', NULL);

None of those did what I needed them to do. Though in testing another function: $('featurebox-3').classNames().inspect() I realized that since that returned an enumerable, which using Prototype's toArray() function I could make an array and loop through to remove all the classes I knew I was onto something.

Example 3 - Removing Specific Styles and All Styles

Add the class blue | Remove the class blue | Add the class big-bold | Clear all classes (except featurebox)

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Above in the other examples we covered adding and removing classes like the first three links 'Add the class blue', 'Remove the class blue' and 'Add the class big-bold' do. The only new thing is my awesome way to remove all class names, which is done like so:

Code for Example 5 - Removing all Class Names

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $('featurebox-3').classNames().toArray();
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                $('featurebox-3').removeClassName(classArray[index]);
            }
        });
    });
</script>

HTML

<span id="featurebox-3-listen4" class="anchorlike">Clear all classes</span>

If you wanted to exclude a class name you'd just throw in an if statement to avoid removing that class name.

Code for Example 5 - Remove all Class Names Except featurebox

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $('featurebox-3').classNames().toArray();
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                if(classArray[index] != 'featurebox'){
                    $('featurebox-3').removeClassName(classArray[index]);
                }
            }
        });
    });
</script>

Summary

It's very easy to add, remove, clear and switch classes on different elements with Prototype. It's also usually more efficent than just adding inline styles and will always make your life easier in the end!

Prototype Functions Used

Prototype Functions Mentioned

  • [visible()](If you are a web designer or developer in 2007 (almost 2008) then chances are the majority (if not all) of your web projects are visually defined with styles. At night I pray for world peace and the death of the <font> tag.
    That was an exaggeration, for the record.

There are many ways to manipulate the styles of your most dynamic pages with Prototype, you can just add inline styles, like telling an element to add an inline style of bold and italic, or you can apply [or add] a whole new class to an element. Working with classes instead of inline styles is typically an optimal solution since it helps allow for easier updates in the future and is often a more expandable way to work.

first we'll start by applying a new style to a <div>. The div in this first example already had the style featurebox applied to it and by defining a new class I called blue I can use the Prototype functions addClassName() and removeClassName() to add or remove the class blue from the element.

Example 1 - Add a Style to a DIV

Add the class blue | Remove the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Code for Example 1

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-1-listena', 'click', function(){
            $('featurebox-1').addClassName('blue');
        });
        Event.observe('featurebox-1-listenb', 'click', function(){
            $('featurebox-1').removeClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-1-listena">Add the class `blue`</span> | <span id="featurebox-1-listenb">Remove the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Now who doesn't like toggling? Answer: no one. We all like toggling! I don't know a single geek who doesn't love applying a style, and taking it off while only having to click (or code) one button, so let's use the toggleClassName() function to get that started.
* If you don't like toggling, we can't be friends, sorry that's just how it is.

Example 2 - Toggle a Style

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').down('p').toggleClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-2-listen">Toggle the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Don't forget lesson past.

Remember how we learned about changing the inner HTML of the span to reflect the action, or maybe even using an image like we did in the Simple Hide and Show with Prototype Tutorial. The only difference between the hide and show example with the image is that instead of using Visible() you'd use hasClassName() to make your decision.

Here's the sample to accompany the previous CSS and HTML to change the toggle words to 'Toggle blue on' and 'Toggle blue off'

Example 2b - Toggle Style w/ text change

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Same HTML and CSS as above just use this to replace the JavaScript:

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').toggleClassName('blue);
            if($('featurebox-2').hasClassName('blue)){
                $('featurebox-2-listen').update('Toggle blue off');
            } else {
                $('featurebox-2-listen').update('Toggle blue on');
            }
        });
    });
</script>

Now to step it up I'm going to get a little custom. Since the classNames function is depricated I wanted to make sure I had a back-up to clear all class names.

Originally with Prototype you'd do it like this:

// Depricated DO NOT USE
// Displayed for demonstration only
$('element').className = '';

Since that is now 100% unusable I had to find a better way to approach the situation or removing all the classes (known or unknown) from an element.

I tested a number of different failed ideas.

Failed one-liners

  • $('featurebox-3').className('');
  • $('featurebox-3').replaceClassNames('');
  • $('featurebox-3').writeAttribute('class', NULL);

None of those did what I needed them to do. Though in testing another function: $('featurebox-3').classNames().inspect() I realized that since that returned an enumerable, which using Prototype's toArray() function I could make an array and loop through to remove all the classes I knew I was onto something.

Example 3 - Removing Specific Styles and All Styles

Add the class blue | Remove the class blue | Add the class big-bold | Clear all classes (except featurebox)

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Above in the other examples we covered adding and removing classes like the first three links 'Add the class blue', 'Remove the class blue' and 'Add the class big-bold' do. The only new thing is my awesome way to remove all class names, which is done like so:

Code for Example 5 - Removing all Class Names

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $('featurebox-3').classNames().toArray();
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                $('featurebox-3').removeClassName(classArray[index]);
            }
        });
    });
</script>

HTML

<span id="featurebox-3-listen4" class="anchorlike">Clear all classes</span>

If you wanted to exclude a class name you'd just throw in an if statement to avoid removing that class name.

Code for Example 5 - Remove all Class Names Except featurebox

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $('featurebox-3').classNames().toArray();
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                if(classArray[index] != 'featurebox'){
                    $('featurebox-3').removeClassName(classArray[index]);
                }
            }
        });
    });
</script>

Summary

It's very easy to add, remove, clear and switch classes on different elements with Prototype. It's also usually more efficent than just adding inline styles and will always make your life easier in the end!

Prototype Functions Used

Prototype Functions Mentioned

  • [visible()](If you are a web designer or developer in 2007 (almost 2008) then chances are the majority (if not all) of your web projects are visually defined with styles. At night I pray for world peace and the death of the <font> tag.
    That was an exaggeration, for the record.

There are many ways to manipulate the styles of your most dynamic pages with Prototype, you can just add inline styles, like telling an element to add an inline style of bold and italic, or you can apply [or add] a whole new class to an element. Working with classes instead of inline styles is typically an optimal solution since it helps allow for easier updates in the future and is often a more expandable way to work.

first we'll start by applying a new style to a <div>. The div in this first example already had the style featurebox applied to it and by defining a new class I called blue I can use the Prototype functions addClassName() and removeClassName() to add or remove the class blue from the element.

Example 1 - Add a Style to a DIV

Add the class blue | Remove the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Code for Example 1

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-1-listena', 'click', function(){
            $('featurebox-1').addClassName('blue');
        });
        Event.observe('featurebox-1-listenb', 'click', function(){
            $('featurebox-1').removeClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-1-listena">Add the class `blue`</span> | <span id="featurebox-1-listenb">Remove the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Now who doesn't like toggling? Answer: no one. We all like toggling! I don't know a single geek who doesn't love applying a style, and taking it off while only having to click (or code) one button, so let's use the toggleClassName() function to get that started.
* If you don't like toggling, we can't be friends, sorry that's just how it is.

Example 2 - Toggle a Style

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

CSS

<style type="text/css">
    .blue { color: #315FEF; background-color:#D6DCEF; }
</style>

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').down('p').toggleClassName('blue');
        });
    });
</script>

HTML

<span id="featurebox-2-listen">Toggle the class `blue`</span>
<div class="featurebox" id="featurebox-1"><strong>FeatureBox</strong> - Lorem ipsum dolor sit amet[...]</div>

Don't forget lesson past.

Remember how we learned about changing the inner HTML of the span to reflect the action, or maybe even using an image like we did in the Simple Hide and Show with Prototype Tutorial. The only difference between the hide and show example with the image is that instead of using Visible() you'd use hasClassName() to make your decision.

Here's the sample to accompany the previous CSS and HTML to change the toggle words to 'Toggle blue on' and 'Toggle blue off'

Example 2b - Toggle Style w/ text change

Toggle the class blue

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Same HTML and CSS as above just use this to replace the JavaScript:

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-2-listen', 'click', function(){
            $('featurebox-2').toggleClassName('blue);
            if($('featurebox-2').hasClassName('blue)){
                $('featurebox-2-listen').update('Toggle blue off');
            } else {
                $('featurebox-2-listen').update('Toggle blue on');
            }
        });
    });
</script>

Now to step it up I'm going to get a little custom. Since the classNames function is depricated I wanted to make sure I had a back-up to clear all class names.

Before, with Prototype you'd do it like this:

// Depricated DO NOT USE
// Displayed for demonstration only
$('element').className = '';

Since that is now 100% unusable I had to find a better way to approach the situation or removing all the classes (known or unknown) from an element.

I tested a number of different failed ideas.

Failed one-liners

  • $('featurebox-3').className('');
  • $('featurebox-3').replaceClassNames('');
  • $('featurebox-3').writeAttribute('class', NULL);

None of those did what I needed them to do. Though in testing another function: $('featurebox-3').classNames().inspect() I realized that since that returned an enumerable, which using Prototype's toArray() function I could make an array and loop through to remove all the classes I knew I was onto something. Then I found out that the following lines accomplish the exact same thing:

var classArray = $w($('featurebox-3').className);
var classArray = $('featurebox-3').classNames().toArray();

So I decided to stick with the shorter one: $w($('featurebox-3').className) that is recomended on the Prototype classNames() page.

Example 3 - Removing Specific Styles and All Styles

Add the class blue | Remove the class blue | Add the class big-bold | Clear all classes (except featurebox)

Feature Box - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce augue. Integer aliquam porta nisi. Curabitur lacinia venenatis diam. Suspendisse fringilla. Etiam eget turpis ullamcorper sem convallis eleifend. Donec pharetra, velit ac feugiat dictum, felis orci tempus lorem, nec ultricies purus velit at velit. Sed eget justo. Nullam auctor tincidunt lacus. Nullam vitae nisi. Morbi metus. In hac habitasse platea dictumst. Nunc vel massa. Duis et quam. Donec bibendum, mi sed fermentum venenatis, est massa tincidunt nibh, eget convallis sem risus ac tellus. Sed nibh sem, volutpat ut, bibendum ac, imperdiet nec, lectus.

Above in the other examples we covered adding and removing classes like the first three links 'Add the class blue', 'Remove the class blue' and 'Add the class big-bold' do. The only new thing is my awesome way to remove all class names, which is done like so:

Code for Example 5 - Removing all Class Names

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $w($('featurebox-3').className);
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                $('featurebox-3').removeClassName(classArray[index]);
            }
        });
    });
</script>

HTML

<span id="featurebox-3-listen4" class="anchorlike">Clear all classes</span>

If you wanted to exclude a class name you'd just throw in an if statement to avoid removing that class name.

Code for Example 5 - Remove all Class Names Except featurebox

JavaScript

<script type="text/javascript">
    Event.observe(window, 'load', function() {
        Event.observe('featurebox-3-listen4', 'click', function(){
            var classArray = $w($('featurebox-3').className);
            for (var index = 0, len = classArray.size(); index < len; ++index) {
                if(classArray[index] != 'featurebox'){
                    $('featurebox-3').removeClassName(classArray[index]);
                }
            }
        });
    });
</script>

Summary

It's very easy to add, remove, clear and switch classes on different elements with Prototype. It's also usually more efficent than just adding inline styles and will always make your life easier in the end!

Prototype Functions Used

Prototype Functions Mentioned

Series NavigationNext Article»

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Similar Entries
JavaScript Script.aculo.us Fade with a Timer
This entry is part 4 of 10 in the series Prototype TutorialPrototype Tutorial Series IndexSimple Hide and Show with PrototypeEvent Observe and Event Listeners with PrototypeJavaScript Script.aculo.us Fade with a TimerEvolving Styles: Add, Change Remove Classes with PrototypeAlternating Colors Using PrototypeFirst, Last, Active and Only List Styles With PrototypeChange Rel External to Target Blank using
Alternating Colors Using Prototype
This entry is part 4 of 10 in the series Prototype TutorialPrototype Tutorial Series IndexSimple Hide and Show with PrototypeEvent Observe and Event Listeners with PrototypeJavaScript Script.aculo.us Fade with a TimerEvolving Styles: Add, Change Remove Classes with PrototypeAlternating Colors Using PrototypeFirst, Last, Active and Only List Styles With PrototypeChange Rel External to Target Blank using
First, Last, Active and Only List Styles With Prototype
This entry is part 4 of 10 in the series Prototype TutorialPrototype Tutorial Series IndexSimple Hide and Show with PrototypeEvent Observe and Event Listeners with PrototypeJavaScript Script.aculo.us Fade with a TimerEvolving Styles: Add, Change Remove Classes with PrototypeAlternating Colors Using PrototypeFirst, Last, Active and Only List Styles With PrototypeChange Rel External to Target Blank using
Simple Hide and Show with Prototype
This entry is part 4 of 10 in the series Prototype TutorialPrototype Tutorial Series IndexSimple Hide and Show with PrototypeEvent Observe and Event Listeners with PrototypeJavaScript Script.aculo.us Fade with a TimerEvolving Styles: Add, Change Remove Classes with PrototypeAlternating Colors Using PrototypeFirst, Last, Active and Only List Styles With PrototypeChange Rel External to Target Blank using
Event Observe and Event Listeners with Prototype
This entry is part 4 of 10 in the series Prototype TutorialPrototype Tutorial Series IndexSimple Hide and Show with PrototypeEvent Observe and Event Listeners with PrototypeJavaScript Script.aculo.us Fade with a TimerEvolving Styles: Add, Change Remove Classes with PrototypeAlternating Colors Using PrototypeFirst, Last, Active and Only List Styles With PrototypeChange Rel External to Target Blank using
Next Post
Multiple and Dynamic Variable Assignment in PHP
Previous Post
First, Last, Active and Only List Styles With Prototype

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!