0

I have a span tag with id='title' and this value changes after sometime. I want to update the page title with this value when it updates.

e.g. <span id='title'>Title</span> -- This is current title

when after some time it is updated by another script to

<span id='title'>New title</span> 

I want to update the title of page to "New title" whenever it changes and no matter how many times it changes.

Right now I have to call function every 1 second to update the page title. Which keeps blinking the page title. So I want to monitor the change and whenever the value changes I want that value to be the title of page.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

This discussion seems to be looking at the same issue - just instead of a span they are monitoring a div.I know you're looking to do this with pure JavaScript but I think the thread is still good to review.
Jquery Event : Detect changes to the html/text of a div

Community
  • 1
  • 1
Sean
  • 313
  • 1
  • 17
  • but there is browser support issue with that. – Sachin Khokhar May 10 '17 at 12:46
  • Yes, that is correct. There are browser support issues with using Mutation Observer officially. It is still considered experimental in Chrome and Safari. You may use it but your results may vary. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#Browser_compatibility – Sean May 10 '17 at 16:13
0

Yes. You can achieve it by

Mutation Observer

I answered your question based on your jsfiddle link in comment I have used MutationObserver to achieve what you want.

  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || 
window.MozMutationObserver;
      var target = document.querySelector('#demo');

      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          if (mutation.type === 'childList') {
          console.log(mutation.type);
           document.getElementById('status').innerHTML='changed';
          }
        });
      });

      observer.observe(target, {
        attributes: true,
        childList: true,
        characterData: true
       });

I have forked it to this fiddle.

Hope it helps

Khaleel
  • 1,212
  • 2
  • 16
  • 34