0

Hello i'm using the following javascript code which will be in a separate file so that it can be referenced globally across the site.

It allows me to have a global reference for html elements such as footers and menus and include them by id:

<body>

<div id="copyright"></div>

<script>
var copyright = document.getElementById("copyright");
copyright.innerHTML = "<p>&copy; Some Company 2013</p>";
</script>

</body>

This works ok as long as the javascript is placed at the bottom of the page. I was wondering what i might need to modify to allow me to move the script into the header?

Many thanks.

user1741348
  • 193
  • 2
  • 14

1 Answers1

1

Run the code on DOM ready. Not fun without a library like jQuery, but I have to ask why you're doing this at all.

There are far, far better ways to reuse HTML: templating.


Okay, so you're using jQuery. Then you can use the usual, pervasive document ready handling:

$(document).ready(function ()
{
    $('#copyright').html('<p>&copy; Some Company 2013</p>');
});

// or the short-hand version

$(function ()
{
    $('#copyright').html('<p>&copy; Some Company 2013</p>');
});

That said, I still recommend templating instead. You can even do it client-side, with jQuery.

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
  • many thanks. i have used server side includes which work ok as well but i end up with multiple url requests on the same page and thought this way might be simpler as i could include several html elements in one single .js file and then call then by id. – user1741348 Jan 29 '13 at 00:44
  • If you're using jQuery, why are you using `document.getElementById()` instead of `$()`? – Matt Ball Jan 29 '13 at 00:47
  • sorry i'm not a developer and my javascript is very basic. will look into using $(). need to do some more research. Thanks once again for your help. – user1741348 Jan 29 '13 at 00:51
  • I think i've got it $(".footer").load("footer.htm"). Will try this method. Thank you. – user1741348 Jan 29 '13 at 00:55