79
71

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

要素の中身が変更されたことを知る

Last updated at Posted at 2014-11-21

##問題点
・JavaScriptのchangeイベントはformの要素にしか使えない
・divの中身が変更されてもイベントは発生しない

$('<div>').change(function() {
    // 発生しない
});

・付け加えるとresizeイベントもwindowオブジェクトにしか使えない

$('<div>').resize(function() {
    // 発生しない
});

##どうするか?

1.setIntervalで常に変化を監視する

index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var content = null;
$(document).ready(function() {
	$('#click_me').click(function() {
		$('#sample').text('Change!');
	});
	var a = function() {
		if (content != $('#sample').text()) {
			if (content != null) {
				alert('Change!');
			}
			content = $('#sample').text();
		}
	};
	setInterval(a, 300);
});
</script>
</head>
<body>
<input type="button" id="click_me" value="Click!">
<div id="sample"></div>
</body>
</html>

2.DOMSubtreeModified propertychangeイベントを追加する

index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var content = null;
$(document).ready(function() {
	$('#sample').on('DOMSubtreeModified propertychange', function() {
		alert('Change!');
	});
	$('#click_me').click(function() {
		$('#sample').text('Change!');
	});
});
</script>
</head>
<body>
<input type="button" id="click_me" value="Click!">
<div id="sample"></div>
</body>
</html>

動作検証
Chrome 38.0.2125.111 m:OK
Firefox 32.0.1:OK
IE 11.0.9600.17416:OK

比較的新しいブラウザなのに動かないよ、という方のコメントをお待ちしています。

79
71
2

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
79
71

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?