Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
#Return same screen after refresh

I am developing a page that use a ajax request to read a JSON file and I am displaying it by looping on clicks but when I refresh page it returns to first screen is there anyway to return the same screen after I refresh please no JQUERY

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here I have made a "framework" for maintaining the stat of your page.

The AJAX request happens when the hash in the URL changes (here the state is "state1": http://example.org/#state1). There is an event listener for the hashchange event and a function fetshdata().

When clicking the button "Get Data", the hash will change, the hashchange event will happen and the function fetshdata() will be called.

If the page is reloaded (this is your problem) the "state" of the page is maintained in the hash (the hash is still in the URL). To tricker the hashchange event I made the hashchange event "by hand" and dispatch it on the window.

The state of the page could also be maintained in localStorage, but the advantage with the hash in the URL is that the hash change becomes part of the history in the browser and you can save/send/link to the URL etc.

const data = 'data:application/json;base64,W3sidGl0bGUiOiJJdGVtIDEifSx7InRpdGxlIjoiSXRlbSAyIn0seyJ0aXRsZSI6Ikl0ZW0gMyJ9XQ==';

var content;

const fetchdata = hash => {
  let url = hash; //use the hash as part of the AJAX request (not implemented)
  fetch(data).then(res => res.json()).then(json => {
    content.innerHTML = '';
    json.forEach(item => {
      content.innerHTML += `<p>${item.title}</p>`;
    });
  });
};

document.addEventListener('DOMContentLoaded', e => {
  content = document.getElementById('content');
  document.getElementById('btn_load').addEventListener('click', e => {
    location.hash = 'newstate';
  });
  
  document.getElementById('btn_reload').addEventListener('click', e => {
    location.reload();
  });
  
  if(location.hash){
    let event = new Event('hashchange');
    window.dispatchEvent(event);
  }
});

window.addEventListener('hashchange', e => {
  let hash = location.hash.substring(1);
  fetchdata(hash);
});
<button id="btn_load">Get data</button>
<button id="btn_reload">Reload</button>
<div id="content"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!