Home > Enterprise >  Find what happens when you click an html button
Find what happens when you click an html button

Time:11-23

For example, you have this script that adds an event listener to a button like this:

document.getElementById("myBtn").addEventListener("click", function() {
  document.getElementById("demo").innerHTML = "Hello World";
});

How would I see that code in a website, so I can execute the code from the console?

CodePudding user response:

On Chrome, you can open developer tools, select the element, then select the 'Event Listeners' tab:

enter image description here

Which will show you the event listeners bound to the element:

enter image description here

CodePudding user response:

You want to trigger the event from the console. But that is not possible. However, you can call an external function in the second parameter of the EventListener. This function is then in the global scope. You can then trigger the action in the console with the function name that would otherwise be triggered via the click.

makeAction();

document.getElementById("myBtn").addEventListener("click", function() {
  makeAction();
});

function makeAction() {
  console.log('triggered')
  document.getElementById("demo").innerHTML = "Hello World";
}
<button id="myBtn">click</buton>
<div id="demo"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related