How to use dynamic field control annotations in SAP UI5

Sap dynamic field-control annotation is used to dynamically change the behaviour of the UI.  The metadata generated is used to interpret and change the state of the UI control to visible,editable etc.

The following needs to be defined in order to use field control annotations

  • Usage of smartfield must be mentioned in Smart Table
  • Field control annotations must be present in the metadata file
  • Appropriate field control values must be sent in the http response.

Smartfield in Smart Table

<core:View xmlns:core="sap.ui.core" controllerName="initialView.controller"
      xmlns="sap.m"
      xmlns:smart="sap.ui.comp.smarttable"
      xmlns:customData="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
      height="100%">
      <Page id="page1" title="Customers1">
            <VBox fitContainer="true">
                 <smart:SmartTable id="smartTable1" 
                        entitySet="CustomerSet"
                        tableType="ResponsiveTable"
                        showFullScreenButton="true" 
                        header="Customers" 
                        showRowCount="true"
                        editTogglable="true"
                        customData:useSmartField="true"
                        useTablePersonalisation="true" 
                        initiallyVisibleFields="FC,Name"
                        enableAutoBinding="true">
                  </smart:SmartTable>
            </VBox>
      </Page>
</core:View>

Field control annotations in Metadata file

                        <EntityType Name="CustomerType"
                            sap:label="Customers"
                            sap:content-version="1">
                            <Key>
                                <PropertyRef Name="Id" />
                            </Key>

                            <Property Name="Id"
                                Type="Edm.String"
                                Nullable="false"
                                MaxLength="10"
                                sap:visible="false"
                                sap:label="Customer ID"
                                sap:creatable="false" />
                            <Property Name="FC"
                                Type="Edm.Byte"
                                sap:label="Field control" />
                            <Property Name="Name"
                                Type="Edm.String"
                                MaxLength="70"
                                sap:field-control="FC"
                                sap:creatable="false"
                                sap:updatable="true"
                                sap:label="Customer Name" />
                        </EntityType>


                        <EntityContainer Name="CustomerNamespace_Entities"
                            m:IsDefaultEntityContainer="true"
                            sap:supported-formats="atom json xlsx">
                            <EntitySet Name="CustomerSet"
                                EntityType="CustomerNamespace.CustomerType"
                                sap:creatable="false"
                                sap:updatable="true"
                                sap:deletable="true"
                                sap:content-version="1" />
                        </EntityContainer>

As seen in the above metadata, the following conditions must be met.

  • The Entityset must have annotation sap:updatable=”true” set at the global Entityset level
  • The main property ( as in above example “Name”) must have the annotation sap:field-control=”FC” and sap:updatable=”true”
  • The field control property must also be present ( Property Name=”FC” )

The backend must send the appropriate Field control values in the http Response.

{“d”: {
“__count”: “2”,
“results”: [
{
“__metadata”: {
“id”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1000’)”,
“uri”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1000’)”,
“type”: “CustomerNamespace.CustomerType”
},
“Id”: “1000”,
“Name”: “Mani”,
“FC”: 0
},
{
“__metadata”: {
“id”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1001’)”,
“uri”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1001’)”,
“type”: “CustomerNamespace.CustomerType”
},
“Id”: “1001”,
“Name”: “Raju”,
“FC”: 1
},
{
“__metadata”: {
“id”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1002’)”,
“uri”: “Customer_Odata_Service.CustomerSet/CustomerSet(‘1002’)”,
“type”: “CustomerNamespace.CustomerType”
},
“Id”: “1002”,
“Name”: “Jack”,
“FC”: 3
}
]
}
}

As seen in the above http response, the field control contains values such as 0 for hidden, 1 for read only, 3 for editable. This is also seen in the Smart table output picture shown in this post beginning.

5 HTML rare tags

In this blog, we will learn about five uncommon and under used rare HTML tags which are very useful in certain situations.

1. <abbr>:

<abbr> tag is used for defining abbreviations or acronym. It is also has optional title attribute to describe or expand the abbreviation or acronym when the mouse cursor is hovered over the text. The title attribute should contain only human-readable expansion of abbreviation and should have a specific meaning.

Continue reading 5 HTML rare tags

Magic / Dunder Methods in Python

Magic or dunder methods are special methods in Python OOPs that enrich your classes. It is also known as dunder methods. These methods are distinguished from other methods in a special way by using double underscore before and after the method name.

