codergirrl
codergirrl

Reputation: 155

How Javascript control events

Let's say I have a simple code using onmouseover event

    <div onmousemove="myMoveFunction()">
      <p id="demo">I will demonstrate onmousemove!</p>
    </div>

(from w3school)

I want to ask that, how does Javascript know mouse is on that div? Or when we use onclick, how does Js know button has been clicked. Is there automatic event listeners? or Is there any cycle controlling changes for events continually in the background? Please help me I'm confused.

Any links to read would be okay too

Upvotes: 0

Views: 214

Answers (2)

marzelin
marzelin

Reputation: 11600

A browser is responsible for gathering events as they appear on the page. When there's an event listener added for a given action, the listener's callback is added to the event loop. Event loop is an infinite loop that constantly checks if there's something to do (in a cpu optimized manner). On event loop there are two main tasks:

  • rendering the page if there's a change in DOM or CSSOM
  • executing callbacks when some specific action happens

It is important to know that javascript is single threaded, meaning if there's a long running callback, the browser won't be able to rerender the page so the page just freezes.

Another way to understand what's happening under the hood is to open chrome dev tools and go to performance panel. You can find there exactly what happens when you interact with the page: enter image description here

There are a few ways to add an event listener:

  • in html using on[eventname]=action, i.e. <div onmousemove="myMoveFunction()">
  • in javascript by assigning a function to on[eventname] property, i.e. windows.onload = () => alert("hello");
  • in javascript by using addEventListener() method, i.e. element.addEventListener("click", () => alert("hello"));

If you want to know more about event loop, here are good resources:

There's also pretty good and free course that explains a lot about how browser works and most importantly shows you how to improve site's performance: Browser Rendering Optimization

Upvotes: 3

jacobdo
jacobdo

Reputation: 1615

When you use e.g. <div onmousemove="myMoveFunction()">, as the browser reads the DOM on page load, behind the scenes it generates code for the event listener and there is not much else to it.

Upvotes: 1

Related Questions