-1

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();
}
2
  • What makes you think "your function is not running"? If you opened your browser's console, you would have found something like TypeError: myImage is undefined. So the function runs, but an error is thrown. Commented Aug 29, 2014 at 2:20
  • This question is similar to: What is the scope of variables in JavaScript?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 9, 2024 at 14:52

2 Answers 2

3

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');
    }
Sign up to request clarification or add additional context in comments.

Comments

3

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.