简体   繁体   中英

Trying to toggle a panel whilst changing the icon to 'view more' and 'view less'

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:

$('.moreAppsIcon').live('click', function() {
//and...
$('.lessAppsIcon').live('click', function() {

Otherwise your functions aren't being bound correctly. For example $('.lessAppsIcon') finds elements with that class at that time and binds a click handler to them...elements getting that class later don't get that click handler, 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 n event 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.

I figured it out. It was pretty much what Nick was saying actually to do with the time of the event. I added an id to the <li> to handle the click event. This is what it looks like:

$(document).ready(function() {
    $('.allApps').hide();
    $('#moreOrLess').click(function() {
        $('.allApps').slideToggle("slow", function() {
            $('#moreOrLess').toggleClass("moreAppsIcon").toggleClass("lessAppsIcon");
            $(this).toggleClass("active");
        });
        return false;
    });    
});

Cheers for the help though Nick :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM