Umer Javed
Umer Javed

Reputation: 404

JQuery on change not working on div

https://jsfiddle.net/qmLpakuq/

Here is my HTML:

<div class="info-price" id='newrange'></div>

and here's my JQuery:

$( document).on( "change", ".info-price" ,function() {
    console.log("umerjaved");
});

Upvotes: 1

Views: 60

Answers (2)

Andy
Andy

Reputation: 5091

As mentioned in the comments, the onchange event isn't fired for div elements. The DOMSubtreeModified event is now deprecated, and using a timer seems a little bit hacky.

The correct way to do this is by using a MutationObserver:

var targetNode = document.getElementById('my-div');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if(mutation.type === 'characterData') {
    	document.write('targetNode changed:<br />');
    	document.write('Was: ' + mutation.oldValue + '<br />');
        document.write('Now: ' + targetNode.innerHTML);
    }
  });
});

observer.observe(targetNode, {
  characterData: true,
  characterDataOldValue: true,
  subtree: true
});

// Make a change one second after the page is loaded to trigger the observer.
setTimeout(function() {
  targetNode.innerHTML = 'New Value';
}, 1000);
<div id="my-div">Initial Value</div>

If you need to support IE versions older than 11 then you'll need to use a polyfill: https://github.com/megawac/MutationObserver.js https://github.com/webcomponents/webcomponentsjs

Upvotes: 1

Charlie
Charlie

Reputation: 100

you could use setInterval and clearInterval methods. Set interval would be active only when neccessary, like this:

var infoPrice = $('.info-price').html();
var infoPrice_changeFirers = $('.square').add('.infobox').add('#pr-slider');
var my_interval = null;

$(infoPrice_changeFirers).on('mousedown', function(){
    my_interval = check_infoPrice();
});

$(infoPrice_changeFirers).on('mouseup', function() {
    clearInterval(my_interval)
});

function check_infoPrice(){
  my_interval = setInterval(function(){ 
  var current_infoPrice = parseInt($('.info-price').html());
   if(parseInt(infoPrice) != current_infoPrice){
     on_infoPrice_change();
     infoPrice = $('.info-price').html();
   } 
  }, 50);
  return my_interval;
}

function on_infoPrice_change(){ // place your code here
  alert('hello');
}

Upvotes: 1

Related Questions