SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist kyllle's Avatar
    Join Date
    Jun 2008
    Posts
    469
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JQuery hide question

    Hi all,

    I am currently learning Jquery and have a small question

    I am trying to hide this code:
    HTML 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

    HTML 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!!

  2. #2
    SitePoint Zealot
    Join Date
    Dec 2010
    Posts
    187
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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().

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

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

    Code JavaScript:
    <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/0...document-ready

  3. #3
    SitePoint Evangelist kyllle's Avatar
    Join Date
    Jun 2008
    Posts
    469
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thats awesome furicane, thanks loads.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •