HTML file unable to call javascript file

HTML file unable to call javascript file
0

#1

Hi, I have coded one HTML file name file1.html and one Javascript file program.js and try to invoke the javascript file in the HTML file. But it failed to invoke. Did i do any mistake ? Please help to let me know.

my program.js file is

<script>
 $(document).ready(function(){
$("#target1").css("color","red");
  });
</script>

and file1.html file is

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<script type="text/javascript" src="program.js"></script>
<p id= "target1">Javascript</p>
</body>
</html>

#2

You also have to import jQuery to your page. Add this inside your <head> tags:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

#3

Hi Kevcomedia
It’s still not running.


#4

By any chance, do you have <script> tags in your JavaScript file? There shouldn’t be any in that file.


#5

So, the code should be like this

$(document).ready(function(){
$("#target1").css("color","red");
  });

I have changed it. Still not running.


#6

I have it running over here. Can I see your files?


#7

I have only those two files with only those code. Is there any mistake in my codes ? The browser shows only "Javascript " without changing any color to red.


#8

I want to see the changes that you’ve made.


#9

HTML file

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="program.js"></script>
<p id= "target1">Javascript</p>
</body>
</html>

program.js file

$(document).ready(function(){
$("#target1").addClass("color","red");
  });

#10

Ok, I think I’ve found it. In your JS, addClass should be css. It was correct the first time you posted :wink:


#11

Sorry, That was I tried. still not running:sob::sob::sob:


#12

Huh? :confused: How come? I’ve copied and pasted your code and that’s the only part that I’ve changed.

Are you sure your JS file is being loaded? Just for kicks, try adding console.log('hello'); at the very top of your JS file, then reload and check your browser’s console.

Or move the <script> tag (the one that points to your JS file) right before the closing </body> tag.


#13

where/how are you testing your code? via a local web server? or on codepen? or a 3rd-party web host?


#14

Testing my code in google chrome.


#15

Alass :rofl::rofl::rofl::rofl: it ran…Thank u. thanks a lot @kevcomedia.


#16

Hi, you need to put the script tag after the p tag. Try this:

<body>
<p id= "target1">Javascript</p>
<script type="text/javascript" src="program.js"></script>
</body>

#18

Great! How did you fix it?


#19

Actually I found that my console was invoking a previous version file and was not updating the corrections. Your suggestion for using the console in chrome help me track the file and i could run the updated file.