0

I'm setting a variable equal to an image and then calling it in a function. This does not work because according to the javascript error console it doesn't recognize the image variable as anything but null

var image = document.getElementById("gc");
var duration = 3000; /* fade duration in millisecond */
var hidtime = 2000; /* time to stay hidden */
var showtime = 2000; /* time to stay visible */
var image_tracker = 1

function change() {
    if (image_tracker == 1) {
        image.src = "IMG_1267.jpg"
        image_tracker = 2
    } else if (image_tracker == 2) {
        image.src = "IMG_1239.jpg"
        image_tracker = 3
    } else {
        image.src = "IMG_1263.jpg"
        image_tracker = 1
    }
}

However this works fine

var duration = 3000; /* fade duration in millisecond */
var hidtime = 2000; /* time to stay hidden */
var showtime = 2000; /* time to stay visible */
var image_tracker = 1

function change() {

    var image = document.getElementById("gc");

    if (image_tracker == 1) {

        image.src = "IMG_1267.jpg"
        image_tracker = 2
    } else if (image_tracker == 2) {
        image.src = "IMG_1239.jpg"
        image_tracker = 3
    } else {

        image.src = "IMG_1263.jpg"
        image_tracker = 1
    }

}

var timer = setInterval('change()', 3000);
Colin Brock
  • 21,267
  • 9
  • 46
  • 61
apdm
  • 1,260
  • 1
  • 14
  • 33
  • 6
    It could be that the HTML element with ID `gc` does not exist when you initially set `image`. Are you waiting for the page to render before you execute the JS code? – TheDude Jul 06 '15 at 20:42
  • what about the others global variales like 'image_tracker' theay are recognized? – lem2802 Jul 06 '15 at 20:43
  • It could *only* be that the element with that `id` doesn't yet exist, given that the result of the `getElementById()` is `null`. – David Thomas Jul 06 '15 at 20:43

1 Answers1

6

In your code, your JavaScript loads immediately, even before the DOM is completely loaded. When it tries to search for #gc, it can't find it because it isn't loaded into the DOM.

The solution would be to set your image variable when the page is completely loaded. ex.

var image;

window.onload = function() {
    image = document.getElementById("gc");
}

function change() {
    ....
Patosai
  • 750
  • 1
  • 6
  • 16