Observe Input changes in the Given Paragraph
We are given an editable paragraph text. When we add a new line to the text paragraph and hit ENTER, then our program should detect this mutation of adding a new line in the given paragraph and should log the changed paragraph on the console. Detection of the first line of a given paragraph is not required.
Example: we will detect only the changes made directly to the target element (i.e.; paragraph ). If the change is in childList==true, then check when the user is going to hit ENTER (i.e.; line break ). If a line break is found, it means the user has completed adding the data into the current line and entered into a new line. so now we can update our current paragraph data and log the same on the console.
HTML
<!DOCTYPE html> < html > < head > < title > MutationObserver Example </ title > < meta charset = "utf-8" > </ head > < body > <!-- This <p> element is editable --> < p contenteditable oninput = "" > Change this text & look at the console after pressing ENTER </ p > < script > // Selecting the target element let target = document.querySelector('p'); let observer = new MutationObserver( function (mutations) { // As we have to observe only a single element , // so taking mutations[0] into mutation mutation = mutations[0]; // When mutation type is childlist then we // will be checking for line break if (mutation.type === 'childList') { let target_values = [].slice .call(target.children) .map(function (node) { return node.innerHTML }) .filter(function (s) { // When user has hit ENTER, then this // condition is going to hold true if (s === '< br >') return false; return true; }); // Logging the updated target list // stored inside target_values console.log(target_values); } }); // Taking only childlist in config parameter let config = { childList: true, } // Calling observe() method using observer instance // this trigger observing mutation of the target element observer.observe(target, config); </ script > </ body > </ html > |
Output:
Javascript provides some other observer APIs like Intersection Observer, Resize Observer, etc. Each observer API has different use cases and is introduced to provide some kind of optimizations over the traditional way of observing DOM elements.
Web API Mutation Observer
Mutation Observer is a web API (web APIs are APIs provided by the browser itself) that is used to observe (i.e.; detect) the changes of the target HTML element within a web page. For example, when the user wants to know which element has recently been removed and which element has been added to the DOM, we can use Mutation Observer. In dynamic websites, we know that elements are added, removed, or modified dynamically, this API serves as a tool for tracking and reacting to these changes. In this article, we will see the Mutation Observer in the Web API, along with understanding its benefits, use cases, instance methods, & etc.