Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery show div when link gets clicked

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?

like image 841
Thomas Avatar asked Jun 26 '10 16:06

Thomas


People also ask

How to display div after click the button?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .

What does jQuery show hide do?

You can show and hide HTML elements using the jQuery show() and hide() methods. show() – Display the matched elements. hide() – Hide the matched elements.

How to hide something in jQuery?

jQuery hide() MethodThe hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.


2 Answers

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.

like image 56
Darin Dimitrov Avatar answered Oct 14 '22 18:10

Darin Dimitrov


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.

like image 21
Chris Kooken Avatar answered Oct 14 '22 18:10

Chris Kooken