Search code examples
jqueryhtmltogglegoogle-sites

JQuery toggle button first two clicks don't work as intended


My html code is fairly simple, I want to have a (show/hide) button that when pressed scrolls down the abstract of the paper, and when pressed again scrolls it back up. I use JQuery 1.5 inside an HTML box on a google site. The first line of the html box is

Then the html:

The last part of the html box is the following script:

$("#abstract1").click(function () {
    $("abstract1").slideToggle("fast");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js"></script>

<div><font color="#3d85c6"><b>Working Papers</b></font></div>
    
<div><b><font color="#0b5394"><a>Paper 1</a>
&nbsp;</font></b><button id="abstract1"><b>Abstract</b></button><br/> </div>
<abstract1 style="display:none">
<div style="line-height:175%;margin-bottom:1em"><font size="2"><font size="2">
blah blah blah...
&nbsp;</font></font></div>
</abstract1>

As one that doesn't really know html, I was pretty amazed this works :) The only issue is that on the first click the abstract appears immediately (doesn't slide), and on the second click it appears scrolling down (after it was already visible). Then it works perfectly, scrolling down and up...

What did I do wrong?

Thanks so much!!


Solution

  • Your HTML is invalid. You appear to have invalid tags such as <abstract1> and tend to double up on tags. In the below code snippet I've changed your <abstract1> tags to <div> tags and applied the class of abstract1 to it, allowing you to target the div class by using the selector .abstract1 in your javascript code.

    I've also 'cleaned' up your code a little so it uses more appropriate HTML tags (and removed those that were unnecessary).

    See the code snippet below for a working example:

    $("#abstract1").click(function () {
        $(".abstract1").slideToggle("fast");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div>
      <font color="#3d85c6"><b>Working Papers</b></font>
    </div>
        
    <div>
      <b><font color="#0b5394"><a>Paper 1</a>&nbsp;</font></b>
      <button id="abstract1"><b>Abstract</b></button><br /> 
    </div>
    
    <!-- Here is where you need to change the <abstract1> tag to this div: -->
    <div class="abstract1" style="display:none">
      <span style="line-height:175%;margin-bottom:1em">
        <font size="2">blah blah blah...&nbsp;</font>
      </span>
    </div>