In general, jQuery code (that is, JavaScript code that uses the jQuery library) runs on the web browser. You run JavaScript code in web browsers using script
tags, either where the code is actually in the tag:
<script>
alert("I'm some JavaScript code");
</script>
...or where the code is in a separate file and the tag refers to the file:
<script src="myfile.js"></script>
(Note that the end tag is required, and you cannot write it as a self-closing tag like <script src="myfile.js"/>
.)
Since you're using jQuery, you must include the jQuery library file before any code that uses it:
<script src="jquery.min.js"></script>
Or if you're using it from a CDN like Google's:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Code you want to have run when the page is "ready" you can put inside a function that jQuery will call when the page is "ready":
<script>
jQuery(function() {
jQuery("<p>This paragraph added via jQuery</p>").appendTo(document.body);
});
</script>
Alternately, you can put your script
tag at the very bottom of your page, just before your closing </body>
tag; if you do, it's still best to wrap your code in a function so you don't create global symbols unnecessarily:
<script>
// This creates a function to contain any symbols that you create, then
// immediately calls it. As written, it assumes it's at the very bottom of
// the page and so things are basically ready.
(function() {
jQuery("<p>This paragraph added via jQuery</p>").appendTo(document.body);
})();
</script>
jQuery's main function, jQuery
, is available either as jQuery
or $
, so the above could be:
<script>
$(function() {
$("<p>This paragraph added via jQuery</p>").appendTo(document.body);
});
</script>
...but as $
is used by other libraries, there's a way to make jQuery not use the $
symbol. I mention this so you'll understand why you see jQuery
in some code, but $
in other code.
Here's a complete example of using jQuery:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Test Page</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<input type='button' id='theButton' value='Click Me'>
<script>
jQuery(function() {
// Hook the button click
jQuery("#theButton").click(function() {
jQuery("<p>This paragraph was added via jQuery.</p>").appendTo(document.body);
});
});
</script>
</body>
</html>
Live copy