This method allows instances of a class to interact with the built-in functions and operators. The name “dunder” comes from “double underscore”. Simply it can be thought as a contract between your implementation and Python interpreter. Main terms of the contract is Python performing some actions behind the scenes under given circumstances. It is used in operator overloading.

Why the name magic methods?

Here you don’t need to call them directly as you do for other methods. Python calls them for you internally from the class on certain action. For example, when adding two numbers using + operator, python calls __add__() method internally.

Well known Dunder method: __init__()

If you have already used class in Python then you might have seen __init__() method. Constructors in Python are dunder methods.  Its used to pass initial arguments to Python class. It is used for object initialization.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
p = Point(10,5)
print(p)  

Gives output as

<__main__.Point object at 0x00000205182133A0>

When __init__() method is invoked, the object here point is passed as self. Other arguments used in the method call are passed as the rest of the arguments to the function.

It just returns the memory address of the object point. For object representation we have __repr__() and __str__() methods.

__repr__():

It is the official or formal string representation of objects.

class Point:      
    def __init__(self, x, y):
        self.x = x
        self.y = y     
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

p = Point(10,5)
print(p)
Output:
Point(x=10, y=5)

This gives the name of class and value of properties of the class. The goal here is to be unambiguous. Very helpful in debugging.

__str__():

It is used for informal string representation of object. If not implemented, __repr__ will be used as a fallback. Here goal is to be readable.

class Point:   

    def __init__(self, x, y):

        self.x = x

        self.y = y

    def __str__(self):

        return f"Point(x={self.x}, y={self.y})"

p = Point(10,5)

print(p)
Output:
Point(x=10, y=5)

when you call print() it first looks for __str__() to see if it’s been defined otherwise it calls __repr__().

__new__():

When you create an instance of a class, Python first calls the __new__() method to create the object and then calls the __init__() method to initialize the object’s attributes. It is a static method of the object class.

class SquareNumber(int):
    def __new__(cls, value):
        return super().__new__(cls, value ** 2)
x = SquareNumber(3)
print(x)
Output:

9

__add__():

The magic method __add()__ performs the addition of the specified attributes of the objects. Internally, the addition of these two distance objects is desired to be performed using the overloading + operator.

class concat:
  
    def __init__(self, val):
        self.val = val
          
    def __add__(self, val2):
        return concat(self.val + val2.val)
  
obj1 = concat("Hello")
obj2 = concat("Abaython")
obj3 = obj1 + obj2
print(obj3.val)
Output:
HelloAbaython

Magic or dunder methods are useful to emulate behaviour of built-in types to user defined objects and is core Python feature that should be used as needed. 

Points to note:

  • The __init__() method is automatically invoked during the time of the creation of an instance of a class. It is called a magic method because it is called automatically by Python.
  • This __repr__ magic method is used to represent a class instance in a string and it returns the string representation of the value supplied.
  • The __new__() magic method is implicitly called before the __init__() method. It returns a new object, which is then initialized by __init__().
  • The built-in str() function returns a string from the object parameter and it internally calls the __str__() method defined in the int class.
  • The __add()__ method is called internally when you use the + operator to add two numbers or for concatenation of strings

How to add CSS to HTML?

Basic Insight into Inline, Internal and External CSS

Before getting into the topic of how to add CSS to HTML, first we will try to understand what CSS means, how to write it, difference between HTML and CSS, advantages of CSS.

What is CSS?

CSS stands for Cascading Style Sheet. In simple terms, CSS is used to style an HTML document. It describes how an HTML document is displayed. CSS defines the design and layout of a webpage. It can control how a web page look when loaded in browser. The term “Style Sheet” refers to the CSS document itself whereas “Cascading” refers to how style rules are applied to elements present in a web page.

What is the difference between HTML and CSS?

          While building a website, we will usually start with HTML. HTML is a Markup language, we can add headings, paragraphs, images, tables, forms, lists etc., But HTML is more of static in that we cannot change how the above-mentioned elements are presented and displayed in a webpage. It is often used for wide variety of styling purposes including changing text and background color on a page, removing underline from links, animating images, text and other HTML elements. At this point we will need CSS.CSS describes how HTML elements are displayed on a webpage. Thus, usually HTML and CSS go hand-in-hand with website development. Since the creation of CSS several updates have been made to add additional functionality to CSS, now the current standard is CSS3.

