The "click" method in jQuery
The click() method in jQuery is a built-in method that fires an event when the relevant element is clicked on. Clicked on simply means that the user presses and releases the mouse button on that element.
How do we use this method?
The click() method has two ways that it can be called:
- With a given function argument
- Without a given argument
The illustration below shows the method signature:
Implementation
Now that we know how to call this method, let’s look at both implementations of the click() method
1. With a given function argument
This implementation takes in input a function and runs that when the click() method is called.
- The code is written in the
bodyof the HTML code and is written between thescripttag. - The function is called as an attribute of the
h1style. - It takes as input a separate function which is then declared within the argument.
- The function uses the
thisoperator to apply thetogglemethod on the object using a delay of 1000 ms.
2. Without a given argument
In this case, the cick() method is called to fire an onclick event already assigned to an element. This way a separate element can also be used to call the onclick event of another element. The example below shows how this is done.
-
The first step is to first declare an object of a particular style attribute which is clickable and declare and
onclickaction for it as shown on line 11. -
The second step is to create a
scriptblock in thebodyof the code where theclick()method is now attributed to a different style format,p. -
The third step is to call the already defined
onclickmethod forh1within this function call, as shown on line 15. -
This then calls the same
onlickmethod for a particular attribute on a completely separate one.
Free Resources