简体   繁体   中英

Toggling appendTo() using jQuery Waypoints

My .topics element relocates itself in the DOM -- and for testing purposes acquires the "active" class -- when the Waypoint triggers.

$('.navbar').waypoint(function() {
    $('.topics').toggleClass('active');
    $('.topics').appendTo( $('#menu') );
}, { offset: -50 });

When the waypoint is no longer in view the "active" class is removed from .topics as expected, yet the .topics elements remains appended to #menu.

Is it possible to restore .topics to its original DOM location by either toggling appendTo(); or triggering the event when the Waypoint becomes inactive?

How about putting in an if statement to check if the element exists?

$('.navbar').waypoint(function() {
    $('.topics').toggleClass('active');
    if ($('#menu .topics').length) {
        $('#menu .topics').remove();
    } else {
        $('.topics').appendTo( $('#menu') );
    }
}, { offset: -50 });

Not trying to steal @Banana's rep here but you will find it more efficient to avoid having to rediscover the .topics elements several times over, every time the handler fires. For example :

  • assign the result of $('.topics') so it can be reused
  • test .hasClass('active') rather than $('#menu .topics').length

If my understanding is correct, then this should give the same effect as your adaptation of Banana's code :

$('.navbar').waypoint(function() {
    var $topics = $('.topics').toggleClass('active');
    if($topics.hasClass('active')) {
        $topics.appendTo( $('#menu') );
    } else {
        $topics.appendTo( $('#orginialmenu') );
    }
}, { offset: -50 });

Performance optimisations like this can be important for the quality of your site/app's UI/UX, especially when the DOM is extensive.

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