jQuery captures the differences between browsers and provides a uniform programming
interface
- Select one or more elements
$('p')
- Assign an event "handler"
$('p').click();
- Pass an anonymous function to the event handler
// ('p').click();
//
// function(){
// $(this).slideUp();
// }
//
$('p').click(function(){
$(this).slideUp();
} );
[
jq_03_click.html]
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<button>reset</button>
<script>
$('p').click(function(){
$(this).slideUp();
});
$('button').click(function(){
$('p').show();
});
</script>
</body>
</html>
If you prefer, you could use regular (named) functions, instead of anonymous functions, like this:
function myslideUp(){
$(this).slideUp();
}
function myShow(){
$('p').show();
}
$('p').click(myslideUp);
$('button').click(myShow);
Now if you think of the page being ready as an event (thus, the event handler ready()), you should understand the following [
jq_03_ready.html]
<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(document).ready(function(){
$('p').click(function(){
$(this).slideUp();
});
$('button').click(function(){
$('p').show();
});
});
</script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<button>reset</button>
</body>
</html>
$(document).ready() function is a built-in jQuery function that waits until
the HTML for a page loads before it runs your script.
$(document).ready(); //calling a ready() function of a $(document) object
Then we are passing an anonymous function (function without a name) as an argument
function(){} // this is an anonymous function
This results in this somewhat confusing code
$(document).ready(function(){
// code here;
});
The short-hand for the above is the more cryptic:
$(function(){
});
/*
*
* $(); + function(){}
*
*/
FYI The eqivalent in javascript (without jquery) would be:
<script>
window.onload = function(){
// code here
}
</script>