10

i am trying to get jquery to hide this div and for some reason it is not working what am i doing wrong

http://stat-me.com/jq.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#one{
    border:3px solid #00F;
    width:50%;
}
#hideme{
    border:3px solid #00F;
    width:50%;
    display:none;
}
</style>

<script type="text/javascript" src="../_root/js/jquery/jquery-1.4.2.js"></script>

<script language="javascript" type="text/javascript">



$("#one").click(function () {
$("#hideme").toggle();
});

</script>

</head>

<body>

<div id="one">
<a href="#">hello</a>
</div>

<div id="hideme">
hi
</div>


</body>
</html>

3 Answers 3

19

You need to:

  1. Use document.ready
  2. Select the anchor underneath the #one div, not the div itself

So it should be:

$(document).ready(function() {
  $("#one a").click(function() {
    $("#hideme").toggle();
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Both gotchas I've encountered maaaany times :)
2

Your not wrapping your javascript in $(document).ready(function(){}) etc do jQuery is trying to find an element that doesn't exist yet!

Comments

1

I am having the same situation while using ajax and applied this solution. Write javascript:void(0); instead of a '#' in href value. this prevents you to add '#' in url. use .live() when using in ajax mode. in .toggle(), pass argument as effect like 'Drop', 'slide' etc, more at http://jqueryui.com/toggle/.

$(document).ready(function(){
        $('#one a').live('click', function(){
            $('#hideme').toggle('Drop');
            return false;
         });
     });

Applying return false; at last preventing me to reload the page.

Answered just for knowledge.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.