Posts tagged ‘lightning’

Handle DOM Events Raised by Base Lightning Components

Buntysmum / Pixabay

Base Lightning components, introduced with the Winter ’17 release, provide developers with granular and reusable “out of the box” components that can be used to render HTML for everything from navigation menus, to form fields, to data tables, and many other UI patterns in between.

The primary value add of base Lightning components is that they apply the Salesforce Lightning Design System (SLDS) styling to the HTML that is output when the components render.

Another value add is that many of the base Lightning components raise events that can be handled within your component hierarchy.

By now you should realize that the Lightning Component Framework is an event driven architecture, and how you manage events is a critical aspect to Lightning application design.

Thankfully, raising and handling events from base Lightning components is in itself fairly straightforward and handles many of the use cases requiring events to be raised from user interaction.

What I have found in my own development experience is that there are certain edge use cases where the events raised by base Lightning components do not go far enough.

This doesn’t mean we need to throw the baby out with the bathwater and abandon base Lightning components in favor of hand writing all custom HTML and JavaScript, however.

It just takes a deeper understanding of how events are raised and handled to find an elegant solution that incorporates base Lightning components and a minimal amount of custom HTML.

I would like to propose a simple solution for when you run into situations where you need a more robust set of events than what are raised by base Lightning components, and provide some background on “how” and “why” this works.

A Common Pattern: Onfocus and Onblur

One of the things that I have noticed with the architecture of base Lightning Components is that many of them share a common pattern in the way in which they raise events.

While some base Lightning components do not raise any events of their own, many components in the lightning: namespace have event attributes that can be used to raise and handle events within the component hierarchy.

Of the base components that do raise events, such as <lightning:input>, <lightning:select>, <lightning:button> and others, share the same two component event attributes: onfocus and onblur.

The focus event is raised when an element is in focus – meaning a user has clicked on or tabbed to that particular element.

blur is the opposite of focus. When an element is currently in focus and the user then clicks on or tabs to a new element, the blur event fires on the previously focused element while the focus event fires on the newly focused element.

The focus and blur events are typically associated with HTML elements such as <select>, <input> and <a>, but it is important to note that the onfocus and onblur event attributes for base Lightning components do not raise the focus or blur Document Object Model (DOM) events.

When a base Lightning component includes the onfocus or onblur event attributes in its definition, what it actually raises is an event that is custom to the Lightning Component Framework and can only be handled by another Lightning component.

Beyond Blur: Additional Base Lightning Component Event Attributes

Most of the components that raise the focus and blur events will also raise another complementary event specific to the way in which a user interacts with the component itself.

For example, in addition to the onfocus and onblur event attributes, <lightning:button> can raise a third event called click by including the onclick event attribute with a reference to a controller function.

This is because the expected interaction with the <lightning:button> component is for a user to click on it.

The <lighting:select> component, which displays a picklist of options, raises a third event called change by including the onchange event attribute in the reference to the component.

Again, this is because the expected interaction with <lightning:select> is for a user to select an option from a dropdown list, and if the newly selected value is different from the previously selected value, that may be of significance from a UX perspective and require the firing of an event.

Remember, when base Lightning components fire events, they are not DOM events – they are component events raised by the Lightning Component Framework.

While they may not be DOM events, they follow a similar propagation pattern in that the events “bubble up” through the component hierarchy and can be handled by any component in the ancestry starting from the component that fired the event all the way up to the root (top level) component. We’ll cover the concept of bubbling a little later to understand how all of this works.

The reason why it is great that Salesforce provides these event attributes for base Lightning components is because the focus and blur DOM events do not bubble and must be handled by event listeners defined at the level of the specific HTML element that raises the event.

In contrast, using the onfocus and onblur Lightning component events enable the events to be handled by a parent Lightning component that references a JavaScript function in its local controller.

These component events are powerful and handle most use cases for firing events directly from base Lightning components based on specific user interactions, but how does it work if you want to handle events other than focus, blur, change or click?

Base Lightning Components and DOM Events

What happens when you want to handle DOM events such as keyup or mouseover from a <lightning:input> component? How can you handle the dblclick event for a <lightning:formattedText> component?

Well…in a nutshell, you can’t. Why? Because there are no attributes defined for these events in base Lightning components.

Lightning components only support events explicitly listed in the documentation. If <lightning:input> only lists onfocus, onblur and onchange as event attributes, then those are the only events that it raises and can be handled by the parent component.

Not to worry, though. There is a solution if you want to handle DOM events that are not explicitly supported by base Lightning component event attributes.

Handling DOM Events Raised by Base Lightning Components

To handle an event that is not supported for a given base Lightning component, you simply need wrap the component in a containing HTML element. This will typically be a <div>, and you will handle the DOM event there.

