LoginSignup
7
6

More than 5 years have passed since last update.

jQueryでaddClassされたタイミングでイベント発火したいけど無理だった

Last updated at Posted at 2015-10-15

とあるjQueryのpluginを使っていて、とあるタイミングでJavaScriptでも処理を行いたかったのですが、結果スマートな方法な無いみたいですね〜。

自分で管理しているなら以下みたくすればいい。

$('selector').addClass('tempClass');
$('selector').trigger('fire');

でも今回は自分の管理外のpluginなのでできない。
(というか汎用性無くなるからやっててほしかった><)

DOMを無理やりObserveする方法もあるのですが、ブラウザの実装状況によって左右されるので面倒。。。

もしObserveするなら以下を使う。

  • DOMSubtreeModified -> 非推奨
  • propertychange
  • MutationObserver -> 手間おおし
$('selector').on('DOMSubtreeModified propertychange', function () {
    // todo
});
// 準備
var observeSelector = function () {
    console.log('addClass');
}
var temp = new MutationObserver(observeSelector);

// セレクタをセットして監視を開始
temp.observe($('selector')[0], {
    'attributes': true,
    'characterData': true,
    'childList': true,
});

// 適当なタイミングで以下を実行
$('selector').addClass('asdf');

変更を加えると、console.log('addClass');が実行される。

というメモでした。
何も解決できてない。

7
6
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6