Rich
Rich

Reputation: 1156

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?

Upvotes: 0

Views: 427

Answers (2)

Roamer-1888
Roamer-1888

Reputation: 19288

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.

Upvotes: 1

dwitvliet
dwitvliet

Reputation: 7671

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 });

Upvotes: 1

Related Questions