For example, if you want to handle the dblclick event when a user double clicks the mouse on a <lightning:formattedText> component, simply wrap it in a <div> and include the ondblclick event attribute in the reference to the containing <div> as illustrated:

<div ondblclick=“{!c.myDblclickEventHandler}”>
    <lightning:formattedText value=“Double click on me!“ />

Why does this work?

To understand why this works, you first have to understand something called “bubbling.”

The concept of bubbling is fairly straightforward. When an event that supports bubbling is fired from an HTML element, that event can be first be handled by the actual element raising the event if it has a handler defined for the event.

Note: Not all events support bubbling. As mentioned previously, the focus and blur events do not bubble.

If the HTML element raising the event has not added a listener for the event, or if it does handle the event but does not explicitly stop bubbling by referencing the stopPropagation() function on the Event object, the event will bubble to the parent element of the element that raised the event.

Following the same pattern, the event will continue to raise its way through the DOM tree starting with the parent HTML element and continuing until bubbling is explicitly stopped or the event reaches the root of the HTML document without being handled.

How Does DOM Event Propagation Apply to Base Lightning Components?

Earlier we mentioned that base Lightning components do not support the raising of DOM events, only component events that are raised and handled within the Lightning Component Framework itself.

So what does DOM event bubbling have to do with base Lightning components?

The answer is simple if you think about what base Lightning components actually do – base components exist to simplify the process of generating HTML for UI elements that implement SLDS for you automatically.

Rather than having to hand write all of the HTML and CSS to implement SLDS prototype components such as buttons or form input fields, base Lightning components allow developers to control the styling and behavior of the rendered output by setting attribute values in the definition of the base component.

Base Lightning components, in turn, render HTML elements with references to CSS classes defined in the SLDS external stylesheet.

For example, the following reference to a base Lightning component:

<lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />

Renders the following markup:

<div class="slds-form-element lightningInput" data-aura-rendered-by="5:0" data-aura-class="lightningInput">

    <label class="slds-form-element__label slds-no-flex" for="3:0" data-aura-rendered-by="7:0">

        <span class="" data-aura-rendered-by="9:0">

        This is a sample lightning:input component



<div class="slds-form-element__control slds-grow" data-aura-rendered-by="11:0">

        <input class="slds-input" type="text" id="3:0" style="" data-aura-rendered-by="12:0" name="mySampleComponent">



To break this down, at the core of the rendered output we have an HTML <input> element that is contained by a <div> element. We also have a <span> element, which is the child of a <label> element.

The containing <div> element for the <input> as well as the <label> element are themselves wrapped by a top-level containing <div>.

That’s a lot of nesting! This complex output is simplified by the use of the <lightning:input> component, but how does this apply to raising and handling DOM events?

How Does This Work?

Let’s say that we want to handle the focus event for the <lightning:input> base Lightning component in the previous example. This would be simple because <lightning:input> has an event attribute called onfocus.

All we would need to do in order to handle focus is include the onfocus attribute and reference a controller function like this:

<lightning:input onfocus=“{!c.myFocusEventHandler}” />

Because focus is a component event, we could get information about the component that raised the event by using the getSource() method on the Event object in our controller function:

