Simple Prototype.js code to select multiple elements with the same classname

Posted by stephemurdoch on Stack Overflow See other posts from Stack Overflow or by stephemurdoch
Published on 2010-06-10T20:11:23Z Indexed on 2010/06/10 20:12 UTC
Read the original article Hit count: 318

I have one link with an id of "link", and I use the javascript below to open that link up in a modalbox:

#In my template I have: 
<a href="some/path" id="link">link</a>


#Then in my application.js file I have:
document.observe('dom:loaded', function() {
    $('login-link').observe('click', function(event) {
        event.stop();
        Modalbox.show(this.href,{title: 'some title', width: 500});            
    });
})

Since id's must be unique, this javascript only works for one element per page so I use it to observe my login-link and it has served me well. Until now.

I want to use the same javascript to observe multiple links which have classnames instead of id's as below:

<a href="link/to/some/stuff" class="link">link 1</a>
<a href="link/to/some/other/stuff" class="link">link 2</a>

When I do this, I can't get any of the links to open in a modalbox. If I change the class to an id for each link, then I can get the first link in the list to open in a modalbox.

I've tried to use the '$$' notation to build an array of links in my javascript (shown below) but if I do that, then none of the links open correctly

    #document.observe method removed for display purposes
    $$('link').observe('click', function(event) {
        event.stop();
        Modalbox.show(this.href,{title: 'some title', width: 500} );
    });

My javascript skills obviously suck.
Does anyone know how to fix the problem?

© Stack Overflow or respective owner

Related posts about prototype

Related posts about prototypejs