Skip to content Skip to sidebar Skip to footer

How Can I Trigger An Event When This Span Value Changes?

I'm trying to get a console log when the price of the current page's stock changes. page: https://www.google.com/finance?q=NASDAQ%3AGOOG&ei=yvbRVbHSCcKgmAGyu7CoDA Element ID: #

Solution 1:

From Dom Events as your try to listen to text changes in <span> you may be able to use DOMCharacterDataModified.

Or you can use MutationObserver to capture the changes.

var span = document.querySelector('#test');
var text = document.createTextNode('tttt');

// This may be deprecated.
span.addEventListener('DOMCharacterDataModified', function() {
    alert('span text changed to: ' + this.innerHTML);
});

// You may use MutationObserver instead.var mutateObserver = newMutationObserver(function(records) {
  console.log(records);
});
mutateObserver.observe(span, {
  childList: true,                                 // capture child add/remove on target element.characterData: true,                     // capture text changes on target elementsubtree: true,                                   // capture childs changes toocharacterDataOldValue: true// keep of prev value
});

setTimeout(function() {
  span.innerHTML ='SSSS';
}, 2000);

setTimeout(function() {
  span.appendChild(text);
}, 3000);

setTimeout(function() {
  text.data = '3123';
}, 4000);
<spanid="test">This is a span</span>

Solution 2:

span elements do not have an onchange event. One thing you can do is introduce a loop to periodically check the current content with previously held content and do something if the two are different:

var content = null,
    $element = $("#price-panel div span span");

setInterval(function() {
    var currentText = $element.text();

    if (currentText != content) {
        // A change has happenedconsole.log("Change");
        content = currentText;
    }
}, 30000/* check every 30 seconds */);

Post a Comment for "How Can I Trigger An Event When This Span Value Changes?"