What is Event in Javascript?

What is Event

The actions to which JavaScript can respond are called Events. An Event is some notable action to which a script can respond.

  • Clicking an element
  • Submitting a form
  • Scrolling page
  • Hovering an element

Event Handler

An Event handler is JavaScript code associated with a particular part of the document and a particular event. A handler is executed if and when the given event occurs at the part of the document to which it is associated.

  • onclick
  • ondblclick
  • onchange
  • onblur

Event Binding with HTML Attribute

These bindings are element attributes, such as onclick and on change, which can be set equal to JavaScript that is to be executed when the given event occurs at that object.

Ex: – <button onclick= “alert(‘Button Clicked’);”>Click Me</button>

Event Binding with JavaScript

When we use this approach we can add or remove handlers dynamically as well as it improves the separation between the structure of the document and its logic and presentation.

Ex: –

Event Binding with JavaScript

Overwriting Event Handler

DOM Event Model

The DOM 2 Event Model specification describes a standard way to create, capture, handle and cancel event in a tree like structure such as an XHTML document’s object hierarchy.

Phases

  • Capture Phase
  • Target Phase
  • Bubbling Phase

addEventListener ( )

This method is introduced by DOM2, used to engage an event handler in a page.

Syntax:-
Object.addEventListener(event, handler, capturePhase);

Where,

  • Object is the node to which the listener is to be bound.
  • Event is a string indicating the type of event.
  • Handler is the function that should be called when the event occurs.
  • capturePhase is a Boolean indicating whether to use Bubbling (false) or Capture (true). This is optional. If you omit there is false by default.

Ex:-
btn.addEventListener(“click”, show, false);

Why we should use addEventListener ( ) ?

Why we should use addEventListener ( )

  • It allows you to bind multiple handlers to an object for the same event.
  • It enables you finer-grained control of the phase when the listener is activated (Capture or Bubbling).
  • It works on any DOM element, not just HTML elements.

removeEventListener ( )

DOM Event Flow/ Event Propagation

The DOM 2 Event Model specification describes a standard way to create, capture, handle and cancel event in a tree like structure such as an XHTML document’s object hierarchy.

Phases

  • Capture Phase
  • Target Phase
  • Bubbling Phase

Event Object

DOM events pass an Event object as an argument to handlers. This object contains extra information about the event that occurred.

Ex:- addEventListener(“click”, function(e) { });

Event Methods

  • stopPropagation() –  Prevents further propagation of the current event in the capturing and bubbling phases.

Syntax:- e.stopPropagation();

  • stopImmediatePropagation() – Prevents other listeners of the same event from being called.

Syntax:- e.stopImmediatePropagation();

  • preventDefault()  – The Event interface’s preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

Syntax:- e.preventDefault();

Mouse Event

  • mousedown – It fires when mouse button is pressed down.
  • mouseup – It fires when the mouse button is released.
  • click – It fires when something is clicked. mousedown, mouseup and click events fires in sequence.
  • dblclick – It fires when something is clicked twice in rapid succession. mousedown, mouseup, click, mousedown, mouseup, click, and dblclick events fires in sequence.
  • mouseenter – It fires when a mouse starts to hover over some element. NO bubble.
  • mouseleave – It fires when a mouse exits while hovering over some element. No bubble.
  • mouseover – It fires when mouse is hovering over some element.
  • mouseout – It fires when mouse leaves from hovering over some element.
  • mousemove – It fires when the mouse moves.
  • contextmenu – It fires when mouse right button is clicked.

Focus Event

  • focus – It fires when an element gains focus, such as selecting a form field. No Bubble
  • blur – It fires when element loses focus, such as moving away from a form field. No Bubble
  • focusin – It fires just as an element is about to gain focus.
  • focusout – It fires just as an element loses focus and just before the blur event.

Key Event

  • keydown – It fires as a key is pressed down.
  • keypress – It fires after a key is pressed down (after keydown). It only works with printable characters.
  • keyup – It fires as the key is released.
Tagged : / / /

How do I manipulate using DOM Table in JavaScript?

HTMLTableElement

HTMLTableElement interface provides special properties and for manipulating the layout and presentation of tables in an HTML document.

Properties
caption
tHead
tFoot
rows
tBodies

Methods
createCaption()
deleteCaption()
createTHead()
deleteTHead()
createTFoot()
deleteTFoot()
insertRow()
deleteRow()

