Stop Propagation event in LWC JavaScript Salesforce.

Stop Propagation event in LWC JavaScript Salesforce.

Table of contents

No heading

No headings in the article.

The Below code shows exact how the Stop Propagation works. First Create a Div inside parent Div which is Nested Div. Now add onclick() function on both the div. Now When you click on the child Div the parent div will also clicked. To prevent this we use StopPropagation() event. StopPropagation() stops the spread of an event but the stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked. LWC Component

<template>
  <div onclick={onClick2} style="padding: 50px;
  background-color: rgba(255, 0, 0, 0.2);
  text-align: center;
  cursor: pointer;">DIV 2
    <div onclick={onClick1} style="padding: 50px;
  background-color: rgba(255, 0, 0, 0.2);
  text-align: center;
  cursor: pointer;">DIV 1</div>
  </div>
  <lightning-input class="slds-p-left_xx-large" type="checkbox" data-id="checkbox" label="checkbox"
    onchange={handleCheck}></lightning-input>

</template>
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import uploadFile from '@salesforce/apex/FileUploaderClass.uploadFile'
export default class FileUploaderCompLwc extends LightningElement {
    check = false;
    onClick1(event){

        console.log('onClick1',this.check);
        alert('Div1 is Clicked');
        if(this.check){
            event.stopPropagation();
            }
        }
    onClick2(event){

        console.log('onClick2',this.check);
        alert('Div2 is clicked')
    }
    handleCheck(event){
        console.log('Handle Check')

         if(this.check === false){
             this.check = true;
             console.log('if',this.check);

         }else{
             this.check = false;
         }
         console.log('out> ',this.check)
    }
}