This is not meant to be a comprehensive jQuery guide, or even a tutorial, but a tour through some of its core concepts and fun and useful functions.
For more info and some great tutorials, see the jQuery site, especially
jQuery
jQuery('#foo').hide();
$('#foo').hide();
$.now(); // returns the current time in msec
$
function is a Selector$('a.nav[href=/home]')
- selects all A elements whose class is 'nav' and whose href attribute is '/home'this
, i.e. a pointer to the original collection
attr
and html
$('a').attr('href')
-- returns the href
attribute of the first matching elementeach
to execute a function on all itemseq
to reduce the set to a single item$('a').eq(2).attr('href')
-- returns the href
attribute of the third matching element$('a').last().attr('href')
-- returns the href
attribute of the last matching element<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
All Google jQuery links:
3 reasons why you should let Google host jQuery for you
$("#logo").animate({
backgroundColor: "#aa0000"
}, 1000 );
on
method$('#hi').on('click', function() {
alert("hi");
});
$('#hi').click(function() {
alert("hi");
});
click()
with no parameters, it triggers a clickreturn false
submit
eventvar f = function(event) {....}
$('#hi').click(f);
$('#hi').change(f);
on
directly$('#hi').on('click', f);
$('#ho').on('change', f);
on
can hook many events at once$('#hi').on('click change', f);
$('#hi').on('click', f)
.on('change', f);
jQuery has a special event that is fired when the page is "ready", i.e. the DOM hierarchy has been fully constructed.
$(document).ready(function() {
// set up your page
});
It's best to put setup code in a "ready" handler rather than directly inside a <script>
tag since the document might not be ready yet.
This can be abbreviated, but this might be unclear:
$(function() {
// set up your page
});
"In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead." - http://api.jquery.com/ready/
/