Section 2 - Events
document is an HTML object in javascript an is used to handle any object that contains the html document.
Notice that it to is a selector.
It acts like a global object - that this can be done anywhere on the page.
.ready() is wait until all elements have been loaded.
$(document).ready(function(){
alert('document is ready');
})
Function is uniquely defined
Generally done before the execution of any function since it enforces safety.
document acts like a selector, but is more safe.
No difference would have been observed with 'html' as the selector.
Click Events
$(document).ready(function(){
$('p').click(function() {
$('p').css('color', 'red');
})
})
// clicking on any paragraph makes it red
Now notice the difference here:
$(document).ready(function(){
$('p').click(function() {
$(this).css('color', 'red');
})
})
//clicking on a paragraph makes it red, uniquely
This is an HTML DOM element that is returned by the function it is invoked on, in our case the paragraph on the click event.
css invokations work exactly as any .css style pages.
It grabs a selector, in our case 'this', then takes a property and what attributes we want to invoke on that property. Just like:
p {
color: red;
}
The double click event
$(document).ready(function(){
$('p').dblclick(function() {
$(this).css('color', 'red');
})
})
Hovering
Handled by mouseenter and mouseleave events.
Can handled by css alone
$('li').mouseenter(function() {
$(this).css('color', 'blue');
})
$('li').mouseleave(function() {
$(this).css('color', 'black');
})
To combine and minimize both effects, we use the .hover function.
$('li').hover(function() {
$(this).css('color', 'blue');
}, function() {
$(this).css('color', 'black');
})
Notice that .hover is simply invoked with two arguments.
Keyboard Events
$(document).keypress(function() {
console.log('button was pressed and possibly held');
});
This event also captures keys when held down.
Unique keys
$(document).keyup(function() {
console.log('key pressed and released');
});
Does not capture keys held.
Also notice that both events are fired, and one does not overwrite the other.
Executed in sync. Multiple events are put into a queue.
Focus and Blur:
$('input').focus(function(){
$(this).css('border', '1px solid red');
});
$('input').blur(function(){
$(this).css('border', '');
});
.focus is activates as a click event, and .blur resumes the opposite - that is, when a user clicks somewhere else.
Last updated
Was this helpful?