Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .load (or $.ajax) to get and set page title?

So far...

$('#container').load(hash + ' #page','', function() { 
    $('#container').fadeIn('fast');
    document.title = $('#title').load(hash + ' #title').text();
    });

...doesn't work. Is there a better/correct way to do this?

FYI: -

  • I've added the ID #title the tag (all pages/it's a PHP template).
  • The container is .fade(ed)Out beforehand (less important)

Thanks in advance.

like image 660
LeslieOA Avatar asked Jan 22 '10 05:01

LeslieOA


2 Answers

The problem is that, at the time you assign to document.title, the $('#title').load(hash + ' #title').text() might not have finished yet. Try setting the new document.title in the callback of that .load.

UPDATE

Try:

$('#container').load(hash + ' #page','', function() { 
    $('#container').fadeIn('fast');
    $('#title').load(hash + ' #title', '', function(data) {
        document.title = $(this).text();
        });
    });
like image 109
Nikki Erwin Ramirez Avatar answered Sep 27 '22 19:09

Nikki Erwin Ramirez


I had the same requirement, to update the title for the page after ajax loads and that's what I used – one request, no need to set special attributes in your HTML:

var contentWrap = $('#content-wrap'),
    contentId = '#content';

$.ajax({
  url: hash.replace(/^#!\//, '') + '.html',
  success: function(text) {
    var oldContent = contentWrap.find(contentId),
        newPage = $(text),
        newContent = newPage.find(contentId);

    oldContent.remove();
    contentWrap.append(newContent);
    // Set New Title
    document.title = newPage.filter('title').text();
  }
});
like image 28
Misha Reyzlin Avatar answered Sep 27 '22 19:09

Misha Reyzlin