So a few of my co-workers were wanting to know more about jQuery, so I thought I’d post an entry on the topic…a really basic intro to get people thinking and starting to use it.
There are a few things I love about jQuery and they are…
- You can query all your markup
- If it’s something with the client-side, there’s a plugin for it!
- It’s easy and fun to use
So let’s get started with the most common structure:
$(document).ready(function() {
$(selectorhere).whateverfunction();
});
You may be wondering what the $ represents and the answer is…it’s a shortcut! jQuery(document) and $(document) are the same thing.
Okay so why do you call .ready all the time? Well one of the nice things about jQuery is that it knows when the DOM (Document Object Model) has loaded so between the brackets will run as soon as that happens. It works as a safety net basically.
The “selectorhere” represents what you want to query the DOM for basically. You can have all types of selectors, but I’ll list a few of the most common that I use.
- The class selector $(‘div.classname’)
so this will search the DOM for anything marked up like this: <div class=”classname”></div> - The id selector $(‘div#maincontent’)
This will select the div with an id of maincontent like this: <div id=”maincontent”></div> - The html tag selector $(‘a’)
This will select all the anchors on the page like this: <a href=””></a> or <a name=””></a> - The attribute contains selector $(‘a[href*=something]’)
This will select all anchors with an href that contains the word something like this: <a href=”http://testsomething.com”></a>
Those are all the basic selectors I use, but you can read more about all the different types at jquery.com
Once you’ve selected what you want, you can do stuff to it/them. For example, say I wanted to add the jQuery datepicker to all textboxes with a class name of “date”. (Note: the jQuery datepicker is part of the jquery-ui library)
Alright so that jQuery code would look like this:
$(document).ready(function() {
$('input:text.date').datepicker();
});
So here I’m using the jQuery selector to say get me all inputs of type text with a class name of date. Just like the first little sample from above…really easy to use.
You can see more examples on these posts:
- jQuery DocumentReady.js – A Best Practice?
- Change Default TextBox Value with jQuery
- Trick Bots from Stealing Email Address with jQuery
- jQuery AJAX with ASP.NET MVC
- Preload Images with JQuery
As always, thanks for reading!