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.
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