Search code examples
jqueryhtmlslidetoggle

slideToggle not working with button activation


I've stripped away all the CSS and extra HTML and left a bare bones jsFiddle which demonstrates my failure to get this to work: http://jsfiddle.net/95vme63e/

<div class="sectionHeader1"> 
  <div>
    <p class="sectionTitle"> 1: Description </p> 
    <button type="button" class="sectionButton questioner">Button</button>
    <div class="questions">
      <ul>
        <li> Question one </li>
        <li> Question two </li>
      </ul>
  </div>
</div>

$(".questioner").on("click", function () {
  $(".questions").slideToggle(500);
});

.sectionHeader1 .questions {
    display: none;
    float: left;
    width: 100%;
}

I want to click a button which toggles whether a set of questions is visible. Currently, clicking that button seemingly does nothing. Originally I had a lot of CSS and extra HTML elements and thought this must be contributing but I've removed pretty much everything I thought to be non-essential and the problem persists.

If anyone could point out my mistake or offer any advice that would be great, Thanks!


Solution

  • As mentioned in the comments, your problem is that you have not included jQuery.

    See example:

    $(".questioner").on("click", function () {
      $(".questions").slideToggle(500);
    });
    .sectionHeader1 .questions {
        display: none;
        float: left;
        width: 100%;
    }
    <div class="sectionHeader1"> 
      <div>
        <p class="sectionTitle"> 1: Description </p> 
        <button type="button" class="sectionButton questioner">Button</button>
        <div class="questions">
          <ul>
            <li> Question one </li>
            <li> Question two </li>
          </ul>
      </div>
    </div>

    The error is

    enter image description here

    Which is revealed by looking at the console log (In developer tools)

    Include jQuery by putting this:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    

    in either the <head> tag or the <body> tag and it should will work flawlessly.

    $(".questioner").on("click", function () {
      $(".questions").slideToggle(500);
    });
    .sectionHeader1 .questions {
        display: none;
        float: left;
        width: 100%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <div class="sectionHeader1"> 
      <div>
        <p class="sectionTitle"> 1: Description </p> 
        <button type="button" class="sectionButton questioner">Button</button>
        <div class="questions">
          <ul>
            <li> Question one </li>
            <li> Question two </li>
          </ul>
      </div>
    </div>