Jquery executing/triggering same code on different events

57 views Asked by At

I have this function onclick event of custom tag densitybtn='yes'

$("[densitybtn='yes']").on('click', function () {
    var no_of_people = 0;
    //calcdensity
    $("[calcdensity='yes']").each(function () {
        no_of_people = parseInt($(this).val()) + no_of_people;
    });
    var total_density = parseInt(carpetArea) / parseInt(no_of_people);
    $("#densityVal").html(Myval);
});

Can i extend same code by extending it to $("[calcdensity='yes']").on('blur')

$("[calcdensity='yes']").on('blur').$("[densitybtn='yes']").on('click', function () {

});

Am not sure on executing same code on different events

Let me know is this method correct? or is there any alternative way available?

3

There are 3 answers

1
Patrick Evans On BEST ANSWER

Define the function normally (not as an anonymous function) and pass the function to the event listeners

function listener() {
   var no_of_people = 0;
   //calcdensity
   $("[calcdensity='yes']").each( function() {
      no_of_people = parseInt($(this).val())+no_of_people;
   });
   var total_density = parseInt(carpetArea)/parseInt(no_of_people);
   $("#densityVal").html(Myval);
}

$("[densitybtn='yes']").on('click', listener);
$("[calcdensity='yes']").on('blur', listener);
0
Rajendrakumar Vankadari On

Nope, thats not a good practise. Instead you can write a function for the second intent and call it on blur of $("[calcdensity='yes']").

2
Antonio Dangond On

You can bind multiple events using jQuery's .on() method by space-separating the event arguments.

$("[densitybtn='yes']").on('click blur', function() {
    // actions to perform
})


You can bind events to multiple elements using jQuery's .add() method.

$("[densitybtn='yes']").add("[calcdensity='yes']").on('click blur', function() {
    // actions to perform
})