2

I make an AJAX call to my server to read a file and get the value back as response. If the request was successful then i replace the innerHTML from my <p> element with id output with the response value. Now I try to fire an alert every time if the value has changed. I tried to add an event to my <p> element so I can detect if the variable has changed and fire my function:

<p id="output"></p>

<script>
    $("#output").change(function() {
        alert("HELLO WORLD!");
    });
</script>

There is no alert() showing up.

2

2 Answers 2

5

Changing the text/HTML value of an element doesn't raise an event. You would need to trigger one manually. For example:

// in the $.ajax success handler:
$('#output').trigger('contentchanged');

// event handler
$("#output").on('contentchanged', function() {
    alert("HELLO WORLD!");
});

You could also use a Mutation Observer for this, but note they are not supported in older browsers, such as IE10 and lower.

Sign up to request clarification or add additional context in comments.

Comments

2

according to the logic that you described, the content is only changed when ajax was successful. If so, wouldn't the cleanest solution simply be, in your ajax success, run the function that you are expecting to run on content change?

1 Comment

This would also be possible. Thanks!

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.