myFocusEventHandler : function(component, event, helper) {

    var sourceComponent = event.getSource();

    // Additional logic


Simple enough, right?

So now let’s say we wanted to handle the keyup event that gets raised from the <input> element when a user presses and releases a key on the keyboard.

When this event is raised we want to call a function to check whether the user pressed the “tab” or “enter” keys.

How do we do that since onkeyup is not listed as an event attribute in the documentation for <lightning:input>?

This is where we want to wrap our base Lightning component with an HTML element such as a <div> and have the containing element handle the event.

Remember, most DOM events support bubbling. In this example, the keyup event will be raised by the HTML <input> element generated by the <lightning:input> component when it is rendered.

The keyup event will not be handled by the <input> element itself, nor will it be handled by the <div> that contains it or the top-level <div> rendered by the component.

It will bubble up to our wrapper <div> and we will handle the keyup event there by calling the controller function referenced in the onkeyup event attribute.

Here’s what this would look like in your custom component markup:

<div onkeyup=“{!c.myKeyupEventHandler}”>

    <lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />


Handling the DOM Event

When we handle raised events that are native to the Lightning Component Framework, we get access to more robust event handling functionality, such as getting access to the component that raised the event by using event.getSource().

Unfortunately when we raise and handle DOM events like we are doing here, referencing event.getSource() will return an ‘undefined’ value.

So how do we get information about the raised DOM event? This is where we have to know a little bit of JavaScript.

When we raise and handle DOM events using JavaScript, we get access to a number of properties on the Event object that provide references to the HTML elements involved in the firing and handling of the events: references the HTML element that actually fired the event. In our use case, will reference the <input> element where the keyup event occurred.

event.currentTarget references the HTML element that is currently handling the fired event. In our use case, event.currentTarget will reference the <div> that we used to wrap the <lightning:input> component.

Additional Considerations for Using and event.currentTarget

Learning how to use and event.currentTarget for DOM events and event.getSource() for component events will enable you to design a robust event-driven architecture in your custom Lightning components.

So why not just use and event.currentTarget to handle all events, including DOM events and Lightning component or application events?

You can thank Locker Service for throwing cold water on that idea. and event.currentTarget are not available when handling Lightning component events because of Locker Service restrictions.

Without going into the gory details, Locker Service wraps each Lightning component in a secure document that renders the HTML for that component within a virtual DOM.

Using or event.currentTarget would essentially allow you to reach into the DOM for the source component, breaking encapsulation.

Also note that and event.currentTarget are properties of the Event object – not methods. As such, you do not need to append () to the property name – if you do you will experience a JavaScript error.

Additional Resources

A Brief History of Lightning: Dreamforce 2013-2016

The unified Lightning vision as we know it today has been rolled out in fits and starts. To understand how we arrived at the current vision for Lightning, we can look back on prior Dreamforce events as milestones in the history of Lightning.

Dreamforce 2013

At Dreamforce ’13, Salesforce recognized that the world was moving to a “moble first” mindset and rebranded their mobile application as Salesforce1.

With Salesforce1 they also tried to sell the vision of a unified customer experience for the first time. According to a press release for Dreamforce ’13, “Salesforce1 is a new social, mobile and cloud customer platform built to transform sales, service and marketing apps for the Internet of Customers.”

The vision was too ambitious at the time, the messaging was too confusing, and the platform was nowhere close to being ready to support any type of unified experience.

Dreamforce 2014

Lightning emerged as a platform at Dreamforce ’14. Branded as Salesforce1 Lightning, Salesforce opened up the underlying Aura JavaScript UI framework to developers for the first time, enabling the development of custom components for the Salesforce1 mobile application using the same technology that Salesforce had used to develop the Salesforce1 mobile application.

The press release for Dreamforce ’14 hinted at what was in store for Lightning, “Now customers, developers and Salesforce partners can take advantage of the new Lightning Framework to quickly build engaging apps across every device. The same framework Salesforce’s internal development team uses to build apps can now be used to build custom Lightning Components and create any user experience.”

At this point, Salesforce was still using the Salesforce1 branding for the unified end-to-end experience across Salesforce products and platforms, but we now officially had the Lightning Framework to work with.

Dreamforce 2015

Dreamforce ’15 may have been the official coming out party for Lightning, but in an unprecedented move for Salesforce, the company held a special pre-Dreamforce “Meet the New Salesforce” event on August 25, 2015 to announce the new Lightning Experience user interface as well as a complete rebranding of the end-to-end experience to “Lightning.”

The Dreamforce event focused on strengthening the branding and educating developers, admins, and end users on what this unified experience meant for the future of Salesforce. Since then, Salesforce has been all Lightning, all the time.

Dreamforce 2016

With Dreamforce ’16 and the Winter ’17 release of Salesforce, Lightning had finally arrived as a stable, optimized, enterprise-ready platform.

Dreamforce ’16 was less about hype and more about driving Lightning adoption. Sessions focused on design patterns and best practices rather than selling the platform to developers. New tooling was introduced to make the Lightning development experience something that Salesforce developers could get excited about.

With Winter ’17, Lightning Experience felt like a true unified end-to-end experience instead of a patchwork of functionality. The Winter ’17 release notes were packed with enhancements that would get many organizations off of the fence about Lightning and shift the adoption bell curve from towards an early majority from the early adopter state that it had been lingering in while Salesforce filled in the gaps in the platform.

This is the Lightning we had been waiting for.

Why Does it Matter if I Use a Space Between .THIS and a CSS Class Name in the Lightning Component Bundle Style Resource?

One of the things that I have struggled to adequately explain to students in the DEV601 (Programming Lightning Components) course is the difference between using a space between .THIS and a CSS class name or omitting the whitespace after .THIS completely.

I thought this was a Lightning quirk, but it’s actually basic CSS syntax. While this may be obvious to anyone with a deep CSS background, it has never been inherently obvious to me even with ~20 years of CSS exposure.

For example:

.THIS.myTestClass1 {
    text-align: center;

.THIS .myTestClass2 {

    font-weight: bold;


We know from the documentation that .THIS.myClass1 will apply the styling properties only to top-level tags containing a reference to myClass1 within the markup of that particular component. We also know that .THIS .myClass2 will be applied to any tag that contains a reference to myClass2 within a component.

Why is this?

The answer is simple…if you understand what is happening with the underlying CSS.

The first thing we have to understand is that when the Lightning Component Framework is bootstrapped and the app.css external style sheet is compiled, any reference to .THIS that is found within a Style resource in a component bundle is replaced by a base CSS class name that is the full descriptor of the component – i.e. namespace:componentName – with the colon character stripped out.

For example, any reference to .THIS in the Style resource for c:MyComponent will be represented as .cMyComponent in the CSS style sheet that gets compiled by the framework.

Here’s where things get interesting…

Within the HTML that gets generated by the framework, any top-level tag (i.e. a tag that is a direct child of aura:component) that has a class attribute defined will have the base CSS class for the component appended to the values of the class attribute.

For example, if we have the following top-level div tag in c:MyComponent:


<div class="myClass1">




The same div tag will be rendered like this in the HTML output:

<div class="myClass1 cMyComponent">

Whereas if we have the following markup in our component:

<div class="myClass1">

<div class="myClass2">




The child div tag will be rendered like this in the HTML output:

<div class="myClass2">

So here’s where the spacing between .THIS and class names come into play and the key piece of information that I was missing all this time…

When a CSS rule set is defined with a space in between two classes (e.g. .THIS and .myClass2), it becomes what is called a descendent selector.

A descendent selector will apply the styling properties to any matching elements within the ancestry of a containing element, regardless of whether the element is a direct child or if other elements are between the child and the containing element.

This applies not only to class names, but also to element selectors like p or div. For example:

.THIS p {font-weight: bold;}

Learn more about descendent selectors (and CSS combinators in general) here:

Now when we don’t include a space in between .THIS and a class or element name, the styling contained within the rule set only applies to HTML elements where the class attribute references both CSS classes.

So again, if we have .THIS.myClass1 defined in the Style resource for c:MyComponent, the styling will only be applied to HTML elements where both the myClass1 and cMyComponent values are defined in the class attribute for that element.

And as we saw in the examples above, top level HTML elements that have class attributes defined will have the base CSS class of the component appended.

So the “why” behind the no-space styling being applied to top-level tags is because when two (or more) selectors are combined without whitespacing, both (or all) of the classes must be defined as values of the class attribute on the HTML element for the styling to be applied.

Learn more about combining class selectors here:

Again, this may be a “well, duh” revelation for some, but I’m always digging for the “why” behind everything, and this was an important discovery for me as I strive for mastery of the platform. It will change the way I explain this to DEV601 students.

See Mike Topalovich Present at Dreamforce 2016

Dreamforce 2016 df16

This will be my 5th year presenting at Dreamforce, and once again I’m excited about the content that I will be delivering. Come check out a session or two if you are interested in any of these topics, you can bookmark them prior to August 30th so that you have them ready to go when the Agenda Builder opens up.

The World is Flat: Design Principles for Salesforce Data Modeling

Getting the data model right is critical for the performance, usability and maintainability of your Salesforce customizations and custom applications. As you have probably already experienced, the database is unlike any relational database you may have used in the past, and SOQL is definitely not SQL. Attend this session to learn why data modeling is important, how to resist the temptation to normalize the data model and instead apply patterns of denormalization, and what patterns and practices can be applied to balance the competing requirements of user experience, analytics, query performance, scalability and operations to design high-performing data models for Salesforce.

Convert SQL Queries into SOQL Queries

SOQL is the query language of the App Cloud. Join us to learn how to translate SQL queries and joins into SOQL queries and joins. This session is intended for Apex developers who are having trouble understanding SOQL syntax.

Get Started with Responsive Apps in the Lightning Framework

Lightning Components, the UI framework with which the Salesforce1 Mobile application was built, is embedded within the Platform. Lightning Components allow you to rapidly build applications with reusable components using an event-driven architecture. Applications built with Lightning Components can support responsive design, adapting to the user’s device. Join us to learn how to build a simple Lightning application composed of decoupled components and their bundled resources. You should have experience in developing web applications with HTML, CSS, and JavaScript to get the most benefit from this session.

Getting Started with Apex Code for Developers

Do you have Java, C#, or other OOP experience and want to transfer those skills to do some heavy lifting for you on Then get hands-on access to Apex Code, the world’s first cloud-computing programming language. We’ll make the transfer easy from what you already know to what you need to know for writing Apex Code.

This one-day pre-conference training course takes place on Monday, October 3.

Hope to see you in San Francisco! If you want to meet up for a beverage, please connect with @topalovich on Twitter.

Mike Topalovich Salesforce Technical Architect in Chicago
Mike Topalovich - Salesforce Certified Platform Developer I Mike Topalovich - Salesforce Certified Platform Developer II Mike Topalovich - Salesforce Certified Developer Mike Topalovich - Salesforce Certified Advanced Developer
Mike Topalovich - Salesforce Certified Mobile Solutions Architecture Designer Mike Topalovich - Salesforce Certified Platform App Builder Mike Topalovich - Salesforce Certified Administrator Mike Topalovich - Salesforce Certified Advanced Administrator