views:

10291

answers:

7

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?

<script type="text/javascript">
$(document).ready(function() {

    // ???

});
</script>
+7  A: 

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});
roosteronacid
You should post the shorthand thing as a new "Question" in itself. Useful!
MDCore
Not sure I understand you, MDCore.
roosteronacid
Jeff has suggested one uses stackoverflow for those technical tips that one might put on one's blog. I was suggesting posting the tip as a new question that you answer yourself.
MDCore
@MDCore: done: http://stackoverflow.com/questions/182630/jquery-tips-and-tricks
roosteronacid
+5  A: 
<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>
korchev
+13  A: 

The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.

    <script type="text/javascript">
      $(document).ready(function() {

        document.title = 'blah';

      });
    </script>
dimitrisp
Wouldn't any javascript-generated HTML be SEO incompatible? I'm pretty sure googlebot doesn't execute javascript...
Orion Edwards
A: 

Ugh that was such an obvious answer. Should've known that. Thanks.

Jason Miesionczek
Google is your friend: http://tr.im/912
Andrew Hedges
+2  A: 

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

Orion Edwards
+1  A: 

$('title').text("hi")

John Rothfield
+1  A: 

don't use $('title').text('hi') ! because IE doesn't support! better than back is document.title = 'new title'; sorry for my english ;-)

vasio
I found this out myself just today. Functions fine in firefox, javascript errors in IE 8.
numbers1311407