I’m trying to get away from using inline JavaScript events by staying away from the onClick and onMouseOver and writing my own event handlers. I’m pretty familiar with Prototype and Scriptaculous but I still consider myself a novice. What I’m attempting to do is attach an event handler (let’s say a click) to multiple elements (let’s say 5 links) with the same class name. The reason I’m using a class name is because sometimes I’ll store a record ID from a database in this field so I know what record I’m dealing with. For example, let’s say I want to list all books under a certain category and I want to know what book I’m dealing with that cooresponds to a database table using the id. For example:
in this example the book’s ID would be 1. I have many different reasons for doing it this way (as I know I could do delete_book.php?id=1 but sometimes I can’t use this method).
So after all that banter, I would just like to be able to attach an event listener to all five links with the class name bookDeleteLink. I’m sure this is possible, but I’m having difficulty figuring it out. This is what I’ve come up with so far:
However this is for accessing ID’s and I want class names. So I tried document.getElementsByClassName(‘bookDeleteLink’) however this doesn’t work either. If you have a sec and know the answer, I’d appreciate it. Thanks!
Thanks for responding. I forgot to mention that I tried this. I tried again though. Below is my HTML (the links I want to add click handlers for) and the JavaScript below after the links are rendered.
Are you iterating through the collection that $$ returns?
When you use $(id) there is only ever one element that is returned.
When You use $$(selector) there is an array of elements that is returned. You can’t apply the .observe method on that array. You have to iterate through them instead.
It could have just been el.observe instead of return $(el).observe but the latter allows you to add on to the chain, should you desire to do so later on.
I had another question regarding similar thing I am trying to do.
Is it possible to get the text inside each element that can be passed onto a function. For example When “Test” is clicked I want to be able to find out the text inside the particular class element that was clicked. I guess I could have an attribute with the same value as the text and get the value but I was wondering if its possible to accomplish this as is.
Also I should be able to attach a ajax call to this onclick function, right?