Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I link my HTML with my jQuery?

Firstly sorry for the post, I'm pretty new to coding, I'll try and keep it short and sweet.

Simply put, when I include my jQuery code inline, I.E. beneath my HTML, it works fine - the element I am trying to animate 'hides' and then 'shows' as it should.

However, when I make my own separate jquery.js file and put the code in there, it fails to render.

I've got the cdn script from google and included that, alongside a script and src to where my file is located inside my project folder, but still no luck.

Inside my project folder I have a 'script.js' folder, and then within that a 'jquery.js' file.

Here's the code:

<head>

  <link rel="stylesheet" type="text/css" href="css/style.css"/>

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

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

</head>

<div class="content">
  <h2> Hi there</h2>
  <h3> Take a look...</h3>
</div>

Here's the jQuery:

<script>

$(document).ready(function() {

$(".content").hide(1000).show(1000);

});

</script>

(Upon 'inspecting' the problem in chrome I get an error which says "jquery.js:1 Uncaught SyntaxError: Unexpected token <) - But I can't see where I am mis-using a '<'.

Thanks in advance, and please feel free to tell me if I have left out anything important.

like image 867
skoster7 Avatar asked May 31 '16 21:05

skoster7


People also ask

How does jQuery work with HTML?

At its core, jQuery is used to connect with HTML elements in the browser via the DOM. The Document Object Model (DOM) is the method by which JavaScript (and jQuery) interact with the HTML in a browser. To view exactly what the DOM is, in your web browser, right click on the current web page select “Inspect”.

Why jQuery is not working in HTML?

This indicates jQuery is not present so your code is throwing an error on the $(document). ready(); statement. JavaScript doesn't recognize $ as a function. Be sure to import the jQuery library before your custom script is loaded.

What are different ways to put jQuery in HTML file?

You can easily add jQuery to HTML by using several methods, like adding jQuery from CDN or directly downloading jQuery files and including them into your projects.


1 Answers

You need to remove the <script> tags from your jquery.js file, those are HTML tags that are used for implementing inline JS, the error you are getting is because those tags are not valid JavaScript. Your JS file should just look like this:

$(document).ready(function() {
    $(".content").hide(1000).show(1000);
});

As far as folder naming, there's nothing wrong with having a period in your folder name, but as others have suggested it would probably be a good idea to remove the .js part from your folder name even though it's not technically wrong and not what is causing your issue.

like image 127
APAD1 Avatar answered Oct 03 '22 14:10

APAD1