Reputation: 1131
I have a div <div id="Country">India</div>
. I want to execute some code (say JavaScript function) whenever the div value changes. How can I listen to changes on the div value? Do i need to use Jquery for this?
Upvotes: 3
Views: 5354
Reputation: 96
Try this within script tag:
$(document).ready(function(){
var new_country1 = "";
var new_country2 = "";
var func_flag = 0;
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
new_country1 = this.innerHTML;
if(new_country1 != new_country2 && func_flag == 1) {
country_changed_function();
}
} else {
new_country2 = this.innerHTML;
}
func_flag = 1;
});
});
function country_changed_function(){
alert('country changed.');
}
Here "country_changed_function" is function trigger on country div innerHTML got changed.
Upvotes: 0
Reputation: 993
I have prepared a small demo for you. Its a little crude but I am sure You can improve it ;).
Happy Coding :)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#ChangeText").click(function(){
var value = $("#DivText").val();
$("#Country").text(value);
});
$('#Country').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '\n\n' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '\n\n' + this.innerHTML);
}
});
});
</script>
</head>
<body >
<input type="text" id="DivText" />
<button id="ChangeText"> Change Div Text </button> <br /> <br />
<div id="Country">India</div>
</body>
</html>
Upvotes: 2
Reputation: 4430
an easy jquery solution is to use a custom event and trigger it yourself when you change the DOM:
$("#country").html('Germany').trigger('CountryChanged');
$('#country').on('CountryChanged', function(event, data) {
//contentchanged
});
Upvotes: 4
Reputation: 308
Try this Demo, It's in Cracker0dks's link http://jsbin.com/ayiku and this is the code http://jsbin.com/ayiku/1/edit
Upvotes: 0
Reputation: 10167
You can listen to events triggered by the MutationObserver DOM API : https://developer.mozilla.org/en/docs/Web/API/MutationObserver
Upvotes: 0