kabugh
kabugh

Reputation: 315

Vue.js routing and JQuery - coming back from a route

there is a problem (I am using vue-router and have routes that are configured in a proper way): I've got a main page (component home.vue) and use a jquery code: after clicking on a button it scrolls down to a certain div (it works fine) and i've got another button to route to a different component. Routing works, but after coming back from a route (there's a button in the component newpage.vue), jquery code (scrolling) on the main page is not working anymore. The rest of my jquery code is working fine.

App.vue (main component):

<template>
    <div>
      <router-view></router-view>
    </div>
</template>

Routes paths:

export const routes = [
  { path: '', component: Home },
  { path: '/newpage', component: Newpage}
];

Main page: (home.vue component)

   <div>
      //scrolling button
      <a href="#scroll"><button type="button">scroll</button></a>
      <div id="scroll"></div>
      //route - new component name is 'newpage'
      <router-link :to="'newpage'" tag="button">component</router-link>
   </div>

Component 'newpage':

<div>
     <router-link :to="'/'" tag="button">Home</router-link>
</div>

Scrolling code:

$(function () {
  $('a[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

      if (target.length) {
        $('html,body').animate({
          scrollTop: (target.offset().top)
        }, 1500, 'easeInOutQuart');

        return false;
      }
    }
  });
});

What can I do to make it work?

Upvotes: 2

Views: 1161

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50767

You probably need event delegation:

$(document).on('click', 'a[href*=#]:not([href=#])', function () {
    // ...the rest of your code
});

The reason being is that the element you are attempting to bind to is being removed when the page changes and added after it changes back. Event delegation is a work around on this by allowing the event to bubble up and attach to something static.

However, for performance reasons, it would be best if you bound the delegated event to a closer, static element, such as #app.

Upvotes: 3

Related Questions