Sunday 31 January 2021

How to avoid duplicate push on top of History Api Stack

I'm facing problem with push duplicate on top of stack History api stack

let say i have user interface with click pattern (1 to 4 pages ,it can be random as per user choice)

Question: i want to push all pages in the same way as it is clicked without duplicate on top of history api, so that when browser forward,backward button is clicked url should change(right now 2 clicks are required)

here is how my project setup will look like (click same page 2 times to see actual issue):

$('li').on('click',function(){
   var baseUrl = location.href;  //'http://www.siliconvalley.com/pages/';//it can be current url also
   var page = $(this).attr('data-page');
   var urlObj = new URL(baseUrl);
   urlObj.searchParams.append('page',page);
   $('#loadedPageContainer').prepend(`<p>${urlObj.href}</p>`);
   try{
       history.pushState({}, null, urlObj.href); //wanted to avoid duplicate on top of history api stack
   }catch(e){}

});

window.addEventListener('popstate', function(e){    
       console.log('page navigated',e);  // called 2 times in my project
      //navigateToCurrentUrlRoute();
});
ul{
  list-style:none;
  display:flex;
  justify-content: space-evenly;
}

ul li{
    border: 1px solid red;
    padding: 50px;
    cursor:pointer;
}

#loadedPageContainer{
    //display: flex;
    width: 500px;
    height: 200px;
    box-shadow: 0 1px 2px 3px #c7c7c7;
      margin: 0 auto;
/*   overflow:auto; */
  overflow-y:auto;
      line-height: 38px;
   padding:15px;
}

#loadedPageContainer p{
      box-shadow: 0 1px 2px 0px #dee5ea;
}

#loadedPageContainer p:first-child {
    box-shadow: 0 4px 2px 1px #de004b;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li data-page="1">page 1</li>
  <li data-page="2">page 2</li>
  <li data-page="3">page 3</li>
  <li data-page="4">page 4</li>
</ul>
<p>Please click same pages 2 or 3 times to see actual issue below or in url on forward,backward browser button click</p>
<div id="loadedPageContainer">
  
</div>

Note: only top of the history api stack should not have duplicates

For better view here is a codepen link: https://codepen.io/eabangalore/pen/KKgOwgN Please help me thanks in advance!!



from How to avoid duplicate push on top of History Api Stack

No comments:

Post a Comment