10

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, until the user focuses the window (tab) and blurs it again.

My current code:

var notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
if (window.innerHeight === window.outerHeight) {
  $(window).bind('DOMNodeInserted', function() {
      notif.play();
  });
}
000
  • 26,951
  • 10
  • 71
  • 101
alexia
  • 14,440
  • 8
  • 42
  • 52
  • What you have shouldn't work, your object call to `.bind()` isn't complete...isn't that throwing a syntax error? – Nick Craver Nov 24 '10 at 12:41
  • **Update:** I fixed the sound path, it was wrong. Please update your answers. I'll check both answers again later. – alexia Nov 24 '10 at 14:02

2 Answers2

4

Use a variable to represent whether the sound should be played or not.

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

Edit: I've tested this working on Firefox, Safari, and Opera (except for the innerHeight check). (Chrome doesn't support playing WAV audio files, only the MP3, AAC, or Ogg Vorbis formats.)

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
  • This code seems to be fine, and **jsLint** only shows up only one error: *Problem at line 6 character 48: Expected an assignment or function call and instead saw an expression.* `shouldPlayAlertSound && notif.play();`. But even if I replace this with `if (shouldPlayAlertSound === true) { notif.play(); }`, it does not work. :/ – alexia Nov 24 '10 at 13:03
  • **Thanks!** I've made minor fixes to your new code, and now it's doing exactly what I wanted! http://jsfiddle.net/Nyuszika7H/hpRHR/ – alexia Nov 27 '10 at 12:26
0

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
  });
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155