4
\$\begingroup\$

I wrote my first AJAX script that brings content from other pages without refreshing the entire page. I just want to see if improvements can be added to it, or if I'm doing something not recommended.

$(function(){
    // content container content loader
    $("#nav-tabs-list a").click(function() {
        var page = this.hash.substr(1);
        //$("#sidebar-content-container").html(""); // displays content only after fully loaded
        $.get("content/" + page + ".php", function(gotHtml) {
            $("#content-container").html(gotHtml);
        });
    });
    if ( location.hash ) {
        $("a[href="+location.hash+"]").click();
    } else {
        $("#nav-tabs-list a").click();
    }

    // sidebar content loader
    $("#sidebar-container #sidebar-tabs-container a").click(function() {
        var page = this.hash.substr(1);
        //$("#sidebar-content-container").html(""); // displays content only after fully loaded
        $.get("content/sidebar-content/" + page + ".php", function(gotHtml) {
            $("#sidebar-content-container").html(gotHtml);
        });
    });
    if ( location.hash ) {
        $("a[href="+location.hash+"]").click();
    } else {
        $("#sidebar-container #sidebar-tabs-container a").click();
    }
});
\$\endgroup\$
  • \$\begingroup\$ I assume this is jQuery? What javascript library are you using? \$\endgroup\$ – Daniel Dec 11 '13 at 20:03
4
\$\begingroup\$

You seem to have some copy pasted code there.

How about

function enableLinks( selector , path , container )
{
  /* Allow ajax to work */
  $( selector ).click( function()
  {
    var page = this.hash.substr(1);
    $.get( path + page + ".php", function( html ) 
    {
      $( container ).html( html );
    });    
  });
  /* Allow bookmarks to work */
  if ( location.hash )
    $("a[href="+location.hash+"]").click();
  else
    $(selector).click();
}

$(function()
{
  enableLinks( "#nav-tabs-list a" , "content/" , "#content-container" );
  enableLinks( "#sidebar-container #sidebar-tabs-container a" , 
               "content/sidebar-content/" ,
               "#sidebar-content-container" );
});

The things you do with location.hash are a bit of a mystery to me.

\$\endgroup\$
  • \$\begingroup\$ @tomdenmuyt Your code seems the simplest and works. But when i try to navigate to a specific page it does not work for example localhost/TEMPLATE/#features in my code i go to the features page yet i cant in yours. How do i fix that? \$\endgroup\$ – thed Dec 11 '13 at 21:38
  • \$\begingroup\$ @JarolinVargas Try now \$\endgroup\$ – konijn Dec 11 '13 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.