Search code examples
javascriptprototypejs

Prototype toggle - two instances getting muddled


I have two instances that use the toggle(). So in the code there is this link:

<a href="#" onClick="$('div1').toggle(); return false;">Completely independent link</a>

Followed by a more complex show hide toggle area:

<a href="#" onClick="$('showLessInfo').toggle();$('showAllInfo').toggle(); $('showAllInfoLink').toggle(); return false;">Show All</a>

And then the reverse of that:

<a href="#" onClick="$('showLessInfo').toggle();$('showAllInfo').toggle(); $('showAllInfoLink').toggle(); return false;">Show Less</a>

The problem I have is when I toggle the "Show all" link - it renders the "Completely Independent link" unusable. Sometimes it even opens shows/hides #div1?!?

Not really sure what is going on but the two instances are definitely getting muddled up.


Solution

  • I think what is happening is your click event is bubbling up the DOM and it hits other elements - but I can't be sure without seeing more of your HTML structure.

    That being said - I would suggest putting everything in separate click observers, it removes the javascript from the HTML, and makes it easier to handle.

    For example your 3 links

    <a href="#" onClick="$('div1').toggle(); return false;">Completely independent link</a>
    <a href="#" onClick="$('showLessInfo').toggle();$('showAllInfo').toggle(); $('showAllInfoLink').toggle(); return false;">Show All</a>
    <a href="#" onClick="$('showLessInfo').toggle();$('showAllInfo').toggle(); $('showAllInfoLink').toggle(); return false;">Show Less</a>
    

    would change to

    <a href="javascript:void(0);" id="link1">Completely independent link</a>
    <a href="javascript:void(0);" id="showall">Show All</a>
    <a href="javascript:void(0);" id="showless">Show Less</a>
    

    and add this in your head or js file or somewhere on your page

    <script>
        document.observe('dom:loaded', function()
            $('link1').observe('click',function(){
                $('div1').toggle();
            });
            $('showall').observe('click',function(){
                $('showLessInfo').toggle();
                $('showAllInfo').toggle();
                $('showAllInfoLink').toggle();
            });
            $('showless').observe('click',function(){
                $('showLessInfo').toggle();
                $('showAllInfo').toggle();
                $('showAllInfoLink').toggle();
            });
        });
    
    </script>
    

    Now for extra bonus, I changed the href="#" to href="javascript:void(0);" to avoid the need to stop the event.