Properties

  • caption – This property represents the table caption. If no caption element is associated with the table, it can be null.
  • tHead – This property represents  the table’s <thead> element. Its value can be null if there is no such element.
  • tFoot – This property represents the table’s <tfoot> element. Its value can be null if there is no such element.
  • rows – This property rows returns a live HTMLCollection of all the rows in the table, including the rows contained within any <thead>, <tfoot>, and <tbody> elements. Although the property itself is read-only, the returned object is live and allows the modification of its content.
  • tBodies – This read-only property returns a live HTMLCollection of the table bodies. Although the property is read-only, the returned object is live and allows the modification of its content.

Methods

  • createCaption() – This method returns the caption for the table. If no caption element exists on the table, this method creates it, then returns it.
  • deleteCaption() – This method removes the caption from the table. If there is no caption associated with the table, this method does nothing.
  • createTHead( ) – This method returns the <thead> element association with the table, of type HTMLTableSectionElement. If there is no such element associated to the table, this method creates it, then returns it.
  • deleteTHead() – This removes a <thead> element from the table.
  • createTFoot() – This method returns the <tfoot> element associated with the table, of type HTMLTableSectionElement. If there is no footer for this table, this methods creates it, then returns it.
  • deleteTFoot() – This method removes a <tfoot> element from the table.
  • insertRow() method inserts a new row in the table and returns a reference to the new row.

Syntax: – var row = HTMLTableElement.insertRow(index = -1);

index is the row index of the new row.
row is assigned a reference to the new row. A reference to HTMLTableRowElement.
If index is -1 or equal to the number of rows, the row is appended as the last row. If index is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1.
If a table has multiple tbody elements, by default, the new row is inserted into the last tbody.

  • deleteRow() method removes a row from the table. If the number of rows to delete, specified by the parameter, is greater or equal to the number of available rows, or if it is negative and not equal to the special index -1, representing the last row of the table, the exception INDEX_SIZE_ERR is thrown.

Syntax: – HTMLTableElement.deleteRow(index)

an index is an integer representing the row that should be deleted.
However, the special index -1 can be used to remove the very last row of a table.

HTMLTableSectionElement

The HTMLTableSectionElement interface provides special properties and methods for manipulating the layout and presentation of sections, that is headers, footers and bodies, in an HTML table.

Properties
rows

Methods
insertRow()
deleteRow()

  • Rows – This returns a live HTMLCollection containing the rows in the section. The HTMLCollection is live and is automatically updated when rows are added or removed.
  • insertRow() – It inserts a new row just before the given position in the section. If the given position is not given or is -1, it appends the row to the end of section. If the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than -1, it raises a DOMException with the IndexSizeError value.
  • deleteRow() – It removes the cell at the given position in the section. If the given position is greater (or equal as it starts at zero) than the amount of rows in the section, or is smaller than 0, it raises a DOMException with the IndexSizeError value.

HTMLTableRowElement

The HTMLTableRowElement interface provides special properties and methods for manipulating the layout and presentation of rows in an HTML table.

Properties
cells
rowIndex
sectionRowIndex

Methods
insertCell()
deleteCell()

Properties

  • cells – It returns a live HTMLCollection containing the cells in the row. The HTMLCollection is live and is automatically updated when cells are added or removed.
  • rowIndex – It returns a long value which gives the logical position of the row within the entire table. If the row is not part of a table, returns -1.
  • sectionRowIndex – It returns a long value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns -1.

Methods

  • insertCell() – This method inserts a new cell into a table row and returns a reference to the cell.

Syntax: – var cell = HTMLTableRowElement.insertCell(index = -1);

HTMLTableRowElement is a reference to an HTML table row element.
index is the cell index of the new cell.
cell, is assigned a reference to the new cell.
If index is -1 or equal to the number of cells, the cell is appended as the last cell in the row. If index is greater than the number of cells, an IndexSizeError exception will result. If index is omitted it defaults to -1.

Methods

  • deleteCell() – It removes the cell at the given position in the row. If the given position is greater (or equal as it starts at zero) than the amount of cells in the row, or is smaller than 0, it raises a DOMException with the IndexSizeError value.
Tagged : / / /

CSS manipulation in JavaScript

CSSStyleDeclaration Object

The CSSStyleDeclaration object represents a collection of CSS property-value pairs.

It is used in API :

HTMLElement.style
window.getComputedStyle( )

Properties

  • cssText
  • length
  • parentRule

Methods

getPropertyValue(property)
getPropertyPriority(property)
removeProperty(property)
setProperty(property, value, priority)
item(index)

