//define a function
var sayHello = function (name) {
console.log("Hello, " + name + "!");
}
//call a function
sayHello("Girl Develop It");
var sayHello = function (name) {
console.log("Hello, " + name + "!");
}
var textAFriend = function (name, callback) {
callback(name);
}
//call the function with a named callback function
textAFriend("Girl Develop It", sayHello);
var sayAwesome = function (name, callback) {
callback(name);
}
//call the function with an anonymous callback function
sayAwesome("Girl Develop It", function() {
console.log("You are awesome " + name + "!");
});
// First Example, with named callback & .on
var onButtonClick = function() {
console.log('clicked!');
};
$('button').on('click', onButtonClick);
// Second Example, with anonymous callback & .on
$('button').on('click', function () {
console.log('clicked!');
});
// Third Example, with .click (& a named callback)
$('button').click(onButtonClick)
'keydown'
'keypress'
'keyup'
'click'
'mousedown'
'mouseup'
'mousemove'
'change'
'focus'
'blur'
Follow along: http://jsbin.com/jiwoxef/edit
Preventing Default Events
//default event for clicking on link is to go to new page
$('a').on('click', function (event) {
event.preventDefault();
console.log('Not going there!');
});
//default event is to submit form and reload page
$('form').on('submit', function (event) {
event.preventDefault();
console.log('Not submitting, time to validate!');
});
//on page load
$('.kitty-image').show(3000);
$('.kitty-image').fadeIn(3000);
//with an event handler, as a callback
$('button').click(function() {
$('.kitty-image').show();
});
$('button').mouseover(function(){
$(this).css('color', 'red');
});
"If you want to create an animation, effect, or UI component, chances are pretty good that someone has done the work for you already."
<link rel="type/stylesheet" type="text/css" href="tablesorter.css">
<script src="lib/tablesorter.js"><script>
$('table').tableSorter();
Pattern: name variables with $
var $myVar = $('#myNode');
Pattern: store references to callback functions
var myCallback = function(argument) {
// do something cool
};
$(document).on('click', 'p', myCallback);
Anti-pattern: anonymous functions
$(document).on('click', 'p', function(argument) {
// do something anonymous
});
banner.css('color', 'red');
banner.html('Welcome!');
banner.show();
Is the same as:
banner.css('color', 'red').html('Welcome!').show();
Is the same as:
banner.css('color', 'red')
.html('Welcome!')
.show();
Broken code: DOM manipulation and event binding in the <head>
<head>
<script>
$('body').append( myNode );
</script>
</head>
Pattern: If you need to load a script in the <head>
, wait for the rest of the DOM to be ready before executing
<body>
//all your other HTML code
<script>
$(document).ready(function() {
// do something when the DOM is fully loaded
});
</script>
</body>