dev-notes/JavaScript/Events & Animation.md
Marcello Lamonaca 17bf5fe2de
Add React Notes (#1)
* Start React notes

* useEffect & custom hooks notes

* Add React-Router Notes

* Spread operator cloning improvements

* Clarify notation for object with same key-value pair

* Add Redux notes

* Fix: translation

* Add details to event notes

* Add details to useEffect and class components

* Notes on async operations

* Fix: import <script> tag type

* Fix typos

* Add React Tests Notes

* Redux Tests Notes

* generalize paths

* Fix react testing library import

* Improve Store notes

* add missing ;

* Fix swapped examples for thunk and action tests

* Improve variable names

* Typo fixes
2021-03-29 19:34:47 +02:00

2.6 KiB
Raw Blame History

Events & Animation

Events

Event Types:

  • Mouse Events: mousedown, mouseup, click, dbclick, mousemove, mouseover, mousewheel, mouseout, contextmenu, ...
  • Touch Events: touchstart, touchmove, touchend, touchcancel, ...
  • Keyboard Events: keydown, keypress, keyup, ...
  • Form Events: focus, blur, change, submit, ...
  • Window Events: scroll, resize, hashchange, load, unload, ...

Managing Event Listeners

var domNode = document.getElementById("id");

var onEvent = function(event) {  // parameter contains info on the triggered event
    event.preventDefault();  // block execution of default action
    // logic here
}

domNode.addEventListener(eventType, calledback);
domNode.renoveEventListener(eventType, callback);

Bubbling & Capturing

Events in Javascript propagate through the DOM tree.

Bubbling and Capturing What Is Event Bubbling in JavaScript? Event Propagation Explained

Dispatching Custom Events

Event Options:

  • bubbles (bool): whether the event propagates through bubbling
  • cancellable (bool): if true the "default action" may be prevented
let event = new Event(type [,options]);  // create the event, type can be custom
let event = new CustomEvent(type, { detail: /* custom data */ });  // create event w/ custom data
domNode.dispatchEvent(event);  // launch the event

Event Inheritace

Animation

The window object is the assumed global object on a page.

Animation in JavascriptThe standard way to animate in JS is to use window methods. It's possible to animate CSS styles to change size, transparency, position, color, etc.

//Calls a function once after a delay
window.setTimeout(callbackFunction, delayMilliseconds);

//Calls a function repeatedly, with specified interval between each call
window.setInterval(callbackFunction, delayMilliseconds);

//To stop an animation store the timer into a variable and clear it
window.clearTimeout(timer);
window.clearInterval(timer);

Element Position & dimensions

StackOverflow Wrong dimensions at runtime

> console.log(document.getElementById('id').getBoundingClientRect());
DOMRect {
    bottom: 177,
    height: 54.7,
    left: 278.5,
    right: 909.5,
    top: 122.3,
    width: 631,
    x: 278.5,
    y: 122.3,
}