Advantages of CSS:

  • Less Coding: Developer can use CSS to apply the same styling to multiple pages and page elements across a website.
  • More Styling Options: CSS allows us to add lot more styling options to customize our website.
  • Standardization: Standardization gives us uniformity which means a developer can understand the style of a website just by looking at the CSS file.
  • Better Performance: As above mentioned, less code means smaller files, and smaller files automatically leads to less loading time which results in better performance.

How to write CSS?

A CSS syntax looks like this:

The Selector points to the HTML element we want to style.

The declaration block contains one or more declarations separated by semicolon.

Each declaration includes a CSS property and a value separated by colon.

Multiple declarations are separated by semicolon and a declaration block is enclosed by curly braces.

How to add CSS to HTML?

Now we will get into the topic of adding CSS to HTML, we can add CSS to HTML by three ways:

  • Inline CSS
  • Internal CSS
  • External CSS

Inline CSS:

          An inline CSS may be used to apply a unique style to single element. Inline styles are defined within the ‘style’ attribute of the relevant element. It is placed inside the HTML tag to change the style of an element. Since we cannot separate style and content in this type and it has violated many of the advantages of CSS, its generally not recommended to use in practice.

Output:

Internal CSS:

          CSS code is embedded in an HTML document. It is written inside the <style> element, inside the head section. It can be used when single HTML page has a unique style. Suitable for small web projects and individual web pages with their own styling.

Output:

External CSS:

          External CSS exists in its own file. The file is linked with HTML with <link> tag. It is the most common method, since one CSS can be used for multiple HTML documents. To create an external css we can write the code in any text editor or code editor and save the file with .css extension. To link the HTML and CSS file place both the files in same folder.

Linking CSS to HTML:
<link rel="stylesheet" href="external.css">
HTML:
CSS:
OUTPUT:

In this article we have learned basic understanding of CSS, its advantages and three ways of adding CSS to HTML.

What is server-side scripting?

Server scripts run on server side or database. Web browsers communicate with web servers using HTTP. When a HTTP request is made from web browser to web server, a HTML response is sent back from the web server to web browser. Server-side scripting means everything that happens on the server. Web browsers communicate with web servers through something called HyperText Transfer Protocol (HTTP). When you make any action with your browser, like entering some URL and clicking enter, an HTTP request is sent from your browser to the targeted server. After that, the server is waiting for a client-side request; this request is sent by something called a method like POST, GET, or DELETE.

Then, the server processes this request when it arrives and gives something called HTTP Response to the browser; this response holds a status line indicating whether the request succeeded or not (e.g. “HTTP/1.1 200 OK” for success).

The body of the response to a request would contain the requested content, maybe an image, Html page, or anything else. So, we can say that server-side scripting is executed and processed on the server.

The server accepts the request from the web browser or client’s computer, processes the request and return the result (requested file) to respective client that placed the request.

These are programs that run on a web server to generate dynamic web pages, creating a unique user experience for each user.

Main advantage over client-side scripting is that raw data is never transferred over the internet. All processing are done on web server.

Helpful in developing interactive website which involves database.

Suitable for more complex tasks with lot of processing power.

If any problem arises on server side fixed locally on the server.

Server-side script:

Server-side script is a program that is executed on server side when user requests information. Script do not download at client side.

When the client or visitor requests the page, the web server reads it first. After reading, the web server locates the page file on the disk, loads into memory and asks the script engines (or interpreter) to process the script code. After processing, web server generates the HTML page and pass back to the server. The browser processes the client side script along with the HTML

web page from the server and display the web page on the client’s computer screen.

Server-side means ““Happening during the internal processing a server performs as it tries to serve a page back to a client who’s requested it.”

PHP and MySQL are always server-side scripting language. Web browser don’t understand them.

Back end is used as synonym for server-side scripting.

Differences from Client-Side Scripting:

  • Server-Side Scripting is used in the back-end, where the website’s source code is hidden at the client-side. On the other hand, client-side scripting is used at the front-end, which users can see from their browser.
  • When a server-side script is run, it sends a request to the server. Client-side scripting, on the other hand, does not require any server interaction.
  • HTML, CSS, and JavaScript are examples of client-side scripting languages. Programming languages such as PHP, ASP.net, Ruby, ColdFusion, Python, C#, Java, C++, and others, on the other hand.
  • Server-side scripting helps personalize web pages and make dynamic changes to websites. On the other side, the client-side script will effectively reduce the load on the server.

What is client-side scripting?

Before jumping into client-side scripting, first we will see a short intro about script.

What is a script?

Script is a small embedded program. Popular scripting languages are Javascript, VBscript etc.,

