Question

as the title says, why doesnt this code work on my local html file, despite it works on jsFiddle. this is my code:

JS

    var s,t,d; 
s = document.getElementById('start');
t = document.getElementById('temp');
d = document.getElementById('display');

startChange = function(){
  var v,nt,diff,timelapse,decrease,decreaseit,loop;
  v = +d.value;
  nt = +t.value; 
  diff = v-nt;
  timelapse = 500; //set to whatever you like
  decrease = .2;
  decreaseit = function(){
    var v = d.value;      
    if(v>=(nt+decrease)){
     loop = setTimeout(function(){    
      d.value = (v-decrease).toFixed(1);
      decreaseit();
     },timelapse)   
    } else clearInterval(loop);
  }
  decreaseit();

}

s.onclick = startChange;

HTML

  <input id="display" type="text" value="7.2" disabled>

<input id="temp" type="text">
    <button type="button" id="start">Set temp</button>    
Was it helpful?

Solution

You probably have put your code in the <head></head> section of your file and your JavaScript code can't access the DOM elements since the DOM hasn't been created yet.

If your code is in the head, wrap it with:

window.onload = function() {
 // your code
}

Otherwise put it right before the closing body tag. This is the recommended way of including JavaScript since the essential content gets loaded first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top