16

Is there any event in jQuery or JavaScript that triggered when span tag text/html has been changed ?

Code:

<span class="user-location"> </span>

$('.user-location').change(function () {
    //Not working
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Govind Samrow
  • 9,981
  • 13
  • 53
  • 90
  • What do you mean with "change"? When the innerHtml changes? – Jonas Wilms Aug 30 '16 at 07:55
  • `span` is not input element ,so there will be nothing changed until you have changed ! S – Jack jdeoel Aug 30 '16 at 08:07
  • 1
    I just want to event when on span text has been changed ? – Govind Samrow Aug 30 '16 at 09:09
  • @GovindSamrow does my answer not solve your problem? It's done only with Javascript, no special libraries. Or do you need a better solution? – winner_joiner Aug 30 '16 at 10:34
  • Its working but I'm waiting for something very simple. – Govind Samrow Aug 30 '16 at 10:37
  • @GovindSamrow I added a jQuery example, it is even shorter (if you dont count the _simulate Change Code_). – winner_joiner Aug 30 '16 at 11:42
  • @GovindSamrow I would like to improve my future answers, thats' why I would like ask some questions, why didn't you accept my answer which had the solution posted 6 hours before the one you finally accepted? To much text? should the Updates be at the begin of the answer? or should the Updates be better highlighted? – winner_joiner Aug 31 '16 at 06:22
  • Sorry about that but answer two much lengthy and It will confuse future coming users. Its not about points. – Govind Samrow Aug 31 '16 at 06:44
  • @GovindSamrow thanks for the feedback, I will try to keep my future answer precise and concise. _(My question had nothing to do with the points, I just want to improve my answering skills)_ – winner_joiner Sep 01 '16 at 06:07

6 Answers6

37

you can use DOMSubtreeModified to track changes on your span element i.e(if text of your span element changes dynamically ).

$('.user-location').on('DOMSubtreeModified',function(){
  alert('changed')
})

check out the followinf link https://jsbin.com/volilewiwi/edit?html,js,output

Mohit Arora
  • 460
  • 3
  • 9
13

The short answer is for jQuery with the change-Event is, NO,

This event is limited to input elements, textarea boxes and select elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus. ... here is a link to the documentation https://api.jquery.com/change/

But with something like the MutationsObserver here the link to the MDN Reference https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver , you could watch for changes in the DOM. In your specific case the span in question.

Here an brief example (adapted from the MDN Reference)
In the Example the span change is simulated with a setTimeout

  // select the target node
var target = document.getElementById('user-location');
 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.info("EVENT TRIGGERT " + mutation.target.id);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);

// simulate the Change of the text value of span
function simulateChange(){
    target.innerText = "CHANGE";
}

setTimeout(simulateChange, 2000);
<span id="user-location"></span>

If you want / have to use jQuery you could do this:
in this example I added a second span just to show how it could work

// Bind to the DOMSubtreeModified Event
$('.user-location').bind('DOMSubtreeModified', function(e) {
  console.info("EVENT TRIGGERT " + e.target.id);
});

// simulating the Change of the text value of span
function simulateChange(){
   $('.user-location').each(function(idx, element){
      element.innerText = "CHANGED " + idx;
   });
 }

setTimeout(simulateChange, 1000);
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="firstSpan" class="user-location">Unchanged 0</span><br/>
<span id="secondSpan" class="user-location">Unchanged 1</span>
winner_joiner
  • 12,173
  • 4
  • 36
  • 61
6

Using Javascript MutationObserver

  //More Details https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
 // select the target node
var target = document.querySelector('.user-location')
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  console.log($('.user-location').text());   
});
// configuration of the observer:
var config = { childList: true};
// pass in the target node, as well as the observer options
observer.observe(target, config);
PPB
  • 2,937
  • 3
  • 17
  • 12
3

You can use input event :

Like this :

$(document).ready(function(){

    $(".user-location").on("input",function(){

        console.log("You change Span tag");

    })
})

Example :

<!DOCTYPE html>
<html>
    <head>
        <style>
            span {
                border: 1px solid #000;
                width: 200px;
                height: 20px;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <span class="user-location" contenteditable="true"> </span>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){

        $(".user-location").on("input",function(){

            console.log("You change Span tag");

        })
    })
    </script>
    </body>  
</html>
        
Ehsan
  • 12,655
  • 3
  • 25
  • 44
1

Use Mutation API MutationObserver

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
Matheus Toniolli
  • 438
  • 1
  • 7
  • 16
-3

You can use javascript for that.

<html>
  <body>
    <span class="user-location" onchange="myFunction()">
       <input type="text"> 
    </span>
    <script>
       function myFunction() {
          alert("work");
       }
    </script>
 </body>
  </html>

Hope it will help.

Pirate
  • 2,886
  • 4
  • 24
  • 42
  • Well unfortunately it doesn't seem that the onchange alert happens with each onchange text insert. It only alerts when you click out of the box and change the focus to another element. I read that onchange actually doesn't work for span on another stackoverflow thread. Though I'd like to know how to make it work. – Michael d Feb 16 '17 at 04:55
  • 1
    Will not work. What you're doing is fire the event on the input tag. Block elements do not accept onChange event. – Daniel Faure Oct 29 '18 at 19:43