Sean
Sean

Reputation: 141

Jquery Selector Issues

basically I'm trying to get #toggle_box to slide down using Jquery, the code below works if I'm just using document.body as the selector however it doesn't seem to work when #toggle is the selector! Any ideas why?

<html>
<head>

<title>JQuery Testage</title>
<style>
#toggle_box {
 display: none;
}
#toggle {
 background-color: #FFF000;
 border: solid;
}
</style>
</head>
<body>

<script src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$("#toggle").click(function () {
 if ($("#toggle_box").is(":hidden")) {
 $("#toggle_box").slideDown("slow");
 } else {
 $("#toggle_box").hide();
 }
 });
</script>

<div id="toggle">Toggle</div>

<div id="toggle_box">This should silde using the Jquery library 1.4.2</div>

</body>

</html>

Upvotes: 1

Views: 76

Answers (3)

Lazarus
Lazarus

Reputation: 43084

Modify your code thus:

<script type="text/javascript">
$(document).ready(function() {
  $("#toggle").click(function () {
    if ($("#toggle_box").is(":hidden")) {
      $("#toggle_box").slideDown("slow");
    } else {
      $("#toggle_box").hide();
    }
  });
});
</script>

The problem is that the javascript is loaded and executed before the toggle_box element is loaded. It works for the document body as that is loaded before the javascript.

Upvotes: 0

James Long
James Long

Reputation: 4736

Could it be because the DOM isn't ready yet? Try wrapping your script in the following piece of code:

$(function() {
    // your code here
});

That's a short code for $(document).ready(function(){ ...}); and may just be what's missing?

Upvotes: 0

karim79
karim79

Reputation: 342635

Give the click handler a $(document).ready(... wrap, and it should work:

$(document).ready(function() {

     // your click handler and anything else that
     // should run when the DOM is ready

});

Upvotes: 1

Related Questions