javascript - getelementbyid().click not working -


i making website whenever click , x equal range of numbers, plays audio, after click once when x between numbers, play if x not in range. please help. here code. way, not use jquery because not work on chrome.

    if(x<=1200&&x>=600){     var n=true;     };     if(x<=1200&&x>=600&&n==true){     document.getelementbyid('a').onclick = function(){     audio.play();     n=false;             }     }     else{n=false} 

what code adds click event listener on element, , afterwards click handler trigger regardless of x value because don't have checks inside click handler.

the solution create click listener once, , check value of x inside it. this:

document.getelementbyid('a').onclick = function(){   if(x <= 1200 && x >= 600 && n == true) {     audio.play();     n = false;       } } 

see (i've replaced audio playing div highlighting, it's same principle):

var r = document.getelementbyid('r');  var n = true;  var x = 1000;  document.getelementbyid('a').onclick = function(){    if(x <= 1200 && x >= 600 && n == true) {      r.classname = 'playing';      n = false;      printn();      settimeout(function(){        r.classname = '';      }, 2000);    }  }    function togglen(){n = !n;printn()}  function printn(){document.getelementbyid('n').textcontent = 'n set ' + n;}  function randomizex(){x = math.floor(math.random() * 1200);printx()}  function printx(){document.getelementbyid('x').textcontent = 'x equals ' + x;}
#r {display: inline-block; width: 50px; height: 50px; background: #ccc; transition: background 1s linear;}  #r.playing {background: green}
<button id="a">hit me</button><br><br>  <div id="r"></div>  <p id="x">x equals 1000</p>  <p id="n">n set true</p>  <button onclick="togglen()">toggle n</button>  <button onclick="randomizex()">randomize x</button>


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -