The jQuery library provides the jQuery function, which lets you select elements using CSS selectors.
var myItems = jQuery( 'li' );
Of course, if you’ve seen any jQuery code, you’re probably more accustomed to seeing something like this:
var myItems = $( 'li' );
Valid variable names in JavaScript can be pretty much anything, as long as they don’t begin with a number and don’t include a hyphen. So, the $
in the code above is just a shorter, more convenient name for the jQuery
function.
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
When you call the $()
function and pass a selector to it, you create a new jQuery object. Of course, in JavaScript, functions are objects too, so that means that $
(and jQuery
, of course) has properties and methods, too. For example, you can refer to the $.support
property for information on what the current browser environment supports, and you use the $.ajax
method to make an AJAX request. Learn How to make Jquery AJAX request
$
may be used by another library, which can cause jQuery not to work. If you experience this, you should consider using jQuery.noConflict before loading the other libraries.Why $(document).ready() is required
Before you can safely use jQuery to do anything to your page, you need to ensure that the page is in a state where it’s ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready()
. As you can see here, the function we pass can just be an anonymous function.
$( document ).ready(function() {
console.log( 'ready!' );
});
This will run the function that we pass to .ready()
once the document is ready. What’s going on here? We’re using$(document)
to create a jQuery object from our page’s document
, and then calling the .ready()
function on that object, passing it the function we want to execute.
Since this is something you’ll find yourself doing a lot, there’s a shorthand method for this if you prefer — the $()
function does double duty as an alias for $(document).ready()
if you pass it a function:
$(function() {
console.log( 'ready!' );
});
No Comment