Home > Mobile >  Get smooth scroll to slide on another page using Swiper
Get smooth scroll to slide on another page using Swiper

Time:08-03

When I click the button 'back' on a certain page, it goes back to the page with a swiper and to that slide within a swiper (I used data-hash attribute). The only problem is that it shows the first slide for a millisecond and then jumps to the desired slide. That's because it's not the swiper that controls the sliding to the slide, but just the regular hash that makes it jump to the section.

I want to add a smooth scroll to the desired slide when I click on the back button on another page and here's what I did:

var projects = ["Project 1", "Project 2", "Project 3", "Project 4"];

$(document).ready(function() {

  var swiper = new Swiper('.swiper', {
    // parameters
  });

  $(".back").click(function redirect() {
    window.location.replace('../portfolio.html?swiper=slideTo');
  });

  var button = $(".back")[0].id;
  var replace = button.replaceAll("-", " ");
  var number = projects.indexOf(replace);

  if (new URLSearchParams(window.location.search).get('swiper') === 'slideTo') {
    swiper.slideTo(number); // if I put the fixed number, it would work, but only if I remove these 3 variables above
  };

});
<button  id="Project-1" onclick="redirect()"></button> // one page

<div  data-hash="project-3"></div> // another page

If I put the fixed number in slideTo(), it would work. Obviously I don't want a fixed slide number, but a number based on hash, that's why I made an array of the project names, searched the array for a match using button id, then extracted that number, then forwarded the number to slideTo(). It just doesn't work.

Even if I add a random slide number to slideTo(), it still doesn't work until I remove these variables defined before the last condition. I don't get why. The logic is here, everything seems okay but something about these variables blocks the last condition.

CodePudding user response:

that's ok let me see if I can help you,

first, add css to hie the slider

.mySwiper{
  display:none
}

then you can check if the hash is present and act accordingly

  const hasHash = window.location.hash ? true : false;
  //Use to see hash value
  console.log(window.location.hash.substring(1));
  if (hasHash) {
    $(".swiper").hide();
    setTimeout(function () {
      swiper.slideTo(window.location.hash.substring(1));
      $(".swiper").show();
    }, 175);
  } else {
    $(".swiper").show();
  }

I knocked up a codepen demo for you: https://codepen.io/ptahume/pen/jOzZeVb?editors=1111

although because it's codepen its a bit flaky because seems to only reliably work if the codepen console is open and the page seems to need a moment to load twice because that's just codepen for you but it sort of demonstrates the concept

I hope this helps

CodePudding user response:

are you using hash or query string parameters ?

If you want the hash then

window.location.hash.substring(1)

will give you any value after the hash so if your url was:

http://example.com/MySwiperPage#123

then that would give 123 as the value that the ```swiper.slideTo''' can use, e.g

swiper.slideTo(window.location.hash.substring(1));

but in the amended code above it seems your using query string paramaters ?

...?swiper=slideTo

this is not the same as a hash, if you want to use query string parameters then

function GetQueryStringParams(sParam)
{
    let sPageURL = window.location.search.substring(1);
    let sURLVariables = sPageURL.split('&');

    for (let i = 0; i < sURLVariables.length; i  )
    {
        let sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

if your url was like so:

http://example.com/MySwiperPage?SwipeTo=123

use call the above function like so

var SwipeToNumber = GetQueryStringParams('SwipeTo');

you ideally want to pass a number in the url using hash or query string and then use that number to select the slide you want to jump to

don't know why you need an array or button Id's if you know how many slides you have then you just need to set the slide number to jump to on the back button using the hash or query string parameters

if you really want to use button id then

 var button = $(".back")[0].id;
  var replace = button.replaceAll("-", " ");
  var number = projects.indexOf(replace);

Your code is only ever getting the first button id value and removing the "-" and replacing it with a space which I suspect is making it a none numeric value, ensure the value is a number, you may want to use parseInt and repace the " " with "" to remove the white space

 var button = $(".back")[0].id;
  var replace = button.replaceAll("-", "");
  var number = projects.indexOf(parseInt(replace));

but this in itself will only use the first button Id, if you wanted to search your array or find an id button, again you would need to read in the hash value or query string value to tell the script what your looking for and if your going to do that then you might as well get rid of the array and simply use the value passed to the page directly

I hope this makes sense?

  • Related