jQuery bind method Example/Demo

jQuery provides a method called bind() which binds any event types to any element. Let's say you want to bind a click event to a tag.

<a>Link 1</a>

Below jQuery code binds the click event to all the anchor tag of the page.

$(document).ready(function() {
  $("a").bind('click', function() {
      alert('I am clicked');
  });
});

So the advantage of bind is you don't need to write click event for every element (of same type). Just write the bind event and it will automatically attach to all the element.You can also bind events to elements with specific class. See below code.

$("a.link").bind('click', function() {
   alert('I am clicked');
});

Above code binds the click event to all the a tag which are having CSSClass set to"link".You can also bind multiple events to any element at once.

$("a.link").bind('click mouseover', function() {
   alert('I am clicked');
});

Above code will bind click and mouseover event to all the a tag which are having CSSClass set to"link".
Problem with the above code is, it provides the same functionality for both the events. What if you want different functionality/logic for every event? Well, there is another way to achieve the same. See below code.

$('a.link').bind({
  click: function() {
      alert('I am clicked');
  },
  mouseover: function() {
     alert('Mouseover event');
  }
});

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...