Search code examples
javascripthtmlcssevent-listener

How to listen for an event that is happening to another element using JavaScript only?


So from my understanding of event listeners is that the action only applies to the element that you used the event listener on.

But say that I wanted to listen for a click on one element that is in a separate div, but the element I want to apply certain actions on is in a separate div. What would be the best way if possible in doing so?

To help visualize, im looking at this users example.

https://ryannathanwilson.github.io/Rock_Paper_Scissors/

And so from what it looks like it listens for a click on any of the buttons, and then the clicked button shows up in another area and then performs a specific action. Is this possible? Or am I understanding his code incorrectly and the elements that appear at the bottom when clicked is the original element?


Solution

  • You can write a function like this:

    function myfunc(){
             document.getElementById("abcd").value = "Lorem Ipsum";
    }
    

    And call this function on the element you want to listen on:

    <button onclick=myfunc()>Click me! </button>