on:click Attribute
The on:click
directive allows you to attach click event listeners to elements
in your HTML markup.
Usage
To use the on:click
directive, add it to any HTML element followed by the
JavaScript expression or function call you want to execute when the element is
clicked.
~index.html
<button on:click="handleClick">Click me</button>
Features
- Direct Expression Execution: You can include JavaScript expressions directly
in the
on:click
attribute. - Function Calls: You can call functions defined in your application's scope.
- Access to Event Object: The event object is automatically passed to your handler, allowing you to access event properties.
- Access to Reactive System: The reactive instance is available in the handler, giving you access to the framework's reactivity system.
Examples
- Incrementing a counter
~index.html
<button on:click="$.count++">Increment</button>
- Calling a function
~index.html
<button on:click="handleSubmit">Submit</button>
- Using the event object:
~index.html
<div on:click="console.log(event.target)">Log clicked element</div>
- Conditional logic:
~index.html
<button on:click="$.isActive ? deactivate : activate">Toggle</button>
note
- The expression in
on:click
is executed in the global scope, so make sure your functions and variables are accessible globally. - If the result of the expression is a function, it will be immediately invoked.
- Error handling is built-in, and any errors during execution will be logged to the console.