0

I am currently working on a website. What I want it to do is when you load the page a countdown starts, and after 15 seconds a button appears.

Currently it works perfectly on my test server, and on jsFiddle. However when I move it to my web server it doesn't work. I took a look in Google Chrome's Console, and I get the following error.

downloadButton.parentNode.replaceChild(newElement, downloadButton);
Uncaught TypeError: Cannot read property 'parentNode' of null

Here is the full code (See also jsFiddle http://jsfiddle.net/6zchq/)

var downloadButton = document.getElementById('download');
var counter = 15;
var newElement = document.createElement('p');
newElement.innerHTML = 'Getting your file, please wait 15 seconds.';
var id;

downloadButton.parentNode.replaceChild(newElement, downloadButton);

id = setInterval(function() {
    counter--;
    if(counter < 0) {
        newElement.parentNode.replaceChild(downloadButton, newElement);
        clearInterval(id);
    } else {
        newElement.innerHTML = "Getting your file, please wait " + counter.toString() + " seconds.";
    }
}, 1000);

I'm sure this is a simple problem, I just cannot figure out why it's not working.

Any help is appreciated!

Thanks.

Authentic
  • 35
  • 5
  • 3
    Where's the jQuery in your question? – j08691 Feb 22 '13 at 18:20
  • Well, if the code works fine on your server and in the fiddle, then the code must be correct. What do you expect us to do? How can we fix an error that we don't get? However, the error message seems to indicate that `document.getElementById('download')` returns `null`, in that case, have a look at this question: ["Why does jQuery or a DOM method such as `getElementById` not find the element?"](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – Felix Kling Feb 22 '13 at 18:22
  • If `downloadButton` is null, your JS is probably executing at the top of your script. Put it into the bodys onload function or at the bottom of the page. – sachleen Feb 22 '13 at 18:23

2 Answers2

3

try wrapping your code in a ready function.

the reason would be that the loading latency on a real webserver mean that you try to access elements that are not there yet.

Nick Andriopoulos
  • 9,260
  • 6
  • 28
  • 55
1

Presumably, the code is running when the DOM hasn't loaded fully and the download button element does not yet exist. Either run the code inside a ready/onload handler, or place the Javascript at the bottom of your page's body tag, so that it will load after the page's HTML.

antialiasis
  • 811
  • 1
  • 8
  • 19