>_How to check if click is invoked by a user or via a method?

Posted 1 year ago  252 reads  

Author: Marghoob Suleman

In JavaScript, you can determine if a click event is invoked by a user or via a method by checking the event.isTrusted property. The isTrusted property is a Boolean value that indicates whether the event was generated by the user or by a script.

Here is an example:


const myButton = document.getElementById("myButton");

myButton.addEventListener("click", function(event) {
  if (event.isTrusted) {
    console.log("The button was clicked by the user!");
  } else {
    console.log("The button was clicked programmatically!");
  }
});

function clickButton() {
  myButton.click(); // simulate a click event
}

clickButton(); // invoke the function

In this example, we add a click event listener to the button element and check the event.isTrusted property to determine if the click event was generated by the user or via a method. If the value is true, we log a message saying that the button was clicked by the user, otherwise, we log a message saying that the button was clicked programmatically.

We also define a function called clickButton that simulates a click event by calling the click method on the button element. When we call this function, it will trigger the click event, but since it was not generated by the user, the isTrusted property will be false, and we will log the message saying that the button was clicked programmatically.

Note that the isTrusted property is not supported in all browsers, so you should test your code thoroughly before relying on this property.

The isTrusted property is supported by most modern browsers, including Chrome, Firefox, Safari, Opera, and Edge. However, it is not supported by Internet Explorer or earlier versions of Microsoft Edge (before the switch to the Chromium engine).

Powered by HashtagCms.org