maiamachine
maiamachine

Reputation: 280

Accessing JavaScript variables inside a function

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?

Upvotes: 0

Views: 131

Answers (3)

Tolik Kukul
Tolik Kukul

Reputation: 2016

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

Upvotes: 0

csg
csg

Reputation: 2107

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")

Upvotes: 0

Matthias
Matthias

Reputation: 7521

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%';
}

Upvotes: 1

Related Questions