0

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 (the button has an anchor and the slides within the swiper have 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.

When I click on the back button, I want to add a smooth scroll to the desired slide (which is on another page), not just an instant jump. That's why hash is useless in this case, so 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 class="back" id="Project-1" onclick="redirect()"></button> // one page

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

The thing now is that those 3 groups of code work well alone, but not together. To be more precise, these 3 variables used to extract a number, somehow block the last condition, even if I put the fixed number in slideTo(), it doesn't work, until I remove the variables above. 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 and extracted that number, and then forwarded it to slideTo(). It just doesn't work and I can't find a reason why.

Katarina Perović
  • 361
  • 1
  • 5
  • 22
  • you could jquery hide to hide the slider and then call the show method after the ```swiper.slideTo(hash);``` line call and you can check for ```this. hash; ``to see if it's a back page action to know if you need to hide it in the first place, would that work for you? – Patrick Hume Aug 02 '22 at 22:43
  • I am a complete beginner in JS, so I didn't understand a thing except the first part to hide the slider. I don't know how to do anything of that :D But thank you – Katarina Perović Aug 02 '22 at 22:57

3 Answers3

1

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

Patrick Hume
  • 2,064
  • 1
  • 3
  • 11
  • Thank you so much, I get what you did here. But, unfortunately, it doesn't work and I have just realized why. Swiper doesn't allow to forward the hash location to slideTo(), but only the numbers. For this time, I made the script that works another way, I'm gonna edit the question, but it doesn't work again, and this time I just don't know why. I'm gonna explain everything. – Katarina Perović Aug 03 '22 at 00:53
  • I have just edited the question, please take a look. – Katarina Perović Aug 03 '22 at 01:11
  • have posted something I hope that will help explain – Patrick Hume Aug 03 '22 at 01:46
1

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?

Patrick Hume
  • 2,064
  • 1
  • 3
  • 11
  • The only reason my code is not working is not because of this, but because it needs to save the extracted data (number) when getting back to swiper page. Those are two different pages and when you extract data from the first one, you get nothing on the another page... – Katarina Perović Aug 03 '22 at 09:17
  • I know the code works if I use console.log, it extracts the right number this way which needs to be forwarded to slideTo(), but how when it loses that data on another page... Because you are getting the number based on a button on one page, and doing the slideTo using that number on another page. So my code should be modified another way. Something should be added to store the data. – Katarina Perović Aug 03 '22 at 09:18
  • Using your technique, I managed to make it work, I will post it in the answers. Thank you so much. – Katarina Perović Aug 03 '22 at 14:14
  • were you able to work it out in the end ? – Patrick Hume Aug 03 '22 at 17:11
  • Yes, take a look at the answer. But I accepted yours as correct since you helped so much! Thanks! – Katarina Perović Aug 03 '22 at 17:21
  • ah ok that's alright glad i was able to help even if only a bit ;) – Patrick Hume Aug 03 '22 at 17:54
0

Thanks to @Patrick Hume, I managed to solve the problem. When redirecting to the location and adding parameters in the URL, I immediately added the number as well. That way, the slide number is passed on another page and we have the information we need.

Now, on the swiper page, we extract that number from the URL and go to the desired slide.

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

$(document).ready(function() {

  $(".back").click(function redirect() {
    var button = $(".back")[0].id;
    var replace = button.replaceAll("-", " ");
    var number = projects.indexOf(replace);
    window.location.replace('../portfolio.html?SlideTo=' + number);
  });


  if (new URLSearchParams(window.location.search).has('SlideTo')) {
    var location = window.location.search.split("=").pop();
    swiper.slideTo(location);
  } else {
    swiper.slideTo(1);
  }

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

<div class="swiper-slide"></div> // another page
Katarina Perović
  • 361
  • 1
  • 5
  • 22