HTML is not a scripting language because it does not have <script> tag. We need to use <script> tag to generate a script. </script> is used to end the script.

The type attribute in script specifies the type of language we are using. We can also use language attribute.

//type attribute
<script type = “text/javascript”>
     document.write(“TutorialRide”);
</script>
//language attribute
<script language= “javascript”>
     document.write(“Abaython”);
</script>

Client-side scripting:

Client side script is a small program embedded into your web page. Client-side scripting means ‘happening inside your browser’. Here scripts are executed on the browser without connecting to server. When the server sends the script along with HTML webpage to the client, the script runs on client’s browser either while page is loading or after page is loaded.

It is a technique for enhancing the interactivity of online web pages.

It is widely useful in creating dynamic user interface components like pull-down menus, navigation tools, animation etc.,

Its helpful in making the webpage user-friendly.

So, HTML, CSS and JavaScript all are client-side. They are stored on the server like files, but it’s the responsibility of the browser to do anything with them.

JavaScript is used to create dynamic and responsive webpages.

Benefits:

  • Client side scripting is quite easy to learn with minimum programming knowledge.
  • It is light weight and easy to implement. Editing and executing code is fast.
  • Data processing is done on client side from server so it is easy to scale applocations  for large set of users . Reduces workload on server.
  • Execution of client side script is quick as it done on client browser.

Limitations:

Main problem is security as the code is sent as it is. It is usually visible. Not suitable for sensitive data transmission. The web application based on the heavy JavaScript can be complicated to debug and maintain. Running of script depends on browsers configuration and security level. More limited functionalities.

What is window object?

Window object represents the window in a browser. JavaScript environment has global object. Window object is a global object. Any variables created with global scope are properties of this window object and functions are methods of it. The window object methods are used to retrieve the information from the browser window.

Browser Object Model:

BOM(Browser Object Model) is a collection of properties and methods that contains information about the browser. Using window object we can find the browser name, dimension of window, page history etc., BOM is also used to create pop-up window.

JavaScript can be run in different environments. But BOM makes sense only in browser environments. In environments such as node.js we don’t have window object but we still have global object.

Window Object Methods:

MethodDescription
alert()displays an alert box with a message an OK button.
blur() removes the focus from the current window.
clearInterval() clears the timer, which is set by using setInterval() method.
close()specifies a method that closes the current window.
confirm()specifies a method that displays a dialogue box with a message and two buttons OK and Cancel
focus()specifies a method that sets the focus on current window.
open()specifies a method that opens a new browser window
moveTo()specifies a method that moves a window to a specified position
moveBy()specifies a Method that moves a window relative to its current position.
prompt()specifies a method that prompts for input.
print()specifies a method that sends a print command to print the content of the current window.
setTimeout()specifies a method that evaluates an expression after a specified number of milliseconds.
setInterval()specifies a method that evaluates an expression at specified time intervals (in milliseconds)
resizeBy()specifies the amount by which the window will be resized
resizeTo()used for dynamically resizing the window
scroll()scrolls the window to a particular place in document
scrollBy()scrolls the window by the given value
stop()this method stops window loading
Example:
1)window.alert("Hello Abaython!!");
2) const myWind = window.open("", "", "width=250, height=200");
myWind.blur();
3) const myWindow = window.open("", "", "width=250, height=200");
myWindow.focus();
4) <!DOCTYPE html>
<html>
  
<body>
    <h2>The setInterval() Method</h2>
    <p id="demo"></p>
  
    <script>
        const element = document.getElementById("demo");
        setInterval(function () {
            element.innerHTML += "Abaython</br>"
        }, 500);
    </script>
</body>
  
</html>
Output:

Window Object Properties:

Property NameDescription
window.documentThe HTML document that is shown in the window is represented by the Document object, which is referred to by the document property.
window.consoleThe console gives the window’s Console Object back.
window.locationThe location attribute makes reference to the Location object, which has data about the page’s current URL.
window.defaultStatusIt is now Abandoned.
window.closedIf a window is closed, it returns a true boolean value.
window.frameElementIt gives the window’s current frame back.
window.framereturns every window item currently active in the window.
window.historyRetrieves the window’s History object.
window.lengthIt gives the number of iframe> elements currently present in the window.
window.localStorageprovides the ability to store key/value pairs in a web browser. stores data without a time.
window.openerIt returns a pointer to the window that created the window in the opener function.
window.nameReturns or sets a window’s name.
window.parentBrings up the current window’s parent window.
window.sessionStorageProvides the ability to store key/value pairs in a web browser. Contains data for a single session.
window.statusIt is now Deprecated. Don’t employ it.
window.topIt provides the top-most browser window back.
window.screenThe screen attribute makes reference to the Screen object, which stands in for the screen that the browser is shown on.
window.historyThe History object, which includes details about the current page’s browsing history, is the subject of the history property.
window.screenLeft:The x-coordinate of the current window relative to the screen.
window.screenTopThe y-coordinate of the current window relative to the screen.
window.screenXThe x-coordinate of the current window relative to the screen (deprecated).
window.screenYThe y-coordinate of the current window relative to the screen (deprecated).
window.navigatorAn object representing the browser and its capabilities
Example:
//console property
console.log(window.location)
Output:

