softvar
softvar

Reputation: 18435

calling function each time any change is detected `.change()`

I have many elements on my page. They are bind to change event. I think there are such 30 elements.

One such:

$("#set-angle").change(function(){
    //...do stuff
});

Now I want to call globalChangeFunc each time any such .change() is fcalled on any element. I know it is possible. I have used it in Backbone. But to detect the same in JQuery.

Small snippet of Backbone:

// Removes just the `onChange` callback.
object.off("change", onChange);

// Removes all "change" callbacks.
object.off("change");

// Removes the `onChange` callback for all events.
object.off(null, onChange);

// Removes all callbacks for `context` for all events.
object.off(null, null, context);

// Removes all callbacks on `object`.
object.off();

Something similar to this.

Upvotes: 0

Views: 145

Answers (4)

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Dont use id's(dont tell me you will assign 30 diff id's).Instead assign a common class.$(this) takes care of all your worries.

I am assuming that you have to assign a function only to the element undergoing change.

$.fn.globalChangeFunc= function(){   
        //some code   
};

$(document).on('change','.class',function(){
$(this).globalChangeFunc();
});

If its a common function,i.e not for specific element:

  function globalChangeFunc(){...}

  $(document).on('change','.class',function(){
        globalChangeFunc();
    });

Update:

Give four ids to your sliders.Detect those on click and take action by passing arguments to a common function.

$(document).on('change', '.class', function () {
switch ($(this).attr('id')) {
    case 'up':
        $(this).globalChangeFunc(appropriate params);
        break;
    case 'down':
        $(this).globalChangeFunc(appropriate params);
        break;
    case 'right':
        $(this).globalChangeFunc(appropriate params);
        break;
    case 'left':
        $(this).globalChangeFunc(appropriate params);
        break;
   }
});

Upvotes: 0

MonkeyZeus
MonkeyZeus

Reputation: 20737

Without more info, the most generic solution I can come up with is this:

$(document).on('change', 'input, select, textarea', function(){
    globalChangeFunc();
});

Upvotes: 1

Try

$("#set-angle").change(globalChangeFunc);


assign a class to all elements you want change event.

$(".change_me").change(globalChangeFunc);

Upvotes: 1

karaxuna
karaxuna

Reputation: 26940

You can assign css class to all that elements (#set-angle element will also have .x class) like:

$(".x").change(function(){
    globalChangeFunc();
    //...do stuff
});

Upvotes: 0

Related Questions