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.
From stackoverflow
-
Remove your
onClickcalls 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"); });AnApprentice : 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?Jonathan Sampson : @nobosh You can add more beneath the `$.addClass()` line if you need more done.slebetman : That's just a single function for all `- ` in `table-filters`. Can you clarify what you mean by a lot of functions?
AnApprentice : 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? thxsJonathan Sampson : See my updates, Nobosh.AnApprentice : thanks, I learned a lot this time. I appreciate it.Jonathan Sampson : Please accept the answer then :)ZeissS : YOu can access the clicked element with $(this) -
$("#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. -
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"); }
0 comments:
Post a Comment