0

I'm trying to use a variable to hold an HTML id so I don't have to keep writing getElementById over and over again. But I can't get this to work. Here's my code:

var box1 = document.getElementById('box1');

function slide4(){
    box1.style.width='10%';
}

It works if I put the variable inside the function, but that seems like bad practice as I want to access that variable in other functions and don't want to keep declaring the variable over and over again.

function slide4(){
    var box1 = document.getElementById('box1');
    box1.style.width='10%';
}

Any ideas?

3
  • You say you can't get this to work. What actually happens when you try it? Commented Dec 16, 2012 at 19:27
  • 1
    must be scoping issues. Try declaring the variable without the var keyword and see if it works Commented Dec 16, 2012 at 19:28
  • Can you post all your code? Commented Dec 16, 2012 at 19:28

3 Answers 3

1

I think you access the DOM before it has been loaded. Try this instead:

var box1;

window.onload = function() {
    box1 = document.getElementById('box1');
}

function slide4() {
    box1.style.width = '10%';
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should make sure the box1 initialization is run after the page gets loaded. So one solution would be this:

var box1 = null;
window.onload = function(){
    box1 = document.getElementById('box1');
}

Another solution is to create a function, instead of that variable, and use it whenever you want:

function BoxID(){
    return document.getElementById('box1');
}

Of course, if you use jquery library, whenever you want you can use:

$("#box1")

Comments

0

I would recomend you to pass variable as argument:

var box1 = document.getElementById('box1');

function slide4(box){
    box.style.width='10%';
}

Also you can define variable without var that will make it property of window object

box1 = document.getElementById('box1');
alert(window.box1);

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.