Style Property

The style property is used to get or set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element’s inline style attribute.

Style Property represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets or browser default.

Syntax:-

Return
element.style.property

Set
element.style.property = “value”

A style declaration is reset by setting it to null or an empty string, e.g. element.style.property = null

Inline Style Manipulation

The most direct way to modify CSS value with JavaScript is through the style property that corresponding to the inline style sheet specification for a particular HTML element. To perform a manipulation of the CSS with a JavaScript DOM interface, you would access the style object of the element.

Style Property

Example: –

Dynamic Style Manipulation

As we know The most direct way to modify CSS value with JavaScript is through the style property that corresponding to the inline style sheet specification for a particular HTML element, This has performance considerations since you need to change a single property at a time. We might manipulate style rules using CSS class Selector. The element’s class attribute is represented as className property in DOM.

DOMTokenList

The DOMTokenList interface represents a set of space-separated tokens. Such a set is returned by Element.classList, HTMLLinkElement.relList, HTMLAnchorElement.relList, HTMLAreaElement.relList, HTMLIframeElement.sandbox, or HTMLOutputElement.htmlFor.  etc. It is indexed beginning with 0 as with JavaScript Array objects. DOMTokenList is always case-sensitive.

Properties
length
value

Methods
item()
add()
remove()
replace()
contains()
toggle()
value()

classList Property

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element.

Syntax: –

var elementClasses = elementNodeReference.classList;

Computed Style

The computed style is the style actually used in displaying the element, after “stylings” from multiple sources have been applied.
Style sources can include: internal style sheets, external style sheets, inherited styles, and browser default styles.
Style Property represents only the CSS declarations set in the element’s inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets or browser default. To get the values of all CSS properties for an element you should use window.getComputedStyle( ) instead.
The returned style is a live CSSStyleDeclaration object ( The CSSStyleDeclaration object represents a collection of CSS property-value pairs.), which updates itself automatically when the element’s style is changed.

Syntax:-
window.getComputedStyle(element, pseudoElement)
Element – Element for which to get the computed style.
pseudoElement – A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.

Ex: –
var elm = document.getElementById(“myid”);
var allCSSProp = window.getComputedStyle(elm)

Tagged : / / / / /

HTML-DOM and CSS-DOM Mapping in JavaScript

HTML-DOM Mapping

Many object properties are simply direct mapping to the attributes of the HTML element. In other words, there is a mapping directly between HTML Syntax and the DOM.

Ex:-

Above title can be accessed in DOM by
document.getElementById(“myid”).title

P tag’s title attribute is mapped to DOM property title in the above example that is the reason we can access title in DOM that way.

HTML-DOM Mapping

The mapping is direct between HTML attributes and the DOM properties with the following considerations:-

  • The mapping is direct if the attribute is a single non-reserved word, so an element’s title attribute is accessed via the corresponding DOM object’s title property.
  • The mapping will change case as camelCase if the attribute has two word. Ex:- tabindex attribute will be represented tabIndex in the DOM.
  • If the HTML attribute name is reserved under JavaScript, the value will be modified to work. Ex:- class attribute will be represented className in DOM for attribute will be represented htmlFor in DOM
  • There are also some exception. Ex: – char attribute will be represented ch in DOM
  • For others and custom attributes, we have to use getAttribute() and setAttribute( ) Methods because they may not have direct mapping.

CSS-DOM Mapping

We can modify the CSS Properties by applying a mapping between the CSS property and the DOM object. The mapping is direct between CSS properties and the DOM properties with the following considerations:-

  • CSS properties have a single word, so their mapping is direct.            Ex:- color in CSS will be represented as color in DOM too.
  • Hyphenated CSS properties are repsrented as a single word with camelCase in the DOM.         Ex:- background-color in CSS will be represented as backgroundColor in DOM
  • CSS properties value with vendor prefixs.  Ex:- -webkit-box-shadow in CSS will be represented as webkitBoxShadow in DOM.
  • There are some reserved words which can be exception in the above cases.    Ex – float in CSS will be represented as cssFloat in DOM

Tagged : / / / /

Manipulation Attributes in JavaScript

Attributes

The attributes property returns a live collection of all attribute nodes registered to the specified node. It is a read-only property.

Syntax:-
Element.attributes[index/key]

Attr Object

Properties

  • name (do not use nodeName)
  • value (do not use nodeValue or textContent or appendChild() or insertBefore( ) or removeChild( ) or replaceChild( ) these all are deprecated for attr object)

