Tuesday, March 25, 2008

Changing a button name when toggling show/hide

If you have a button that does a Scriptaculous toggle, you can have the text of the button changes from "Show" to "Hide" by updating the text property of the button using JavaScript and AJAX. Here's how you do it:

First, define the button and the area in which you want to show/hide. In this case, I have a change history that can get quite large, so I want to be able to toggle it on and off, with some scriptactulous pizazz. So, I first define the button as:


Change History:
<form action="javascript:void%200" method="get">
<button type="button" id="switchoff" class="togglebutton"
name="switchoff">Hide</button></form>




Next, define then area to show/hide using a div tag with an id. I'll use the id of "change_history" in this case.


<div id="change_history">
<table><!-- this is just a table with my
change history in it --></table>
</div>



Ok, now that I have my elements named and defined, it's time to set up some JavaScript to handle the toggle.


window.onload = function() {
/**
* Toggle change history.
*/
if ($("change_history") && $("switchoff")) {
$("switchoff").onclick = function() {
// Effect.toggle(element,
// ['appear' | 'slide' | 'blind'], [options] );

Effect.toggle($("change_history"), 'appear');
var toggleButton =
document.getElementById('switchoff');

if (toggleButton.textContent == "Show") {
toggleButton.textContent = "Hide";
} else if (toggleButton.textContent == "Hide") {
toggleButton.textContent = "Show";
} else {
toggleButton.textContent = "Show";
}
}
}
}



Put this JavaScript at the top of your web page in the section or, preferably, in another JavaScript file and reference it from your web page. I usually do the later. Basically, this JavaScript looks for elements named "change_history" and "switchoff", and if they are available, then go ahead and perform the function.

It next defines the onclick() method for switchoff so that, when clicked, use Scriptaculous to toggle the change_history (i.e. if it's shown, then hide it. If it's hidden, show it). This is all basic Scriptactulous, so nothing new here. However, now the JavaScript tries to determine if the text of the button is currently "Show" or "Hide". It will change it to the opposite of what it is now. The last case is for those who didn't originally use "Show" or "Hide" for the button name. It will basically change it go "Show" the first time you hide what you want to hide.

That's about it. Enjoy!