- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binding an object's method to a click handler in JavaScript
Following is the code for binding an object’s method to a click handler in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Binding an object's method to a click handler in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">Click Here</button> <h3>Click on the above button to know how many times you have clicked the button</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let testObj = { a: 0, timesClicked() { this.a += 1; resEle.innerHTML = "Times clicked = " + this.a; }, }; BtnEle.addEventListener("click", () => { testObj.timesClicked(); }); </script> </body> </html>
Output
On clicking the ‘Click Here’ button −
- Related Articles
- How to manipulate JavaScript's Date object?
- How to iterate a JavaScript object's properties using jQuery?
- How to get a subset of JavaScript object's properties?
- Binding mouse double click in Tkinter
- How to get a subset of a javascript object's properties?
- Retrieving object's entries in order with JavaScript?
- How to convert a date object's content into json in JavaScript?
- How to create a Python dictionary from an object's fields?
- Selenium WebDriver Error: AttributeError: 'list' object has no attribute 'click'
- How to get only first word of object's value – JavaScript?
- How to change an element's class with JavaScript?
- What's the most efficient way to turn all the keys of an object to lower case - JavaScript?
- How to make a condition for event 'click' inside/outside for multiple divs - JavaScript?
- How to add an event handler to an element in JavaScript HTML DOM?
- How to set an element's display type with JavaScript?

Advertisements