Methods

  • setAttribute( )
  • getAttribute( )
  • removeAttribute( )

setAttribute( )

This method is used to set the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise, a new attribute is added with the specified name and value. We should not use this method to set inline style as it will overwrite other CSS properties.

Syntax:-
Element.setAttribute(name, value);
Element.setAttribute(“style”, “css properties: value”);

Ex: –
p.setAttribute(“id”, “mydiv”);
p.setAttribute(“style”, “font-size: 80px”);

getAttribute( )

The getAttribute() returns the value of a specified attribute on the element. If the given attribute does not exist, the value returned will either be null or “ ”.

Syntax: –
var attribute = element.getAttribute(attributeName);

removeAttribute( )

This method is used to remove an attribute from the specified element.

Syntax: –
element.removeAttribute(attrName);

hasAttribute( )

The hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not.

Syntax:-
var result = element.hasAttribute(attr_name);

Tagged : / / / /

Modifying Text Nodes in JavaScript

Properties

  • Data
  • Length

Methods

  • appendData(String)
  • deleteData(start, length)
  • insertData(start, string)
  • replaceData(start, length, string)
  • splitText(start)
  • substringData(start, length)

Length

Length property is used to access the length of Text which indicates the number of characters it contains.

Syntax:- TextNode.length

Data

Data property is used to set or return the value of a text node and comment node objects.

Syntax: –
Sets
TextNode.data = value
Returns
TextNode.data

Ex:- TextNode.data = “Hello DevOpsSchool”;

appendData(String)

This method is used to append the passed string to the end of the text node and comment node.

Syntax: –
TextNode.appendData(String);

Ex: –
TextNode.appendData(“Hello DevOpsSchool”);

deleteData(start, length)

This method is used to delete or remove text content from a text node and comment node. It deletes the specified length of characters starting from index defined in start.

Syntax:-
TextNode.deleteData(start, length);

Ex: –
TextNode.deleteData(0, 5);

insertData(start, string)

This method is used to insert text content to text node and comment node. It inserts the value in string, starting at the character index specified in start.

Syntax:-
TextNode.insertData(start, string)

Ex: –
TextNode.insertData(3, “Hello”)

replaceData(start, length, string)

This method is used to replace text content of text node and comment node. It inserts the value in string, starting at the character index specified in start.

Syntax:-
TextNode.replaceData(start, length, string)

Ex: –
TextNode.replaceData(0, 4, “Hello”)

splitText(start)

The splitText(start) method breaks the Text node into two nodes at the specified start index, keeping both nodes in the tree as siblings. It returns right side of the split in a new text node and leaves the left side in the original.

Syntax: –
var rightSide = TextNode.splitText(start)

Ex: –
var rightSide = TextNode.splitText(5)

substringData(start, length)

It returns the part of the current element’s (TextNode and CommentNode) text content from the specified position with the specified length.

Syntax:-
TextNode.substringData(start, length)

Ex: –
TextNode.substringData(2, 5);

Tagged : / /

Difference between innerHTML and outerHTML in JavaScript

innerHTML

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
It is recommended you should not use innerHTML when inserting plain text; instead, use textContent.

outerHTML

The outerHTML is the HTML of an element including the element itself. Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.

What is the difference between innerText and outerText?

The innerText property works similarly to the innerHTML property, except that it is focused solely on the textual content contained within an element. The innerText property sets or returns the text content of the specified node, and all its descendants. If you set the innerText property, any child nodes are removed and replaced by a single Text node containing the specified string. This feature was originally introduced by Internet Explorer and was formally specified in the HTML standard in 2016 after being adopted by all major browser vendors. To set or return the HTML content of an element, use the innerHTML property.

outerText

outerText property works similarly to the outerHTML property, modifies the element itself, and replaces it with a single text node. This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user.

Tagged : / / / / / /

Insert( ) Method in JavaScript

The insertBefore() method is used to insert a node before the reference node as a child of a specified parent node. If the given child is a reference to an existing node in the document, insertBefore( ) moves it from its current position to the new position.

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

Syntax: –

parentNode.insertBefore(newNode, referenceNode);

insertAdjacentElement ( ) Method

The insertAdjacentElement() method inserts the specified element into a given specified position. It returns the element that was inserted, or null if the insertion failed.

Syntax:-

element – The element to be inserted into the tree.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

insertAdjacentHTML ( ) Method

The insertAdjacentHTML() method is used to insert a text as HTML (parses the specified text as HTML or XML) into a specified position.

