1

This code works fine in JSFiddle, but not locally in Chrome or Firefox. Am I doing something wrong in linking the CSS or JavaScript? In the Firefox console, I get an error that $ is undefined. Am I linking jQuery improperly?


index.html:

<!DOCTYPE HTML>
<head>
    <title>Digital Etch-A-Sketch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
</head>

<body>

    <div id="wrapper">


    </div>

<script src="etch-a-sketch.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

</body>

</html>

main.css:

//Etch-A-Sketch - CSS

.square {
  float: left;
  height: 48px;
  width: 48px;
  background-color: black;
  border: 1px solid white;
}

#wrapper {
  position: relative;
  top: 50px;
  margin: 0 auto;
  height: 200px;
  width: 200px;
}

etch-a-sketch:

$(document).ready(function(){

  var wrapper = $('#wrapper');

  for (var i = 0;i < 16; i++) {
    var div = $('<div class="square"></div>');
    wrapper.append(div);
  }

});
1
  • My error was in my CSS. I commented JavaScript style and the caused the browser to not recognize the styling to .square. Although, it did still apply styling to #wrapper. I updated my CSS code to show where I went wrong. Commented Apr 20, 2014 at 3:32

2 Answers 2

3

Include the jQuery library before you include your custom script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="etch-a-sketch.js"></script>

Otherwise you're trying to use jQuery functionality before you have library available.

Sign up to request clarification or add additional context in comments.

4 Comments

No luck still... Although the $ error is now gone. How should I go debugging this? The CSS and custom script are both linked according to the console.
@JohnD. So you're 100% sure both your scripts and your CSS has loaded? Any errors at all? Try refreshing the cache (F5).
And I figured it out. I used JavaScript style commenting in my CSS... Thanks a lot for sticking around :)
It works just fine for me when I have all of the CSS/JS/HTML all in one file. Are you sure your JS and CSS are linked properly? Is the paths actually pointing to the files?
0

JSFIDDLE DEMO

Codepen Demo

The error lies in Jquery ! you have to use .html() to inform the jquery to extract the #wrapper from the HTML document.

By the way, this also works

Jquery :

$(document).ready(function(){
  for (var i = 0;i < 16; i++) {
    $('#wrapper').append('<div class="square"></div>');
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.