8. Handling Events
Events are handled synchronously in TargetJS. They are captured at the start of the frameworkâs execution cycle and made
available to all relevant targets within your components. TargetJS provides specialized event targets such as onClick, onResize, and onScroll.
These behave like regular targets but are also triggered when their corresponding browser events occur.
For example, onClick is triggered by a click event, onResize by a window resize, and onScroll by a scroll event.
The best way to illustrate how events work is through examples:
Handling a click
In the first example, the background color of the pane changes randomly whenever you click on it. When a click event occurs, onClick will activate the background target, causing it to execute again.
We can also implement the background update directly within the onClick, especially when there is only one target to activate:
Handling onEnter and onLeave events
In the example below, the background updates when the mouse enters and leaves the square.
The implementation is similar to the previous example, except that we are handling onEnter and onLeave events instead of click events.
Handling a hover event
In the example below, it handles moving events. The background continuously updates whenever we moves the cursor over the square.
Triggering animation with a click
In this example, we use a list of target values [120, 50, 120], which are applied sequentially to both width and height. The first value in the array serves as the initial value. The actual values are then updated over 30 steps for each target.
The animation becomes smoother when both x and y are incorporated directly, rather than being reactive.