Search code examples
javascriptjqueryanchorfullpage.js

Fullpage.js - Custom button won't update the anchor tag in URL


I'm using fullpage.js to create a site with scrolling slides. Everything is working as expected, except a button that randomizes which slide displays. When the button is clicked, the site scrolls to the expected slide, but the anchor name in the URL bar does not update.

What's strange is if you click the back button on the browser, it DOES display in the URL bar, before returning to the previous slide upon a second click. My assumption is that the actual anchor is being captured correctly, but something is preventing it from displaying in the URL bar.

Here's the code that I'm working with:

// Capture the number of slides
ritualsCount = window.ritualsCount;

// Create the anchors
function buildRitualAnchors() {
  var array = [];

  for (i = 0 ; i < (ritualsCount + 1); i++) {
    array.push("page" + i);
  }
  return array
}

// Randomizer button
$('.randomizer').click(function() {
    var randomNumber = Math.floor((Math.random() * ritualsCount) + 2);
    fullpage_api.moveTo(randomNumber, 1);
});

What am I missing here? I've tried messing around with location.hash but it seems like it's already capturing this information just fine.

You can see the site live here - https://be-inclusive.sypartners.com/


Solution

  • That's because .randomizer is anchor tag. On click of any anchor tag, it has a default behavior of redirecting to it's href. In your case i.e. #, so after your click handler event listener finishes it's execution it's redirecting to anchor tag's href.

    Possible solutions are

    1. You can use event.preventDefault() to stop that default behavior.

      $('.randomizer').click(function() {
           event.preventDefault();
           var randomNumber = Math.floor((Math.random() * ritualsCount) + 2);
           fullpage_api.moveTo(randomNumber, 1);
       });
      
    2. Having/Updating anchor tag's href as per expectations.

    3. Changing <a> to a different element type like <button type="button">.