views:

50

answers:

2

Im trying to show/hide a div using jquery when a link gets clicked. I put this in my head section:

<script type="text/javascript"> 
  $("#attach_box").click(function {
    $("#sec_box").show()
    });        
</script>

I have a link that looks like this:

<a href="#" id="attach_box">+ Add a Postal Address (If Different)</a>

And a div that looks like this:

<div id="sec_box" style="display: none;">
Hello world!!               
</div>

This doesn't work and I can't figure out why. Any ideas?

+7  A: 

You need to attach the click handler in the document.ready in order to make sure that the DOM has been loaded by the browser and all the elements are available:

<script type="text/javascript"> 
   $(function() {
       $('#attach_box').click(function() {
           $('#sec_box').show();
           return false;
       });        
   });
</script>

Also you forgot to put parenthesis () next to the anonymous function in the click handler.

Darin Dimitrov
I'd also add `return false;` to the end of the function so that the # doesn't end up in the location, but that's just a personal preference.
Daniel Schaffer
@Daniel, good remark, I've updated my post.
Darin Dimitrov
That works beautifully. Any idea how I could go about hiding the div when the user clicks the link a second time?
Thomas
@Thomas, yes, try `$('#sec_box').toggle();`
Darin Dimitrov
Worked like a charm, thanks!
Thomas
+1  A: 

Chances are the DOM isnt fully loaded yet.

   <script type="text/javascript"> 
      $(document).ready(function()
      {  
         $("#attach_box").click(function() {
         $("#sec_box").show()
         });  
       });      
   </script>

put that in your head and put your initialization code in there.

Climber104