I’ve just started learning jQuery/javascript, so this might seem like a really basic question, but it’s annoying me nevertheless.
I have a panel of 6 <li>s, 3 of which are hidden until clicking on the ‘view more’ link at which point the panel toggles to reveal the other 3. The icon is changing from ‘more’ to ‘less’, but then not changing back to ‘more’. Can anyone see the problem in the code?
Any help would be greatly appreciated 🙂
Thanks,
David
$(document).ready(function() {
$('.allApps').hide();
$('.moreAppsIcon').click(function() {
$('.moreAppsIcon').removeClass("moreAppsIcon").addClass("lessAppsIcon");
$(this).toggleClass("active");
$('.allApps').slideToggle("slow");
return false;
});
$('.lessAppsIcon').click(function() {
$('.appsMore').slideToggle("slow", function () {
$('.appsMore').removeClass("appsMore").addClass("moreAppsIcon");
$(this).toggleClass("active");
return false;
});
});
});
It’s easier to use
.live()here, like this:Otherwise your functions aren’t being bound correctly. For example
$('.lessAppsIcon')finds elements with that class at that time and binds aclickhandler to them…elements getting that class later don’t get thatclickhandler, whereas.live()works on the selector of the element at the time of the event, having the result you want.So basically you’re attaching
nevent handlers, one for each element matching initially…when you do.addClass()the other elements don’t get that event handler all the sudden, it’s on the DOM elements you initially found, not dynamically added to others when they change class. For the same reason.removeClass()doesn’t remove the event handler. However, if you use.live()like above, it’ll have the effect of changing event handlers like you’re after.