Use jQuery in a JS file

Asked

Viewed 1,050 times

0

I’m a beginner and I would like a help if possible... I have file index.html, which I’m importing the jQuery:

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

I want to write the scripts of this page in another file (in my case, index js.). I’m already importing this JS file into my HTML file:

<script src="script/index.js"></script>

That is, I want to use jQuery in this index.js file to interact with index.html. I used the import $ from 'jquery', but it doesn’t work. I did another test by installing jQuery via NPM and importing into the index.html page, but I can’t import into the index.html page either. The error that appears in the browser console is:

SyntaxError: import declarations may only appear at top level of a module

How then can I import jQuery into a JS file so that I can develop the interactions of an HTML file?

  • Read this here https://developer.mozilla.org/en-US/docs/Glossario/Hoisting see if this helps.

  • Please [Dit] and provide a [mcve] of the problem to enable the post.

3 answers

3

You do not need to make any statement within the index js., if you include calls to both scripts, you can normally use jquery in your js file.

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

<script src="script/index.js"></script>

0

Both jQuery and any other JS file should be imported into the gave head of each HTML that uses them.

<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 
</script>
      <script src="script/index.js"></script>
   </head>
   <body>

   </body>
</html>

0

You can follow the steps that are in this answer of a question similar to yours in the Stack Overflow.

If you want to include jQuery code from another JS file, the following should serve:

I had the following in my HTML file:

<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>

I created a separate my_jquery.js file with the following:

$(document).ready(function() {
  $('a').click(function(event) {
    event.preventDefault();
    $(this).hide("slow");
  });
});

I hope it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.