简体   繁体   中英

use change() to detect changes of attribute value

is it possible? I want to detect the width of a div for example, bind it with on() to do something..

var widthVal= $('#panel').width();

$(widthVal).on('change', function(){

});

then I create a button to increase the width of the #panel, but nothing happen..

use change() to detect changes of attribute value ? make sense?

The simple answer would be to use mutation events .

However, they have been deprecated and are not widely supported.

I think your best bet is to use a timer to periodically check if the CSS attribute has changed;

var $panel = $('#panel');
var width = $panel.width();

$panel.on('resized', function () {
  // do something!
});

setInterval(function () {
  if ($panel.width() !== width) $panel.trigger('resized');
}, 50);

I'll suggest to use the following approach http://jsfiddle.net/krasimir/5PXnv/

HTML

<div>test</div>

JS

var changeWidth = function(el, width) {
    el.css("width", width + "px");
    el.trigger("width-changed");
}
var div = $("div");
div.on("width-changed", function() {
    console.log("changed");
});
setTimeout(function() {
    changeWidth(div, 200);
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM