简体   繁体   中英

Cannot get this simple script to run correctly

I am a beginner to JavaScript and jQuery.

My objective is to use the slideToggle() function in jQuery to hide/show <div> sections in HTML(inspired by the answer to [this question]( How can I expand and collapse a <div> using javascript? ). Cannot get it to work though :(

Here is what I have tried:

1 test.html (in my Desktop directory)

<html>
    <title>Test jQuery</title>
    <head>
        <script charset="UTF-8" src="jquery.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css"/>
        <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>

        <script language="JavaScript">
        $(".header").click(function() {

            $header = $(this);
            //getting the next element
            $content = $header.next();
            //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
            $content.slideToggle(500, function() {
                //execute this after slideToggle is done
                //change text of header based on visibility of content div
                $header.text(function() {
                    //change text based on condition
                    return $content.is(":visible") ? "Collapse" : "Expand";
                });
            });
        });
        </script>
    </head>

    <body>
        <div class="container">
            <div class="header">
            <span>Expand</span>
            </div>

            <div class="content">
                <ul>    
                    <li>This is just some random content.</li>
                    <li>This is just some random content.</li>
                    <li>This is just some random content.</li>
                    <li>This is just some random content.</li>
                </ul>
            </div>
        </div>
    </body>
</html>
  1. I have downloaded jquery-1.12.0.min.js, renamed it to jquery.js and it's in the same local directory as test.html (viz. Desktop)

  2. style.css (on the Desktop)

     .container { width: 100%; border: 1px solid #d3d3d3; } .container div { width: 100%; } .container .header { background-color: #d3d3d3; padding: 2px; cursor: pointer; font-weight: bold; } .container .content { display: none; padding: 5px; } 

I have searched and read answers to the following questions already:

Local jQuery.js file not working

Why jQuery does not work on my home (local) machine?

...but seem to be still doing something basic wrong. Any help would be much appreciated!

First of all, language="JavaScript" should be type="text/javascript"

Second, you need to wrap your code into $(document).ready(....) - note that this is better practice than to simply trust on the order of the html, although you should have the scripts at the bottom of your body

See working snippet below

  .container { width:100%; border:1px solid #d3d3d3; } .container div { width:100%; } .container .header { background-color:#d3d3d3; padding: 2px; cursor: pointer; font-weight: bold; } .container .content { display: none; padding : 5px; } 
 <html> <title>Test jQuery</title> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" /> </head> <body> <div class="container"> <div class="header"> <span>Expand</span> </div> <div class="content"> <ul> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> </ul> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $(".header").click(function() { $header = $(this); //getting the next element $content = $header.next(); //open up the content needed - toggle the slide- if visible, slide up, if not slidedown. $content.slideToggle(500, function() { //execute this after slideToggle is done //change text of header based on visibility of content div $header.text(function() { //change text based on condition return $content.is(":visible") ? "Collapse" : "Expand"; }); }); }); }); </script> </body> </html> 

This is because your script is run before your elements have loaded, thus not having any elements to act upon. Simply move the script under the content, or add a $('document').ready() . $('document').ready() :

 div.content { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html> <title>Test jQuery</title> <head> <link rel="stylesheet" type="text/css" href="style.css"/> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/> <script language="JavaScript"> $('document').ready(function() { $(".header").click(function() { $header = $(this); //getting the next element $content = $header.next(); //open up the content needed - toggle the slide- if visible, slide up, if not slidedown. $content.slideToggle(500, function() { //execute this after slideToggle is done //change text of header based on visibility of content div $header.text(function() { //change text based on condition return $content.is(":visible") ? "Collapse" : "Expand"; }); }); }); }); </script> </head> <body> <div class="container"> <div class="header"> <span>Expand</span> </div> <div class="content"> <ul> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> </ul> </div> </div> </body> </html> 

Moving script:

 div.content { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <html> <title>Test jQuery</title> <head> <link rel="stylesheet" type="text/css" href="style.css"/> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/> </head> <body> <div class="container"> <div class="header"> <span>Expand</span> </div> <div class="content"> <ul> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> <li>This is just some random content.</li> </ul> </div> </div> <script language="JavaScript"> $(".header").click(function() { $header = $(this); //getting the next element $content = $header.next(); //open up the content needed - toggle the slide- if visible, slide up, if not slidedown. $content.slideToggle(500, function() { //execute this after slideToggle is done //change text of header based on visibility of content div $header.text(function() { //change text based on condition return $content.is(":visible") ? "Collapse" : "Expand"; }); }); }); </script> </body> </html> 

$(".header").click(function() .. fails, because the div with the class 'header' doesn't exist yet when the script is executed.

There are several ways to solve this. One is wrapping everything in a function that is only executed when the DOM is fully loaded , another is moving the script to the end of the page, so it is executed when the div is available.

But my personal favorite is using on to bind events .

Old:

$(".header").click(function() {

New:

$(document).on("click", ".header", function() {

As adeneo already stated in his comment, your JavaScript is at the wrong position in your HTML. The browser executes the code as soon as he sees it. Now in your example, the code is in the header, but your code tries to work with an element, which will be defined later in the file. Of course this cannot work, as the element does not exist at the time of the execution. There are two solutions:

  • Move your code: You can move your JavaScript to the end of the HTML page, just above the closing </body> tag

  • Use $( document ).ready() : You can give this function a function, that will be called as soon as the document is ready and all HTML elements are parsed and useable for the JavaScript. See this example, taken from the JQuery site

     // A $( document ).ready() block. $( document ).ready(function() { console.log( "ready!" ); }); 

Additionally, the use of the language="JavaScript" tag is obsolete and was never really standardized. You should use the type attribute. See this MDN entry .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM