3

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?

5

5 Answers 5

4

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1 As I would try to hook into the source, as opposed to reacting to the DOM changes. The DOM observers (old and new style) are not well-enough supported, although there are various [jQuery] plugins to try and make the support usable/consistent ..
2

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>

Comments

0

You can listen to events triggered by the MutationObserver DOM API : https://developer.mozilla.org/en/docs/Web/API/MutationObserver

Comments

0

Try this Demo, It's in Cracker0dks's link http://jsbin.com/ayiku and this is the code http://jsbin.com/ayiku/1/edit

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.