Reputation:
I'm trying to add a class to a parent <li>
, this is what I have been trying with no result:
function calendaractive(){
$(this).parent('li').addClass("active");
}
HTML
<li>
<a href="javascript:void(0)" onclick="calendaractive();">2009</a>
</li>
Why does this not work?
Upvotes: 3
Views: 8688
Reputation: 639
the this
keyword in javascript means different things in different places. Sometimes it is the window, sometimes it is the function where it is used, sometimes something different. It depends on the method of invocation of the function. There is more info (and more accurate) here: How does the "this" keyword work?
So when you wrote $(this)
jQuery thought you mean this class should be added to the this object whichever it is.
If you put a selector by id as an argument to jQuery, or better yet pass an argument, your code should work.
Upvotes: 0
Reputation: 24334
You should add the event using JQuery instead of onClick method:
JS Should be something like this instead:
$(document).ready(function(){
$("a").click(function() {
$(this).parent('li').addClass("active");
});
});
HTML Like this
<li>
<a href="#">2009</a>
</li>
Note this will add to all anchor links, use a class if you want to only add the click event to certain anchor links
Upvotes: 1
Reputation: 8540
It's better to not mix your HTML and JavaScript. It would be better to check for the click within the JavaScript itself:-
$(document).ready(function(){
$('li > a').on('click', function(e) {
$(this).parent().addClass('active');
});
});
Keeping JavaScript separate from the HTML will make it easier to maintain (the same argument goes with CSS).
Upvotes: 3
Reputation: 4701
Try.
Pass this
at your function binding
<li>
<a href="javascript:void(0)" onclick="calendaractive(this);">2009</a>
</li>
change the JS accordingly
function calendaractive(anchorLink){
$(anchorLink).parent().addClass("active");
}
Upvotes: 7