JQuery hide question

Hi all,

I am currently learning Jquery and have a small question

I am trying to hide this code:


<p id="disclaimer">
  Disclaimer! This service is not intended for the those with criminal intent. Celebrities are kind of like people so their privacy should be respected.
  <button>Hide 'em</button>
</p>

using this code

 <script>
		 $('button').click(function() {
				$('#disclaimer').hide();
			});
	  </script>

This works fine when I place this code under the html in the main source, but if I try to add this Jquery code to an external js sheet it doesnt seem to work?

Currently my js sheet is called in the header, when I move this link to the footer of my page the code works again, so Im guessing this has something to do with where the jquery code is placed in relation to the code Im trying to hide?

In that case can anyone explain how I can keep my js in the header but still make the content disappear on click?

Thanks!!

It’s because you’re binding an event to an element that hasn’t been loaded yet.
You load your .js file with this statement, however the actual HTML markup is loaded at later point (after the .js). Hence, it’s not “seen” to put it bluntly.

Solution #1 - use jQuery.live().

<script>
$("button").live('click', function(){ your code here });
</script>

Solution #2 - use $(document).ready();


<script>
$(document).ready(function()
{
    $("button").click(function(){ your code here });
});
</script>

More info on what $(document).ready() is can be found here: http://www.learningjquery.com/2006/09/introducing-document-ready

Thats awesome furicane, thanks loads.