javascriptjqueryjquery-trigger

Jquery executing/triggering same code on different events


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?


Solution

  • 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);