Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic jQuery commands not working

Can anyone tell me why none of the javascript/jQuery commands I try ever work on my computer, but always work on the internet? Here is an example of basic commands:

Javascript file (test.js), css file (test.css) (don't mind the css) and html file (test.html):

var $list = $('li');
$list.click(function() {
  alert("working");
  });
li {
  list-style-type: none;
  position: relative;
  margin: 1px;
  padding: 0.5em 0.5em 0.5em 2em;
  background: grey;
}

li.done {
  background: #CCFF99;
}

li.done::before {
    content: '';
    position: absolute;
    border-color: #009933;
    border-style: solid;
    border-width: 0 0.3em 0.25em 0;
    height: 1em;
    top: 1.3em;
    left: 0.6em;
    margin-top: -1em;
    transform: rotate(45deg);
    width: 0.5em;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" type="text/css" href="test.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
  </head>
  <body>
    
    <ul>
  <li>Acheter du lait</li>
  <li>Promener le chien</li>
  <li>Faire de l'exercice</li>
  <li>Coder</li>
  <li>Jouer de la musique</li>
  <li>Relax</li>
</ul>
  </body>
</html>

See? It works on stack overflow. Yet, when I run the html file from my computer, the js/jq scripts never work. I know I haven't linked the js file improperly, because Safari developer tools are able to access it from the html file. What's wrong here?

like image 707
Guillaume Duchesne Avatar asked Apr 24 '26 08:04

Guillaume Duchesne


1 Answers

If $list.click part is in test.js, then you are executing this code before li elements are constructed. Wrap your code in $(document).ready(function(){...})

Note:

It works here, because in the snippet frame source stackoverflow appended your javascript fragment below html - so that the code is executed when the DOM is fully constructed.

like image 141
Igor Avatar answered Apr 27 '26 00:04

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!