yeppe yeppe - 5 months ago 7
jQuery Question

Track changes to particular div without using onclick functionality

I am using jquery to implement some functionality that is repeated multiple place in the same jsp. I want to re-use the same jquery code again. Can anyone let me know how can I achieve that? Hope the below code snippet explain what I really want to achieve.

<div id="1" class="a">
//implement the some functionality to all the
elements that below to this class and id="1"
</div>


<div id="2" class="a">
//implement the similar functionality that is happening
int above div to all the elements that below to this class and id="2"
</div>


<div id="3" class="a">
//implement the similar functionality that is happening
int above div to all the elements that below to this class and id="2"
</div>

<script type="text/javascript">
//Re-usable code goes here that applies for class type 2 and tracks id 1,2,3 differently.
</script>


Edit

I want to use datatable at multiple places in the same html page and at each instance of the datatable used, I want to do similar customization using Jquery.

https://datatables.net/examples/

Answer

I think this is what you're after. When any element with id 1,2 or 3 is clicked, then it will execute the same function.

$(document).on('click', '#1, #2, #3', function (e) {
   console.log(e.target); // This is the element that was clicked
   alert('Clicked')
});

https://jsfiddle.net/cnLvk3o1/1/

If you want to select by class like A.Wolff has mentioned below. You can use this instead.

$(document).on('click', '.a', function (e) {
   console.log(e.target); // This is the element that was clicked
   alert('Clicked')
});
Comments