Explain the difference between .bind() and .on() in jQuery with an example.
Explain the difference between .bind() and .on() in jQuery with an example.
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
The .bind() and .on() methods in jQuery are used to attach event handlers to elements. However, there are some key differences between the two methods.
Here is an example of how to use .bind() to attach a click event handler to a button:
Code snippet
In this example, the event handler will only be triggered when the button is already present in the DOM. If the button is added to the DOM after the .bind() method is called, the event handler will not be triggered.
Here is an example of how to use .on() to attach a click event handler to a button:
Code snippet
In this example, the event handler will be triggered for any button that is added to the DOM in the future. This is because the .on() method attaches the event handler to the document, not to the button itself.
In general, .on() is the preferred method for attaching event handlers. This is because it allows you to attach event handlers to elements that are added to the DOM in the future. However, .bind() can be useful in some cases, such as when you need to attach an event handler to a specific element that already exists in the DOM.