Javascript events
with jQuery
December 2014
Ib
án Martínez [email protected]
www.openshopen.com
What actually
are those so
called
“events” ?
Timer
triggers
after 5
seconds
and shows
a modal
window.
Modal form
shown
after
server
responds
to an AJAX
request.
User click
Mouse hover
Window
scroll
Window
resize
Image was
downloaded
Events : When
do they occur?
Anytime.
And you can't do
anything about that.
Get over it.
Events : Where
do they occur?
At your page's DOM.
(Document Object Model)
Click
Change
Hover
...
At your page's timeline.
(Timers)
Events : Handling them.
Use Handlers
(Yes they are just functions/methods)
$( 'a' ).on( 'click', function() {
$(this).css('backgroundcolor', red );
});
Events : Handling them.
$( 'a' ).on( 'click', function() {
$(this).css('backgroundcolor', red );
});
$( 'a' ).on( 'click', function() {
$(this).css('backgroundcolor', red );
});
Handler: Function that holds event's logic.
Binding: Links browser's event with your handler.
Events : Event handling function .
The event Object
http://learn.jquery.com/events/insideeventhandlingfunction/
Events : Event handling
function.
The event Object
$( 'a' ).on( 'click', function( event ) {
$(this).css('backgroundcolor', red );
});
event.pageX , event.pageY
The mouse position at the time the event
occurred, relative to the top left of the
page.
event.type
The type of the event (e.g. "click").
event.which
The button or key that was pressed.
event.data
Any data that was passed in when the
event was bound.
event.target
The DOM element that initiated the event.
event.preventDefault()
Prevent the default action of the event (e.g.
following a link).
event.stopPropagation()
Stop the event from bubbling up to other
elements. Next slide will explain this.
http://learn.jquery.com/events/insideeventhandlingfunction/
Events : Event propagation.
AKA bubbling.
<html>
<body>
<div id="container">
<ul id="list">
<li><a href="domain1.com">Item #1</a></li>
<li><a href="domain2.com">Item #2</a></li>
<li><a href="domain3.com">Item #3</a></li>
<li><a href="domain4.com">Item #4</a></li>
</ul>
</div>
</body>
</html>
1 <a>
2 <li>
3 <ul #list>
4 <div #container>
5 <body>
6 <html>
7 Document root
Event will propagate until any DOM element has a handler binded
to “click” event which stops propagation (executing
event.stopPropagation() for instance).
From the DOM item that triggered the event, bubbling it up to
its ancestors, until document root is reached.
Connecting Events to Run Only
Once
$( 'a' ).one( 'click', function() {
alert('This message will be shown just once.' );
});
Disconnecting Events
$( 'a' ).off( 'click' );
Binding events to elements that don't
exist yet.
Event delegationEvent delegation
Binding events to elements that
don't exist yet.
Event delegation
http://learn.jquery.com/events/eventdelegation/
$(document).ready( function(){
$( '#list li a' ).on( 'click', function(event) {
event.preventDefault();
$('#list').append(
$('<li>').append(
$('<a>').attr({
href: 'http://url.com',
text: 'New item',
})
)
);
});
});
<div id="container">
<ul id="list">
<li><a href="domain1.com">Item #1</a></li>
<li><a href="domain2.com">Item #2</a></li>
<li><a href="domain3.com">Item #3</a></li>
<li><a href="domain4.com">Item #4</a></li>
</ul>
</div>
By clicking on any of
these <a> , we will
append a new <a> item
on that <ul> list.
Binding events to elements that
don't exist yet.
Event delegation
http://learn.jquery.com/events/eventdelegation/
<div id="container">
<ul id="list">
<li><a href="domain1.com">Item #1</a></li>
<li><a href="domain2.com">Item #2</a></li>
<li><a href="domain3.com">Item #3</a></li>
<li><a href="domain4.com">Item #4</a></li>
<li><a href="url.com">New Item</a></li>
</ul>
</div>
Click event for that
new <a> item won't be
handled
by our handler.
Because “on” function
was executed before
this <a> even existed
(was executed at
document.ready).
$(document).ready( function(){
$( '#list li a' ).on( 'click', function(event) {
event.preventDefault();
$('#list').append(
$('<li>').append(
$('<a>').attr({
href: 'http://url.com',
text: 'New item',
})
)
);
});
});
Binding events to elements that
don't exist yet.
Event delegation
http://learn.jquery.com/events/eventdelegation/
$( '#list li a' ).on( 'click', function(event)
{
event.preventDefault();
$('#list').append(
$('<li>').append(
$('<a>').attr({
href: 'url.com',
text: 'New item',
})
)
);
});
<div id="container">
<ul id="list">
<li><a href="domain1.com">Item #1</a></li>
<li><a href="domain2.com">Item #2</a></li>
<li><a href="domain3.com">Item #3</a></li>
<li><a href="domain4.com">Item #4</a></li>
</ul>
</div>
$( '#list' ).on( 'click', 'a' ,function(event)
{
event.preventDefault();
$('#list').append(
$('<li>').append(
$('<a>').attr({
href: 'url.com',
text: 'New item',
})
)
);
});
Event delegation
Main selector moved (delegated) to < a> item's ancestor.
Added a second parameter (selection rule) for ancestor's
future descendants.
Event sequence
Event sequence
$( 'div' ).on( 'hover', foo ).on( 'hover', bar );
On hover event both handlers will be executed :
=> foo
=> bar
var bar = function() {
console.log( 'bar' );
};
var foo = function() {
console.log( 'foo' );
};
Events tips & examples
$(document).ready mayhem.
Long lines of code hard to read.
Mixed concepts :
User actions (login submit).
DOM elemets effects (modal windows).
Comments will make it even worst.
Some deprecated code also.
Events tips & examples
$(document).ready mayhem.
Refactor it using functions.
Events tips & examples
$(document).ready mayhem.
$(document).ready(function(){
initModalWindows();
bindShopLoginEvent();
bindShowNewslettersFormEvent();
bindSubmitLoginFormEvent();
});
Easy to read.
No comments needed to understand what's going on at
$(document).ready
Events tips & examples
$(document).ready mayhem.
$(document).ready(function(){
initPageEffects();
bindUserActions();
});
function initPageEffects(){
initModalWindows();
}
function bindUserActions(){
bindShopLoginEvent();
bindShowNewslettersFormEvent();
bindSubmitLoginFormEvent();
}
Even better reading and
makes it harder to
reach another mayhem on
the future.
Uncle Bob says :
“Functions are
supposed to do "One
Thing", do it well,
and do it only.”
https://cleancoders.com/episode/clean
codeepisode3/show
Javascript events
with jQuery
December 2014
Ib
án Martínez [email protected]
www.openshopen.com
http://learn.jquery.com/events/handlingevents/
http://learn.jquery.com/