Search code examples
prototypejs

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


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() {
    $('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?


Solution

  • Your code only needs two changes

     $$('.link').each(function() { observe('click', function(event) {
            event.stop();
            Modalbox.show(this.href,{title: 'some title', width: 500} );
        }}));
    

    Note the '.link', to indicate it's a class name, and then the each function to apply it to each result. Brackets may need tweaking, I'm holding a baby at the moment