Drew
Drew

Reputation: 15408

Getting element properties in click handler

Forewarning: I'm a newbie to JQuery.

I have a collection of links and lists that look something like so. They're dynamically generated by my back end framework...

<ul>
  <li>
    <a id="link1" class="special" href="#">...</a>
    <ul id="list1"> ... </ul>
  </li>
  <li>
    <a id="link2" class="special" href="#">...</a>
    <ul id="list2"> ... </ul>
  </li>
  <li>
    <a id="link3" class="special" href="#">...</a>
    <ul id="list3"> ... </ul>
  </li>
</ul>

I'm trying to learn JQuery and Unobtrustive Javascript, so I want to add a click handler on all the links with the class "special" that will toggle the related lists.

So...

$(document).ready(function() {
  $("a.special").click(function() {
     id = *magicFunctionToGetOwnID*
     $(convertListIDtoLinkID(id)).toggle
  })
})

What is the magic function that I need? What about if I want to get other properties of the thing I'm attaching a handler to? Say, in the future, I add a "toggle-target" property and I would want to get that?

Upvotes: 1

Views: 283

Answers (3)

jAndy
jAndy

Reputation: 236012

Not sure If I get you right, but it looks like you want something like this:

$(function() {
   $('ul:first').delegate('a.special', function( event ) {
       $(this).next('ul').toggle();
   });
});

You don't should bind an event handler to all nodes in a situation like that. It's enough to bind one handler to a shared parent and make use of the event bubbling.

Update
.delegate() does exactly what I described above. It'll bind the event handler to a node. The trick is, that event if that event is triggered on a child node from the delegated node, the events will "reach" our destination by bubbling up the DOM tree (unless explicitly prohibit event bubbling). However, jQuery is nice and will always bind this to the target node (the node which originally received the event).

Have a read: http://api.jquery.com/delegate/

Upvotes: 4

lonesomeday
lonesomeday

Reputation: 237865

The way to get an element's own id is with the id property. The element that was clicked is set as this within the handler, so you can use this.id.

That said, this is not an optimal technique. Use DOM relationships, rather than setting ids, wherever you can. This will make your code more flexible and intuitive. In this case, you can use the next method, to get the DOM element that follows the element that was clicked:

$(this).next().toggle();

See the API "traversing" category for more ways of adjusting a selection.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154838

Try $(this).parent().find("ul").toggle(). It is rather self-explanatory.

http://jsfiddle.net/gLu9a/

Upvotes: 1

Related Questions