Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I replace the meta title, keywords and description on the ajax loaded html document?

How would I replace the meta title and description on the document with the meta title and description from an incoming html document on an ajax call??

I am calling new content from the #content div on an adjacent html document. What I want to happen is when the new content loads I want to replace the main documents title (and description and keywords... might as well since im tooling around up there anyway) with the meta title in the html file that is being loaded.

I have thought about using replace(); or match(); but I just wanted to find out the best way.

here is the script:

// JavaScript Document
$(document).ready(function() {

    var toLoad
    $(window).bind( "hashchange", function(e) {
            loadcontent();
            return false;

    });



        $('#toc li a').click(function(){
            window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-0);
            var href = $(this).attr( "href" );
            $('meta[name=title]').attr('title', new_title);
            $('meta[name=description]').attr('description', new_description);
            $('meta[name=keywords]').attr('keywords', new_keywords);
            //alert("hey" + window.location.hash);
            $('#breadcrumbs h1').append(" </a><a href='index.html"+ window.location.hash + "' >" + $(this).attr('href') +" ></a>");
            $.bbq.pushState({ url: href });
            $(window).trigger( "hashchange" );

        });

    loadcontent();

});

function loadcontent(){

    var toLoad = window.location.hash.replace("#","") +'.html #content';
            $('#content').hide('slow');
            $('#load').remove();
            $('#conContainer').append('<span id="load">LOADING...</span>');
            $('#load').fadeIn('normal');

            $('#content').load(toLoad,'',function(returnText,status,request){
                showNewContent()
            });

            function loadContent() {
                $('#content').load(toLoad,'',showNewContent());

            }
            function showNewContent() {
                $('#content').show('slow',hideLoader());
            }
            function hideLoader() {
                $('#load').fadeOut('normal');
            }

}
like image 280
DJERock Avatar asked Jun 06 '12 17:06

DJERock


1 Answers

For the title you could do the following:

$('title').html('my new meta title');

Give your meta description and keywords elements an id, so you can easily select the elements:

$('#mdescription').attr('content', 'my new meta description');
$('#mdkeywords').attr('content', 'keyword one, keyword two');
like image 83
Frankey Avatar answered Jan 03 '23 12:01

Frankey