Creating a friendly URL on a one-page

5

I have a site that is one-page. I separated the screens by <div> to make it easier. However, if I click news it goes correctly to the news screen, but the URL does not change.

How do I include a friendly URL for each "section" of the site? So that Google Analytics correctly captures the URL that the user is.

For example, if I clicked contact , he gave up to the contact section and the URL is www.mysite.com/contact

Below, some of my main structure for the site:

<div class="fundo1">CONTEUDO</div>
<div class="fundo2">CONTEUDO</div>
<div class="fundo3">CONTEUDO</div>
<div class="fundo4">CONTEUDO</div>
<div class="fundo5">CONTEUDO</div>
    
asked by anonymous 17.09.2014 / 14:56

1 answer

7

Using hash ( # ) is a possible solution.

Changing the hash does not cause the browser to trigger a new request.

You can change the hash in two ways:

  • Via links:
  • <a href="#noticias">Notícias</a>
    
  • Via Javascript:
  • window.location.hash = "noticias";
    

    It is possible to trigger an event every time the hash is changed:

    // usando jQuery
    $(window).on("hashchange", function() {
        alert(window.location.hash);
    });
    

    If the user directly accesses a hashed URL as:

    https://www.seu-site.com/#noticias
    

    The ideal is to create an event that loads the requested content:

    // novamente com jQuery
    $(document).on("ready", function() {
        var pagina = windows.location.hash;
        if (pagina === "#noticias") {
            // carrega "Notícias"
        }
    }
    

    To get more DRY, you can create a function that loads the correct page and trigger it in the two events (domready and hashchange):

    var carregaPagina = function() {
        var pagina = windows.location.hash;
        if (pagina === "#noticias") {
            // carrega "Notícias"
        }
    };
    
    $(document).on("ready", carregaPagina);
    $(window).on("hashchange", carregaPagina);
    

    I've assembled a basic example in JSFiddle .

    About Google Analytics

    My Google Analytics experience is zero . But this answer of Stack-EN suggests manually informing the page request in the hashchange event. I have not tested this but I believe this page tells you exactly how to do that.

    There is also the History API

    I will not say much about it, because I have never used it in practice. (It would be good for someone with experience to give an answer about it.)

    Basically it provides a means of artificially manipulating browser history, in conjunction with the URL, via Javascript, without the need to use the hash. This is a new HTML5 feature, and will not work in legacy browsers:

      

    Usefullinks

    17.09.2014 / 18:06