Skip to content
Advertisement

.blur() sound notifications

I have two text boxes whose values are ‘yes’ and ‘no’. When I type ‘yes’ in the first text box, it beeps and the same should happen with the remaining text box. The sound should play only once when I enter the correct value in the corresponding text boxes.

In my case, the sound is repeating again and again… I don’t know what might be the cause.

<input type="text" id="question"/>
<input type="text" id="question1"/> 
<audio src="beep.mp3" id="mp3" preload="auto"></audio>

function checkResults() {

    if ($('#question').val().toLowerCase() == 'yes') {
            document.getElementById("mp3").play();

    }

    if ($('#question1').val().toLowerCase() == 'no') {
        document.getElementById("mp3").play();
    }


}

$('input').blur(checkResults);

Advertisement

Answer

The sound is playing more than once because you’re checking the blur event, so every time the user blurs out of the box the sound will replay as long as the correct answer in in the box. Instead you should check for keyup event.

Example:

var answers = {
    'question': 'yes',
    'question1': 'no'
};

function checkResults() {
    var $this = $(this), val = $this.val().toLowerCase();

    for (var k in answers) {
        if (answers.hasOwnProperty(k)) {
            if (answers[$this.attr('id')] && answers[$this.attr('id')] === val) {
                  play(); 
            }
        }
    }   
}

function play() {
    var sound = document.getElementById('mp3');
    sound.pause();
    sound.currentTime = 0;
    sound.play();
}

$('input').on('keyup', checkResults);

JSFiddle demo

http://jsfiddle.net/7ahpgt5s/

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement