ndemoreau
ndemoreau

Reputation: 3869

Set handler for change event on a DOM element using jQuery

I would like to run a function every time a specific DOM element is manipulated.

Example:

I manipulate the data-expertize attribute of an element having the class .milestones-chain:

$(".milestones-chain").data("expertizes","<%= @challenge.root.expertizes %>");

I would like this to trigger a function automatically.

I tried this:

$(document).on('change','.milestones-chain', function() {
    alert("trigger my function");
});

But it doesn't seem to work. What should I do?

Upvotes: 2

Views: 239

Answers (1)

user1823761
user1823761

Reputation:

Working jsFiddle Demo (with version 1.8.3)

Before jQuery 1.9, there are event handlers for working with data:

  • setData - fired whenever setting a data
  • getData - fired whenever getting a data

However there are no documents in jQuery site, and it's removed from jQuery 1.9.

$(function () {
    $('.milestones-chain').on('setData', function (e, k, v) {
        alert('[CHANGED] ' + k + ' : ' + v);
    });

    $('.milestones-chain').data('expertizes', '12345');
});

If you run this code by jQuery 1.8, you get the alert. The event fired by setting a data to the element. Btw, it won't work with jQuery 1.9 and upper.


Working jsFiddle Demo (with version 1.10.1)

You can take this feature back to new versions of jQuery.
(I take it from this question: JQuery 1.9 not triggering setData event).

(function () {
    var olddata = $.fn.data;
    $.fn.data = function (key, value) {
        olddata.call(this, arguments);
        if (value !== undefined) $(this).trigger('setData', [key, value]);
    };
})();

Just add it at the first line of your script.

Upvotes: 2

Related Questions