JS event and Handler

Javascript event occur on user interaction on HTML dom or anything changes in DOM
like mouse event, key event, window event,
click, keypress, load, unload,....soon

When event occur event handler are executed.
we cam also assign multiple event Handler to element

like
event => execute handler;
click event execute  onclick handler

onClick = function (){
}


We can assign handler to element..

1. by direct HTML attribute
<div onclick="handler_func();">
2. by js
element.getElementById('id');
element.onClick = function(){

};

3. by call addEventListener method, it has 2 param, event, handler function...
element.addEventListener(event, myFunction);
element.addEventListener("mouseover", myFunction);
 - addEventListener(event, function, useCapture);

4. for InternetExplorer
document.attachEvent() 



We can also remove Handler function

 - removeEventListener(event, myFunction)
-  JQuery off()
$('selector).off(event);





EventObject event param 


pageX, pageY the mouse position (X & Y coordinates) at the time the event occurred, relative to the top left of the page.

type the type of the event (e.g. "click").
which the button or key that was pressed.
data any data that was passed in when the event was bound.
target the DOM element that initiated the event.
preventDefault() prevent the default action of the event (e.g., following a link).
stopPropagation() Stop the event from bubbling up to other elements.

Event Propagation



There are two ways of event propagation in the HTML DOM: bubbling and capturing.

In bubbling, the innermost element's event is handled first and then the outer element's event is handled. The <p> element's click event is handled first, followed by the <div> element's click event.


In capturing, the outermost element's event is handled first and then the inner. The <div> element's click event is handled first, followed by the <p> element's click event.

we can control this by
 - addEventListener(event, function, useCapture)
useCapture is boolean
false = bubbling [default]
true = capturing

REF: https://www.sololearn.com/Play/JavaScript

Share this

Related Posts

Previous
Next Post »