- “preventDefault()” method.
- “Boolean Value” approach.
- “stopPropagation()” method.
The “preventDefault()” method cancels the attached event if it is cancel-able. This method can be utilized to detach the attached event from the accessed link thereby preventing the action to be performed.
In the given syntax:
- “event” refers to the event to be detached.
Go through the below-given code-snippet:
Follow the below-stated steps:
- Firstly, include the stated heading to be displayed on the Document Object Model(DOM).
- After that, specify the “URL” using the “href” attribute.
- Also, attach a “click” event with the URL with the help of a function using the “addEventListener()” method.
- Finally, the “preventDefault()” method will be applied with the help of the function’s parameter to detach the attached event.
This approach can be implemented by returning the “false” boolean value upon the triggered event.
The following lines of code demonstrate the stated concept:
In the above code snippet:
- First, within the “<center>” tag, allocate an input text field.
- Also, attach an “oninput” event with the specified “placeholder” value. This will result in invoking the specified function upon inputting the text.
- Finally, specify the stated message in the alert box. The returned boolean value will result in avoiding the dialogue box to be displayed.
In the above output, it can be observed that upon the accessed function, the alert dialogue box is not displayed thereby canceling the attached event.
The “stopPropagation()” method prevents the same event from being propagated. This method can be utilized to stop propagating between the two divs upon checking the checkbox.
Observe the following lines of code:
- In the first step, similarly, include the stated heading.
- Now, include two “div” tags with attached “onclick” events with each of them invoking two different functions element2() and element1().
- Also, include a checkbox with the specified id. This checkbox will result in stopping the propagation between two divs.
In the above js code:
- Define a function named “element1()”. Here, the parameter “e” refers to the “event” being fired specified in the HTML part of the code.
- In its definition, display the alert dialogue box having the stated message.
- After that, access the created checkbox by its id using the “getElementById()” method. Also, apply the “checked” property to it in order to check the condition of the checked checkbox.
- Then, apply the “stopPropagation()” method referring to the parameter “e”. This will result in stopping the propagation from one function to the other function.
- Similarly, define another function “element2()” to be propagated upon. This function will be functional before propagation only.
Here, observes the behavior upon clicking the div upon checking the checkbox.