Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AJAX to change div content - how do I display navigation as hash / anchor

I want to create a page that refreshes content within a div async alongside providing a user with an anchor to enable direct access to the content within the div. (e.g. www.website.co.uk/#page1)

I've managed to make it so that the content can be updated for 1 page, however, if I add multiple pages it stops working

Additionally - if I was to navigate to the URL website.co.uk/#page1 it wont display #page1.

Can anyone help?

This is my current code:

HTML :

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>

JS :

<script type="text/javascript">
    var routes = {
        '#page1' : '{{site.url}}/page1'
        '#page2' : '{{site.url}}/page2'
    };
    var routeHandler = function( event ) {
        var hash = window.location.hash, 
            xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("div1").innerHTML = xhttp.responseText;
            }
        };
        xhttp.open("GET", routes[hash], true);
        xhttp.send();    
    };
    window.addEventListener('hashchange', routeHandler);
    window.addEventListener('load', function() {
        var hash = window.location.hash;
        if (routes.hasOwnProperty(hash)) routehandler();
    });
</script>
like image 662
David Smith Avatar asked Jul 01 '16 13:07

David Smith


1 Answers

You made some small js errors. So here is you fixed code

html:

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>
<div id="div1"></div>

javascript:

  //change these routs
  var routes = {
    '#page1': '/page1.html',
    '#page2': '/page2.html'
  };

  var routeHandler = function() {

    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById("div1").innerHTML = xhttp.responseText;
      }
    };

    xhttp.open("GET", routes[window.location.hash], true);
    xhttp.send();

  };

  window.addEventListener('hashchange', routeHandler);
  window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (routes.hasOwnProperty(window.location.hash)) routeHandler();
  });
like image 107
Maksym Semenykhin Avatar answered Sep 29 '22 11:09

Maksym Semenykhin