2.5 Handle events for regular html elements

We have handled press event for a ui:button. But what if we need to handle events for normal html tags. Like <div>, <p>, <button>, <span>, etc. ?

Well, generally speaking, it is almost the same. We just handle those events as we normally do in javascript. Below is a sample code for a drag and drop demo app. This piece of code is provided by Brian Fear (also known as Sfdc fox).

The code

Let’s create a new lightning app called DragDropDemo. Below is the app code:

<aura:application >
    <aura:attribute name="values"
                    access="private" />
    <aura:attribute name="dragid"
                    access="private" />
    <aura:handler name="init"
                  action="{!c.doInit}" />
    <div class="droparea" 
        <aura:iteration items="{!v.values}"
            <div class="row" 

Css file:

    border: 1px solid black;
    position: relative;
    margin: 3px;
.THIS.droparea .row {
    position: relative;
    border: 1px solid red;
    padding: 3px;
    margin: 3px;

Javascript Controller:

    doInit: function(component, event, helper) {
        var values = "a b c d e".split(' ');
        component.set("v.values", values);
    dragstart: function(component, event, helper) {
        component.set("v.dragid", event.target.dataset.dragId);
    drop: function(component, event, helper) {
        var dragId = component.get("v.dragid"),
            values = component.get("v.values"),
        temp = values[dragId];
        values[dragId] = values[event.target.dataset.dragId];
        values[event.target.dataset.dragId] = temp;
        component.set("v.values", values);
    cancel: function(component, event, helper) {

Try this app and see how the drag and drop functionality works.

A little bit explanation

In the dragstart function, the controller used dragId attribute to capture the dragged div’s original position. And in drop function, it simply did a swap between the values of original position’s value and dropped position’s value. And then use component.set to reset the values attribute.

Don’t worry about event.prentDefault() for now.

For aura:iteration attribute, we will explain that further in our next post. For now, just consider it similar to apex:repeat in Visualforce pages.

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *