durid
durid

Reputation: 3

DOM event repeates on other template pages

I have a quick animation on my landing page that users see when entering my site. Once the animation is completed the users are routed over to a currentTasks page where they begin to interact with the site.

I wanted to add a skip feature during the animation for users who have already seen it. I have added the following jQuery events, allowing people to skip the transition by hitting Esc or clicking the mouse

// If the user hit the escape button, navigate them to the currentTasks page
    $(document).keyup(function(event) {
        event.preventDefault();
        if (event.keyCode == 27) { // escape key maps to keycode `27`
            Router.go('/currentTasks');
        }
    });
    $(document).mousedown(function(event){
      event.preventDefault();
      Router.go('/currentTasks');
    });

However, once the user is routed to the currentTasks page and wonders throughout the site, if they were to hit the escape button or click on the mouse again, they would again be rerouted back to the current tasks page.

I've looked at other approaches and can't seem to figure out what is wrong with this approach.

Appreciate any help

Upvotes: 0

Views: 25

Answers (1)

Neil S
Neil S

Reputation: 2304

You need to unbind those event handlers after one has occurred. I also updated the code to use the preferred "on" method for attaching event handlers.

// If the user hit the escape button, navigate them to the currentTasks page
    $(document).on('keyup', function(event) {
        event.preventDefault();
        if (event.keyCode == 27) { // escape key maps to keycode27
            $(document).off('keyup mouseup');
            Router.go('/currentTasks');
        }
    });
    $(document).on('mouseup', function(event){
      event.preventDefault();
      $(document).off('keyup mouseup');
      Router.go('/currentTasks');
    });

I should note - this is assuming these are the only event handlers you have attached to the mouseup and keyup events. If you had more event handlers, you'd probably want to declare those event handler functions separately and use those named references to unbind the handlers you want to dispose of.

Upvotes: 1

Related Questions