Home > OS >  Mousclick vs keypress
Mousclick vs keypress

Time:07-28

While making sounds with the keyboard my teacher used:

document.addEventListener("keypress", function(event) {
---------------function-body-----------
});

And with a mouseclick, he used

document.addEventListener("click, function(){
var drum = this.innerHTML;

I am not understanding why "event" cannot be used with mouseclick?

CodePudding user response:

You can use event property, it usually is just not necessary with a mouse click.

document.addEventListener("click", function(event){
    var drum = this.innerHTML;
});

The above code is perfectly valid Javascript. Just a note, make sure you terminate your strings with ".

CodePudding user response:

You can use the event interface with any event. You don't always need it however but it's always passed regardless.

These are the MDN Docs on what the event interface is.

Here is a simple example of one way the event interface is useful, and a very simple (a bit unrealistic) use case of when you might not need it.

const container = document.querySelector('div');

container.addEventListener('click', function(event) {
   // Event contains data about the event, such as the element that triggered it.
   event.target.textContent = 'you clicked me!';
});

const input = document.querySelector('input');
const output = document.querySelector('.output');

input.addEventListener('keydown', function() {
   // You don't need the event for the below side effect.
   output.textContent = `You've entering some text.`;
});
<div>
<button>Click me</button>
<button>Click me</button>
<button>Click me</button>
<button>Click me</button>
<button>Click me</button>
</div>

<input />
<div class='output'></div>

  • Related