Zyonix
Zyonix

Reputation: 107

jquery ajax() back button wont change content

i made simple $.ajax() with hashchange with local files, however the back button only changes url, not the content. Nothing i found seems to be working for me. COuld anybody help me?

  $(document).on('click', ".nextPage2", () => {
    $.ajax({
      url: 'page2.html',
      dataType: "html",
      success: function(result) {
        $('.content').html(result);
      }
    });
    window.location.hash = 'looks';
    return false;



  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="content"></div>



    <button type="button" class="nextPage2" name="button">page2</button>

Upvotes: 0

Views: 207

Answers (2)

Hele
Hele

Reputation: 415

If page2.html is an Html file, than use .load() function instead .html()

$('.content').load(result);


load() will load data from the server and place the returned HTML into the matched element.
http://api.jquery.com/load/

code in page2.html mustn't have "html", "head" and "body" tags, cause will be inserted inside your .content div



Hope this Help
Hele

Upvotes: 0

Quentin
Quentin

Reputation: 944533

When you change the URL, you are also using JavaScript to modify the DOM.

You need to listen for changes to the URL and use JavaScript to modify the DOM again.

function navigated() {
    if (location.hash === '#something-different') {
        $('.content').html("The content for something-different");
    }
}

window.addEventListener("hashchange", navigated);

Upvotes: 1

Related Questions