jan777
jan777

Reputation: 39

My function is not running in JavaScript

How do I get this code to work in the "head" tag of the HTML. I must use these two functions, and cannot use only one function. I know this is bad practice, but how would I go about doing this? Thank you for your help.

var myImage;
function prepareEventHandlers() {
    var myImage = document.getElementById('mainImage');
}

function runEvents() {
    myImage.onclick = function() {
        alert('You clicked on the image.');
    };
}

window.onload = function() {
    prepareEventHandlers();
    runEvents();
}

Upvotes: -1

Views: 94

Answers (2)

Steve
Steve

Reputation: 86

Remove the "var" in your prepareEventHandlers() function.

var myImage;

function prepareEventHandlers() {
    myImage = document.getElementById('mainImage');
}

function runEvents() {
    myImage.onclick = function() {
        alert('You clicked on the image.');
     };
}  

window.onload = function() {
    prepareEventHandlers();
    runEvents();
}

Upvotes: 3

levi
levi

Reputation: 22697

You need to remove var in prepareEventHandlers(), because you are declaring a new local variable called myImage, not assigning the outer one.

    var myImage;

    function prepareEventHandlers() {
        myImage = document.getElementById('mainImage');
    }

Upvotes: 3

Related Questions