简体   繁体   中英

Local html file wont run javascript (on any browser)

I tries to search on Google but i'm not sure If any of the questions found really relate to my issue.

It's very simple. I have here on my PC an html file with only a button on the screen.

I have the link to a .css file on the same folder as my html. The .css works well.. the properties of colors and shape are working.

And I also have a .js file with a code that should make a fadeout fadein effect on this button.

I'm learning HTML (and other stuff) on codecademy.com. They have a test environment there and my code works well.

But locally (as I described) the javascript code won't run. No fadeout-fadein effect.

I tried on different browsers (Chrome, IE, Edge...) no deal. Also tried to open all the security on IE allowing active content and many other items.

Below are my codes from html, .css and js:

HTML file (name of the file botao.html):
 <title> Button Magic </title>
     <link rel='stylesheet' type='text/css' href='stylebotao.css' >
     <script type='text/javascript' src='script.js'> </script>
 </head>
 <body>
     <div>  <br/>  strong Click me! </strong>  </div>
 </body>
 </html>

CSS file (Name of the file stylebotao.css)

div  {
    height: 60px;
    width: 100px;
    border-radius: 5px;
    background-color: #69D2E7;
    text-align: center;
    color: #FFFFFF;
    font-family: Verdana, Arial, Sans-Serif;
    opacity: 0.5;
}

Javascript file (Name of the file script,js)

$('div').mouseenter(function(){$(this).fadeTo('fast',1)});
$('div').mouseleave(function(){$(this).fadeTo('fast',0.1)})

What can I do about it?

My guess is you didn't include jQuery, so the $ selector is not defined. So when you try $('div').mouseenter(function(){$(this).fadeTo('fast',1)}); it gives an error telling you $ is not a function (which you'll be able to see if you open the console). So the solution would be to either use pure javascript or include jquery before your script.

Btw: it's better to run your javascript after the DOM has completely loaded, so you are sure the elements you are referencing are there when the code runs. In jquery you can do it like this:

$(function () {
    //your code here
});

You must include the jQuery file/cdn. CDN Also try use scripts at bottom of your body tag unless you know what you are doing.

 $( document ).ready(function() { //YOUR CODE HERE }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM