Tej Tej - 4 months ago 35
jQuery Question

How to change the span from a jQuery binding to an onClick?

This question might seem trivial but I really need to get the hang of it. Any help regarding this is greatly appreciated.

<span class="first">This thing</span>

$(.first).click(function() {});

Until now I have been using this. But due to some coding constraints, I was told to change the span from a jQuery binding to an onClick. I am unable to follow exactly what they meant by that... Could any help me figure this out and if possible throw a better light on the differences between jQuery binding and onClick binding. Any help in this regard is greatly appreciated. Thanks a lot !


I suggest you to use ".on()" jQuery's feature to bind the event and handle the binded event.

The official jQuery's ".on()" documentation says: "Attach an event handler function for one or more events to the selected elements."

Direct link: http://api.jquery.com/on/

Working example:

$(document).ready(function() {
  $('.first').on( "click", function() {
    alert('you clicked me!');  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="first">This thing</span>