jQuery Basics
jQuery is a popular javascript framework simplifying cross-browser development. To get started, include the jQuery:
<script src="jquery.js" type="text/javascript"></script>
Since you will likely be manipulating the DOM, we need to wait until the page is fully loaded before executing our code. So we start by creating a statement to this affect:
$(document).ready(function(){ //code goes here });
jQuery is useful for applying CSS to elements on the page. This is useful when you would like to change an existing style. Here's a basic example.
First, create CSS:
<style type="text/css">
.warning{ border:red 1px solid;padding: 8px; }
</style>
Now, we can apply it when a specific event occurs:
$(document).ready(function(){ $("a").click(function(){ $("#results").addClass("warning"); }); });
In the real world, clicking a link will cause the browser to navigate away from the page before the warning could be displayed. jQuery offers an easy solution to prevent this from occurring:
$(document).ready(function(){ $("a").click(function(event){ event.preventDefault(); $("#results").addClass("warning"); )}; });
Notice how we passed the event as an argument. Now this is all fine and dandy but what good is a warning without any explanation? So let's add some text within the results div:
$(document).ready(function(){ $("a").click(function(event){ event.preventDefault(); $("#results").addClass("warning").html("Warning! You clicked a link!"); } });
jQuery adds a simple way to chain events by passing around the actual query object. This makes coding simpler and more compact.
Tags: basics, jQuery