Location {ancestorOrigins: DOMStringList, href: ‘chrome://new-tab-page/’, origin: ‘chrome://new-tab-page’, protocol: ‘chrome:’, host: ‘new-tab-page’, …}

// document property
window.document
Output:

Window object represents the browser window itself. window object is an important part of the JavaScript language and is frequently used in web development to manipulate the web browser and the document being displayed. We have also seen about its various methods and properties.

What are polyfills and transpilers in JavaScript?

There are situations where we might have encountered that our code runs in one browser and not in another. This may be because one of the browsers may not be updated with latest features. Now let’s see about polyfills and transpilers.

Polyfills and transpilers:

JavaScript like many programming languages evolves steadily. To make our latest code work on old engines that don’t understand the latest features we have two tools : polyfills and transpilers.

Transpilers:

Term transpiling is the union of transformation and compiling. Transpiler is a piece of code or plugin that translates (‘read and understand’) one source code to another source code. It parse the modern code  and rewrite it using older syntax of that language that will work in older engines.

Babel is one of the most used transpiler

Project build systems like Webpack or parcel allows us to automatically run transpiler on every code change so it’s easy to integrate transpiler into our development process. Developers run their transpiler in their own computer or in the cloud and then deploys the transpiled code to the server.

Example:

Nullish coalescing operator is introduced in 2020. So older browser transforms our code as follows:

// before running the transpiler
num = num ?? 150;
// after running the transpiler
num = (num !== undefined && num !== null) ? num: 150;

Polyfills:

At times when new functionality is not available in old outdated browser engines. The code that uses new functionality won’t work. To fill this gap, comes polyfills.

Polyfill is a piece of code that can add, update a feature that engine may lack.

A polyfill is a browser fallback, made in JavaScript that allows functionality you expect to work in modern browsers to work in older browsers.

Example:

filter() method is introduced in ES5 and some outdated browser doesnot support

const arr = [1, 2, 3, 4, 5, 6];
const filtered = arr.filter((e) => e % 2 === 0); // filter outs the even number
console.log(filtered); // [2, 4, 6]
Polyfill for filter():
Array.prototype.filter = function (callback) {
  // Store the new array
  const result = [];
  for (let i = 0; i < this.length; i++) {
  // call the callback with the current element, index, and context.
  //if it passes the text then add the element in the new array.
    if (callback(this[i], i, this)) {
      result.push(this[i]);
    }
  }
  //return the array
  return result
}
Two interesting polyfill libraries are:
  • core.js that supports a lot, allows to include only needed features.
  • polyfill.io service that provides a script with polyfills, depending on the features and user’s browser.

How to use call(), apply(), bind() in JavaScript?

In JavaScript objects have their own properties and methods. With every function we have three methods: call(), apply() and bind().

Before moving into this concept, first lets have a recap on this in functions. This keyword determines how a function is called (runtime binding).

There is a feature in JavaScript which allows to use the methods of some other objects to another object without redefining them. This way of borrowing is done through call(), apply(), bind() methods.

Call(), apply(), and bind() methods are used to set the this keyword independent of function call. Useful in callbacks.

Call():

Call method sets the this inside function and immediately executes the function. Here you can pass arguments as a list.

Syntax:

function.call(thisArg, arg1, arg2, …)

function – function that needs to be invoked with different this object.

thisArg – value that needs to be replaced with this keyword present inside this function.

arg1,arg2,… – arguments passed for invoking function with this.

Example:
 function test(arg1, arg2){
   console.log(this.num, arg1, arg2); // 100, 10, 20
}

test.call({num: 100}, 10, 20);
Output:

100,10,20

apply()

apply() method binds the this value to the function and executes the function. Here  you can pass argument as an array.

Syntax:
function.apply(this, [argumentsArray])

It returns the result of the function which is invoked by this.

function test(...args){
  console.log(this.num, args);//100, [1,2,3]
}
test.apply({num: 100}, [1,2,3]);
Output:

100, [1,2,3]

Bind()

Bind() function binds this value to the function and returns new function. We need to invoke the returned function separately.

Syntax:
function.bind(this,arg1,arg2,arg3,...)

Bind returns a copy of function with this and arguments.

function test(arg){

 console.log(this.number, arg);

}

let bindedFn = test.bind({number: 1}, "Abaython");

bindedFn();
Output:

1 Abaython

Differences : call() vs apply() vs bind()

call()apply()bind()
DefinitionCall method is a predefined javascript method. With call an object can use a method belonging to another object. Here we supply list of argumentsSimilar to call(). But here we supply array of argumentsBind() helps in creating another function and execute later with new this function
ExecutionAt time of bindingAt time of bindingAt time when we execute the return function
Return?Yes it returns and calls the same function at time of bindingYes it returns and calls the same function at time of bindingYes it returns a new function of copy of function which can be used later.
ParameterList of argumentsArray of argumentsArray and any number of arguments

Key points to note:

  • call: binds the this value, invokes the function, and allows you to pass a list of arguments.
  • apply: binds the this value, invokes the function, and allows you to pass arguments as an array.
  • bind: binds the this value, returns a new function, and allows you to pass in a list of arguments.

Event Delegation in JavaScript

Event delegation in JavaScript is a pattern that efficiently handles events. It adds single event handler to parent element instead of having to register multiple event handlers to the child elements.

Adding multiple event handlers to a page has adverse effects and to avoid this event delegation is used. Before jumping into event delegation, we need to understand event propagation.

Event Propagation:

                  Three phases of event propagation: event capturing, event target, event bubbling.

  • Event capturing – event goes down to target element.
  • Event Target – event reached target.
  • Event Bubbling – event bubbles from element.

Event Capturing:

                   When an event takes place on a target element, the event handlers on the parent element are executed first and after that, the event is propagated down towards the target element and target event handler is executed.

document → html → body → parent → child

It is also known as trickling outer event handler fires before specific event handler fires.

Here div fires before button.

Capturing has higher priority than bubbling. Capturing event handlers executes before bubbling event handlers.

Event Target:

                   It is a phase where the event reaches the target element and the event handler execution takes place

Event bubbling:

                   When an event takes place on  a target element the event handler on target element is executed first and then it is propagated upwards to its parent element and their event handlers are executed.

child → parent → body → html → document

The process is bubbling, because events bubble from inner element up through the parents like a bubble in the water.

Almost all events bubble. A focus event does not bubble.

To stop bubbling – event.stopPropagation

event.target:

The most deeply nested element which causes the event is target element, accessible as event.target: Handler on parent can always get details about where it actually happened.

event.Target – ‘target’ element that initiated the event, it doesn’t change through bubbling process.

this(=event.currentTarget) – ‘current’ element, the one that has a currently running handler on it.

Listening to propagation events:

Using addEventListener() method we can listen to propagation events. It accepts three arguments: eventname, callback function and an optional capture value, which is false by default.

element.addEventListener(event, handler, false)

Example:

<div>
        <span>

             <button> Click Me! </button>

        </span>

</div>

Here, <div> is a parent of <span> which in turn is a parent of <button>

Due to event bubbling, when button receives an event, say click that event bubbles upto span and div respectively and they also receive event.

How does event delegation work?

Instead of handling event on button, we handle it on div. The idea is to delegate event to a different element instead of actual elements.

const div = document.getElementsByTagName("div")[0]

div.addEventListener("click", (event) => {

  if(event.target.tagName === 'BUTTON') {

    console.log("button was clicked")

  }

})

The event object has a target property which contains the information about the element that actually received the event. The target.tagname get the name of the tag for the element.

Benefits:
  • Write cleaner code
  • Fewer event listeners.
  • Easier to add or remove elements without having to add or remove existing event handlers
<div>
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
</div>

Here we have 3 buttons and each button handle a click event. It’s implementation

const div = document.querySelector('div')

div.addEventListener("click", (event) => {
  if(event.target.tagName === 'BUTTON') {
    console.log(event.target.innerText)
  }
})

We have created one event handler for all 3 buttons. As  click event on these buttons propagates upward in the DOM tree, we can use a common parent or ancestor that they have to handle the event.