1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Swapping Content

Join the Discussion

Questions? Comments?

Do you have some text that you want to have toggle between two values when someone clicks on it? Well we can do that very simply with just a couple of lines of code. In fact we can set up multiple fields on the same page that will toggle between two values and set them all up to call the same function even if the values that each needs to toggle between are different.

We will start with an example. Simply click on the word in blue at the end of this paragraph to see it change between 'More' and 'Less': More

The function that we need to do this is fairly simple:

function swap(me,main,alt) {
me.innerHTML = (me.innerHTML == main) ? alt : main;

The code that we need to use to call the function is also fairly simple. We just call the swap() function from within the onclick event handler attached to the tag surrounding the text that we want to be able to swap and pass it this as the first parameter. The second and third parameters contain the two values to toggle between (in our example 'More' and 'Less'). One of thes values should also match the actual text within the tag.

My example tag that I am toggling the content of uses:

<span onclick="swap(this,'More','Less')">More</span>

The swap function doesn't have to be all by itself in the onclick event handler either, if you want other actions to also be performed when the content is clicked on (for example if it is to expand and contract a collapsible menu) then it is simply a matter of adding the swap function call to the code that you already have in the onclick. For example if you use my collapsible menu script you can change the + to a - on the front of the menu field when the menu expands and collapses using:

<div class="mH"
onclick="swap(this, '+ Menu', '- Menu');toggleMenu('menu1')">
- Menu</div>
Related Video
Compete's Stephen Dimarco on user-generated content
Create Tables in HTML

©2016 About.com. All rights reserved.