April 27, 2012

jQuery: How to close ajax loaded page and bring back old content?

Question by jwaldeck

I’m developing a one page portfolio site which will pull projects from separate html files. So, currently I have this code that loads the new URL (specifically the “#project” div) into the current div “#port-content”.

Part of my custom.js follows:

var hash = window.location.hash.substr(1);
var href = $('.ajax').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
    var toLoad = hash+'.html #project';
    $('#port-content').load(toLoad)
        }                                           
    });

    $('a.port-more').click(function(){                        
        var toLoad = $(this).attr('href')+' #project';
        $('#port-content').hide('normal',loadContent);
        window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
        function loadContent() {
            $('#port-content').load(toLoad,'',showNewContent())
        }
        function showNewContent() {
            $('#port-content').show('normal');
        }
        return false;
    });

How can I close this content and bring back my original “#port-content” div. I tried to create a new fucntion doing the opposite but it didn’t work.

Any ideas?

Tks in advance!
jw

Answer by Starx

Using .data() sound like the correct option for this.

function loadContent() {
   if(!$('#port-content').data('default')) $("#port-content").data('default', $("#port-content").html());
   $('#port-content').load(toLoad,'',showNewContent())
}
// and create another function to load the default
function loadDefault() {
  $('#port-content').html($("port-content").data('default'));
}
...

Please fill the form - I will response as fast as I can!