patternjavascriptMinor
Bringing content from other pages without refreshing the entire page
Viewed 0 times
withouttheentireotherpagesrefreshingpagecontentfrombringing
Problem
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();
}
});Solution
You seem to have some copy pasted code there.
How about
The things you do with
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.Code Snippets
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" );
});Context
StackExchange Code Review Q#37157, answer score: 4
Revisions (0)
No revisions yet.