views:

166

answers:

3

Given the following:

<div id="table-filters">
    <ul>
        <li class="active" onclick="myfunc();">blah</li>
        <li onclick="myfunc();">blah</li>
        <li onclick="myfunc();">blah</li>
        <li onclick="myfunc();">blah</li>
    </ul>
</div>

function myfunc() {
// Activate the LI clicked
$(this).addClass("active");
}

I would like my JQUERY to work as follows. Add class="active" to whatever LI is clicked.

+4  A: 

Remove your onClick calls from the HTML, and then place the following in your .js file:

$("#table-filters li").click(function(){
  $(this).addClass("active").siblings("li.active").removeClass("active");
  // requested in comments: how to get id of LI clicked?
  var thisID = $(this).attr("id");
});
Jonathan Sampson
Hi Jonathan, thanks for the answer. Is there a way I can do this without having to bind the elements? I'm hoping to have this function do a lot more than just add a class, and adding a lot of functions could great very messy. Any other ideas?
AnApprentice
@nobosh You can add more beneath the `$.addClass()` line if you need more done.
Jonathan Sampson
That's just a single function for all `<li>` in `table-filters`. Can you clarify what you mean by a lot of functions?
slebetman
The thing is I need to know which LI was clicked in the function, because I'm going to use that info to do a JQUERY load and inject some HTML into a div. I was going to expand upon the above sample by doing something like onclick="myfunc('Identified on which url to load');"> If I remove the onclick I can't do that. Unless somehow you function can pull the ID of the LI clicked? Is that possible? thxs
AnApprentice
See my updates, Nobosh.
Jonathan Sampson
thanks, I learned a lot this time. I appreciate it.
AnApprentice
Please accept the answer then :)
Jonathan Sampson
YOu can access the clicked element with $(this)
ZeissS
+1  A: 
$("#table-filters li").click(function(){
  $("#table-filters li.active").removeClass("active"); // remove current active
  $(this).addClass("active"); // set new active

  // Put more stuff here that you want to happen when clicked.

});

Adding an event listener using this method is generally considered the "good" way, adding a listener using onlick="BLAH" is considered a bad way.

adamse
A: 

You don't need to use .click(...); instead you can do it the way you want to do it like this:

<div id="table-filters">
    <ul>
        <li class="active" onclick="myfunc(this);">blah</li>
        <li onclick="myfunc();">blah</li>
        <li onclick="myfunc();">blah</li>
        <li onclick="myfunc();">blah</li>
    </ul>
</div>

function myfunc(li) {
// Activate the LI clicked
$(li).addClass("active");
}
Nathan Ridley