0

I wrote this very simple code to expand and collapse a text when pressing a button, but it doesn't work.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('.expand').click(function(){
    $('.content').slideToggle('slow');
});
</script>
</head>
<body>
<div class="sitesection">
    <p class="expand"><a href="#">Click Here To Display The Content</a></p>
    <p class="content">Hello World!"</p>
</div>
</body>
</html>

When I click on "Click here to display the content", nothing happens.

Alessandro
  • 79
  • 1
  • 8

2 Answers2

0

put your code to bottom or use DOM ready event

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>
<body>
<div class="sitesection">
    <p class="expand"><a href="#">Click Here To Display The Content</a></p>
    <p class="content">Hello World!"</p>
</div>
<script>
$('.expand').click(function(){
    $('.content').slideToggle('slow');
});
</script>
</body>
</html>
Pasha K
  • 182
  • 6
  • thanks it works! can you explain (or link me an explanation) why the script should be put at the bottom of the body instead of the head? – Alessandro Jun 26 '17 at 12:52
  • @alessandro when the script executing elements must be in DOM https://learn.jquery.com/using-jquery-core/document-ready/ – Pasha K Jun 26 '17 at 13:03
  • @Alessandro the click event is not bind to anything if you do it before the dom elements are created. If you place the .click at the end the dom is ready or you specify in your script document.ready before binding the click event. – user5014677 Jun 26 '17 at 13:06
-1

Try This

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>
<body>
<div class="sitesection">
    <p class="expand"><a href="#">Click Here To Display The Content</a></p>
    <p class="content">Hello World!"</p>
</div>
<script>
$('.expand').click(function(){
    $('.content').slideToggle('slow');
});
</script>
</body>
</html>

Or must call javascript after load document.

Ashish Kadam
  • 1,193
  • 2
  • 10
  • 18