You could use instead:
$('.mycontainer .mylink').on('click', function () {
$(this).closest('.mycontainer').addClass('active').siblings('.mycontainer.active').removeClass('active');
});
Question
I have this:
<div class="mycontainer active">
<a href="#" class="mylink">link</a>
</div>
<div class="mycontainer">
<a href="#" class="mylink">link</a>
</div>
and I want to "move" the active class to the second container when i click on the link in it.
I tried with the following jQuery:
$('.mycontainer .mylink').on('click', function(){
$(".active").removeClass('active');
$(this).parent().find(".mycontainer").addClass('active');
});
But this is not working, actually I don't know pretty much about Javascript/jQuery, what am I doing wrong? Any kind of help is appreciated, thanks.
Solution
You could use instead:
$('.mycontainer .mylink').on('click', function () {
$(this).closest('.mycontainer').addClass('active').siblings('.mycontainer.active').removeClass('active');
});
OTHER TIPS
try:
$(this).parent().addClass('active');
or:
$(this).parent(".mycontainer").addClass('active');
instead. Because $(this).parent()
already refers to the element you're looking for, and then with find()
you're trying to find elements with class mycontainer
inside of it which will not work.
The line:
$(this).parent().find(".mycontainer")
is finding the mycontainer div, then looking for .mycontainer inside it, when actually you are already there.
Try this instead:
$('.mycontainer .mylink').on('click', function(){
$(".active").removeClass('active');
$(this).parent().addClass('active');
});
You want to add the active class on the link that is getting clicked...
Example: http://jsfiddle.net/LCaNP/
$('.mycontainer .mylink').on('click', function(){
$('.mycontainer').removeClass('active');
$(this).parent().addClass('active');
});
$('.myContainer').toggleClass('active')
should do it.
It will remove the class where it is present and add where it is not.
Check out .toggleclass()
So, the code would be -
$('.mycontainer .mylink').on('click', function(){
$('.myContainer').toggleClass('active');
});
Here's a JSFiddle