How do I play a sound when an element changes, like SO Chat does?

后端 未结 2 1433
不知归路
不知归路 2021-02-14 07:05

I want a sound to play when an element changes on a page. I know how to do this, but I can\'t get it to play only on the first change, and don\'t do it later, u

2条回答
  •  清酒与你
    2021-02-14 07:52

    If this is your only DOMNodeInserted handler, I'd just remove it when the work is done (making all future insertions cheaper), like this:

    notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
    if (window.innerHeight === window.outerHeight) {
      $(window).bind({
        'DOMNodeInserted': function() { 
          notif.play(); 
          $(window).unbind('DOMNodeInserted'); 
        }
      });
    }
    

    If it's not the only handler that's workable too, just make it a named function:

    notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
    if (window.innerHeight === window.outerHeight) {
      function play() { notif.play(); $(window).unbind('DOMNodeInserted', play); }
      $(window).bind({
        'DOMNodeInserted': play
      });
    }
    

提交回复
热议问题