Home > Software engineering >  Javascript works in html but won't work in .js file
Javascript works in html but won't work in .js file

Time:01-24

I am very new to JavaScript and have a bit of code that works when included directly in my html file, but when I try and put it into the .js file I am building for my website, it stops working.

Is the "$" being in the .js file causing the problem?

How do I re-write this code so that it can be used in my JS file?

<div id="section1" > 
  <a >Option 1</a>
  <div >
     <div >item 1</div>
     <div >item 2</div>
     <div >item 3</div>
  </div>
</div>

   <script>
   $('body').click(function() {
      $('div.childSection').hide();
        });
      $(".dropSection a").click(function(event) {
          var parent = $(this).parent();
          parent.toggleClass("selected");
          parent.find("div.childSection").toggle();
          parent.find("section-content").toggle();
          event.stopPropagation();
        });
  </script>

EDIT: In the section I have a working script reference to jquery-3.6.1.min.js as well as my personal .js file (which does have other working script in it - they just don't used the $ format)

CodePudding user response:

The "$" being in the .js file is not causing the problem. "$" symbol is being used as a shorthand for the jQuery library which also you need to import in your .html file in <head> section.

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

You need to wrap your js code in $(document).ready(function($), because it ensures that the code inside the function only runs after the DOM is fully loaded and ready. So, your finaly script.js file will be somethig like this. Also you need to import script.js in your html file.

$(document).ready(function ($) {
    $("body").click(function () {
        $("div.childSection").hide();
    });
    $(".dropSection a").click(function (event) {
        event.stopPropagation();
        var parent = $(this).parent();
        parent.toggleClass("selected");
        parent.find("div.childSection").toggle();
        parent.find("section-content").toggle();
    });
});
  • Related