Explain the use of the $.fn.bind and $.fn.trigger
In this article, we will learn two methods that are related to jQuery events of DOM when the user or the program triggers an event.
Use of bind():
- It adds a common event listener method for multiple events to a single DOM element.
- Avoids code repetition, as the same function does not have to be added for different events separately.
- We have given a single functionality to a DOM element for 3 different events. Select the element, call the bind() method on it, and pass two arguments, first is the name of event and the second argument is the function that handles the event.
- Generate a random number between 0 and the last index of the colours array, using Math.floor() and Math.random() function in combination. Use this number to access any one colour randomly from an array of colours. Save this colour to put this as the value of the CSS background-color property of the HTML div tag.
Use of trigger():
- The event-dependent functions can be executed without the user triggering that event.
- The user will be free from doing a lot of things, as the script will trigger necessary events on its own and do a lot of the user’s work for him
- The below code above extends the bind() method. We add a button with an id attribute. Whenever we click the button, we want to change the color of the HTML div.
- Add an event listener for the click event on the div tag and repeat the code that changes the colour of the div.
- Or simply make one of the events to be triggered. We pass one argument to the trigger() method, which is the name of the event we want to be triggered, we choose the click event, you can change the code to use other events as well, just make sure they are part of the events that are used in the bind() method so that ultimately, the colour of the div is changed.
My Personal Notes arrow_drop_up
Please Login to comment...