Answer the question
In order to leave comments, you need to log in
How to implement the history API to return to the previous page state?
I really need help! There is no one to ask and all hopes are only on you.
I'm doing a trial webshop and I'm running into a problem.
When switching from the product card back to the catalog, the mobile version of the Chrome browser scrolls the screen to the very bottom.
The catalog is uploaded from a JSON file, here is an example code for uploading a product card:
function loadGoods(){
$.getJSON('goods.json', function (data) {
let out = ''
function showMansGoods() {
for (let key in data){
if (key > 1000 && key < 2000){
out+='<div class="single-goods" data-price="'+data[key].cost+'" id="'+data[key]['article']+'">'
out+= '<div class="goodsCart">'
out+='<img src="'+data[key].img4+'" alt="">'
out+='</div>'
out+='<a class="getArticle" data-art="'+key+'" href="goodsDetails.html">'
out+='<h3>'+data[key]['name']+'</h3>'
out+='</a>'
out+='<p>Цена: '+data[key]['cost']+' руб</p>'
out+='<button class="addToBag" data-art="'+key+'">В корзину</buttondata-art>'
out+='</div>'
}
if (key > 4000 && key < 4050){
out+='<div class="single-goods" data-price="'+data[key].cost+'">'
out+= '<div class="goodsCart">'
out+='<img src="'+data[key].img+'" alt="">'
out+='</div>'
out+='<a class="getArticle" data-art="'+key+'" href="goodsDetails.html">'
out+='<h3>'+data[key]['name']+'</h3>'
out+='</a>'
out+='<p>Цена: '+data[key]['cost']+' руб</p>'
out+='<button class="addToBag" data-art="'+key+'">В корзину</buttondata-art>'
out+='</div>'
}
$('.manGoodsPage').html(out)
}
}
showMansGoods()
})
}
let goodsHistory = Array.from(document.getElementsByClassName('single-goods'));
function selectGoods(id){
goodsHistory.forEach(b => {
b.classList.toggle('selected', b.id === id);
});
}
goodsHistory.forEach(b => {
let id = b.id;
b.addEventListener('click',e =>{
history.pushState({id}, null, './${id}');
selectGoods(id);
});
});
window.addEventListener('popstate', e => {
selectGoods(e.state.id);
});
history.replaceState({id: null}, 'Default state', './index.html');
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question