Issue with toggle

Below is test code I’m looking at to get a simple toggle out when I click on toggle link:

The <h2> tage and <a> tag shifts below the <p> block even though it’s wrapped in the code.

Any help with this would be great.

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("a").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>

<p style = "width:100%;height:200px;background-color:lightblue;">
<h2 style = "float:left;">This is a heading.</h2>
<a href="#" style = "float:right;">Toggle</a>
</p>

</body>
</html>

Hi there,

The problem isn’t jQuery, it’s rather that your markup is invalid and the browser is rendering the <h2> tag and the <a> tag outside of the containing <p> tag.

To see what I mean, change your code to this:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("a").click(function(){
        $("div").toggle();
      });
    });
    </script>
  </head>

  <body>
    <div style="width:100%;height:200px;background-color:lightblue;">
      <h2 style = "float:left;">This is a heading.</h2>
      <a href="#" style = "float:right;">Toggle</a>
    </div>
  </body>
</html>