0

This is my code which doesn't work:

$(document).ready(function() {
 $(document).on('click', '.item', function() {
  $(this).width(120);
 });
});
.item {
 width: 100px;
 height: 100px;
 border-radius: 10px;
 background-color: red;
 margin-right: 10px;
 display: inline-block;
 cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
 <title>jQuery</title>
 <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

<script type="text/javascript" src="script.js"></script>
</body>
</html>

In the browser console it says "$ is not defined" as soon as the page loads. What is the problem?

Xyntell
  • 155
  • 1
  • 14

2 Answers2

2

You have to add the JQuery library,

You can add it in the head section

or right before the script.js import

Felix Cen
  • 733
  • 1
  • 6
  • 24
2

In your <head>, you should import the JQuery library otherwise you won't be able to use JQuery functions:

<script type="text/javascript" src="path/to/jquery.js"></script>

You can also link to online versions of it:

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

JQuery is an external library which means it isn't included in your standard Javascript functionality - you need to import it using the above method in order to make its functionality available for your code to use.

You can download the library from http://jquery.com/download/ or you can use an online version like in my second example. If you download your own version from their website, you then just put it in a folder inside your project and link to it the same way you have done for your other script.

millerbr
  • 2,951
  • 1
  • 14
  • 25