Barba: Custom prevent event does not work as described in the documentation

Created on 28 Jul 2020  路  3Comments  路  Source: barbajs/barba

I using the prevent function to check if clicked link is same than the current page to prevent page reload.

In the documentation it's said :
prevent: ({ el }) => el.classList && el.classList.contains('prevent')

When I use the same method as described and click on a current page link, the page reload :
prevent: ({ href }) => href === window.location.href

I've found a working alternative :
prevent: e => e.href === window.location.href ? e.event.preventDefault() : false

This is working properly but the console nevertheless print this :

image

Would it be possible to clarify the subject to understand what would be the best practice to carry out my action ?

documentation

All 3 comments

Salut @pierredarrieutort :smiley: !

I will give a look at this tomorrow and give a feedback.
Thanks a lot :wink:

Salut @pierredarrieutort,

Well, I have took the time to check the documentation, and everything looks fine as it is described: you can use a custom prevent test to tell Barba to not do a page transition on specific eligible links... but this do not mean that the link event will be automatically prevented. That's why you get a page reload: as link is prevented, Barba won't play a transition and will fallback to the browser default behavior.

The best way to achieve what you want is to use this approach:

barba.init({
  prevent: ({ event, href }) => {
    if (event.type === 'click') {

      // prevent the user to reload the page if the location is the same
      if (href === window.location.href) {
        event.preventDefault();
        event.stopPropagation();

        // automatically scroll to the top of the page on same location
        if (window.scrollY !== 0) {
          window.scroll({
            top: 0,
            left: 0,
            behavior: 'smooth'
          });
        }

        return true;
      }
    }
  }
});

This example ca be seen on www.kyoso.fr.

If the user is on the same location than the current clicked link, the page will automatically scroll to the top and user will stay on the same page.

Hope the explanation is clear.
Feel free to close the issue :wink:

Salut @xavierfoucrier !
It's good for me, I had not thought enough about my function, thank you again 馃槢
__
_Resolved, will be closed_

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pburdylo picture pburdylo  路  3Comments

luglio7 picture luglio7  路  4Comments

ProdesignerAgency picture ProdesignerAgency  路  3Comments

oguilleux picture oguilleux  路  3Comments

iamtompickering picture iamtompickering  路  3Comments