Back button of the browser is not working + content is not loading if don't click on refresh button

106
March 06, 2022, at 7:20 PM

I am really new to JS/jQuery/Ajax I have this code. I want that the content in article tag change but to keep all the rest (header, menu and footer) stays the same while the user click on a link of on the website. I absolutely don't want to have the full page reloading entirely because it causes a poor user experience. This works perfectly and the code is loading the new page, title is changing when you click on a link BUT the back button of the browser does no longer works, title is still the same as the page I was on, really annoying. What should I do to fix this really annoying issue?

$(function() {
  var $article = $("article"),
  
      init = function() {
        // Do this when a page loads.
      },
      ajaxLoad = function(html) {
        document.title = html
          .match(/<title>(.*?)<\/title>/)[1]
          .trim();
        init();
      };
  init();
  $(document).on("click", "a, area", function() { 
    var href = $(this).attr("href");
    history.pushState({}, '', href);
    $article.load(href + " article>*", ajaxLoad);
    return false;
  });
});

Thanks so much for your help!

Answer 1

I added that after the last init()

and it works perfectly!

$(window).on("popstate", function(e) {
    if (e.originalEvent.state !== null) {
      loadPage(location.href);
    }
  });
    
  loadPage = function(href) {
    $article.load(href + " article>*", ajaxLoad);
  };
Rent Charter Buses Company
READ ALSO
`element.innerHTML` not working as expected

`element.innerHTML` not working as expected

I have a form on whose submission, will post a URL, and the server returns a HTML string which should be appended to the form

98
How to call method Model in jQyery

How to call method Model in jQyery

I have a path method in the Course model

112
Jquery data tables need to show only selected rows from an integer array of IDs

Jquery data tables need to show only selected rows from an integer array of IDs

I have a drop down with checkboxes in itWhen I select multiple items, I have a method which gets those IDs in an integer array

125