Syntax:-

text – The string to be parsed as HTML or XML and inserted into the tree.
It is recommended you not use insertAdjacentHTML when inserting plain text instead, use the node.textContent property

insertAdjacentText ( ) Method

The insertAdjacentText() method inserts the specified element into a specified position.

Syntax:-

text – The text which is about to insert.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

Tagged : / / / /

How is Node.js created with JavaScript?

Creating Nodes

  • createElement(element_name)
  • createTextNode(string)
  • createComment(string)
  • createDocumentFragment( )

Create Element Node

The createElement(element_name) method is used to create the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized. It returns the New Element.

Syntax:-
createElement(element_name)

Create Text Node

The createTextNode(string) method is used to create the Text Node with the specified text (string).

Syntax:-
createTextNode(string)

Create Comment Node

The createComment(string) method is used to create the Comment Node with the specified string and returns it.

Syntax:-
createComment (string)

Document Fragment

  • The DocumentFragment interface represents a minimal document object that has no parent.
  • A common use for Document Fragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild( ) or insertBefore( ).
  • Document fragment isn’t part of the active document tree structure, changes made to the fragment don’t affect the document.
  • Doing this moves the fragment’s nodes into the DOM, leaving behind an empty Document Fragment.
  • An empty Document Fragment can be created using the document.createDocumentFragment() method.

Create Document Fragment

The createDocumentFragment() method creates a imaginary Node object, with all the properties and methods of the Node object.

Tagged : / / / /

How To Traverse The DOM In JavaScript?

DOM Traversal

  • parentNode – Returns parent node
  • parentElement – Returns parent element node
  • childNodes – Returns collection of an element’s child nodes (including text and comment nodes)
  • children – Returns a collection of an element’s child element node (do not include text and comment nodes)
  • firstChild – Returns first child node of an element (it can be text or comment node)
  • firstElementChild – Returns first child element node of an element
  • lastChild – Returns last child node of an element (it can be text or comment node)
  • lastElementChild – Returns last child element node of an element
  • previousSibling – Returns previous node of the same level (it can be text or comment node)
  • previousElementSibling – Returns previous element node of the same level
  • nextSibling – Returns next node of same level (it can be text or comment node)
  • nextElementSibling – Returns next element of same level

parentNode and parentElement

The parentNode read-only property returns the parent of the specified node in the DOM tree.

The parentElement property returns the parent element of the specified element. If the parent node is not an element node, it returns null.

childNodes

The childNodes read-only property returns a live NodeList of child nodes of the given element where the first child node is assigned index 0. childNodes includes all child nodes, including non-element nodes like text and comment nodes.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.
  • You can use the length property of the NodeList object to determine the number of child nodes, then you can loop through all child nodes and extract the other info.

children

The children property returns collection of child elements of the given element where the first child is assigned index 0. children include only element nodes (no whitespace, text node, and comment node).

  • You can use the length property of the NodeList object to determine the number of child nodes, then you can loop through all child nodes and extract the other info.

firstChild

The firstChild property returns the node’s first child in the tree, or null if the node has no children. If the node is a Document, it returns the first node in the list of its direct children. It includes a text node and a comment node.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.

firstElementChild

The firstElementChild property returns the element’s first child element node in the tree, or null if the node has no children element. It ignores text node and comment node or any whitespaces.

lastChild

The lastChild read-only property returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child elements.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.

lastElementChild

The lastElementChild property returns the element’s last child element node in the tree, or null if the node has no children element. It ignores text node and comment node or any whitespaces.

previousSibling

The previousSibling read-only property returns the node immediately preceding the specified one in its parent’s childNodes list, or null if the specified node is the first in that list. It includes text node and comment node or any whitespace.

previousElementSibling

The previousElementSibling property returns the element node immediately preceding the specified one in its parent’s node list, or null if the specified node is the first in that list. It ignores the text node and comment node or any whitespace.

nextSibling

The nextSibling read-only property returns the node immediately following the specified one in its parent’s childNodes list, or null if the specified node is the last node in that list. It includes text node and comment node or any whitespace.

nextElementSibling

The nextElementSibling read-only property returns the element node immediately following the specified one in its parent’s node list, or null if the specified node is the last node in that list. It ignores the text node and comment node or any whitespace.

ownerDocument

The ownerDocument read-only property returns the top-level document object for this node. In HTML, the HTML document itself is always the ownerDocument of an element.

Tagged : / / /