6

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: #price-panel > div > span > span

Attempt 1: fail

$("#price-panel div span span").onchange = function() { console.log('change')}

Attempt 2: fail

document.getElementById('price-panel').children[0].children[0].onchange = function() { console.log('change')}

builtwith.com says the javascript is the "google api" which is ambiguous to google searches so that didn't help much.

What event can I watch to find out when this element is change?

implmentor
  • 1,386
  • 4
  • 21
  • 32
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
  • 1
    `span` elements don't have an `onchange` event... You could use an interval and compare every minute. – tymeJV Aug 17 '15 at 15:26
  • 2
    Not sure if you're looking for something like [Detect changes in the DOM](http://stackoverflow.com/questions/3219758/detect-changes-in-the-dom). – fuyushimoya Aug 17 '15 at 15:28

2 Answers2

8

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 = new MutationObserver(function(records) {
  console.log(records);
});
mutateObserver.observe(span, {
  childList: true,                                 // capture child add/remove on target element.
  characterData: true,                     // capture text changes on target element
  subtree: true,                                   // capture childs changes too
  characterDataOldValue: true  // keep of prev value
});

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

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

setTimeout(function() {
  text.data = '3123';
}, 4000);
<span id="test">This is a span</span>
fuyushimoya
  • 9,715
  • 3
  • 27
  • 34
4

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 happened
        console.log("Change");
        content = currentText;
    }
}, 30000 /* check every 30 seconds */);
James Donnelly
  • 126,410
  • 34
  • 208
  • 218