1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<script language="javascript"> function toggleLinkAndElement (link, elementID, text) { Element.toggle(elementID); // toggle the element if (link.innerHTML != text ) { // change link text link.oldInnerHTML = link.innerHTML; link.innerHTML = text; } else { // change it back link.innerHTML = link.oldInnerHTML; } } </script> <div id="content" style="display:none"> <p>HELLO WORLD!</p> </div> <a href="#" onclick="toggleLinkAndElement(this, 'content', 'Hide'); return false;">Show</a>
Refactorings
No refactoring yet !
North
July 19, 2009, July 19, 2009 11:45, permalink
I don't use Prototype, but if you're also interested in a jQuery (or Mootools) solution, I can post one.
Jermaine
August 26, 2009, August 26, 2009 18:48, permalink
Hi North,
JQuery would be fine as well....
paul.wilkins.myopenid.com
September 1, 2009, September 01, 2009 14:49, permalink
This question has been languishing unresponded to for some time now, so I've crafted together some jQuery code to achieve what you require.
For each element with a class of "toggle", the code adds a Show/Hide link just below it.
The link toggles the element by its id attribute, and switches between Show and Hide when you click it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$(function () { $('.toggle') .each(function () { $('<a href="#' + $(this).attr('id') + '">Show</a>') .click(function () { $($(this).attr('href')) .toggle(); $(this).text( $(this).text() !== 'Show' ? 'Show' : 'Hide' ); }) .wrap('<p></p>') .insertAfter(this); }) .hide(); }); . . . <p id="content" class="toggle">Paragraph to be toggled</p>
Hi Everyone,
I've got this small piece of code that basically toggles a element but changes the hyperlink's name as well.
In this case if I would click on the "Show" button, it will display the content div, but it will also change the text from "Show" to "Hide".
Now it all works fine, but I think it looks ugly. I'm not really proficient with javascript, but I'm looking for a better (Unobtrusive) way to do this in prototype.
Any ideas?
Many thanks in advance.
Greets,
- Jermaine