PaulVO PaulVO - 1 month ago 5
Javascript Question

Changing CSS with javascript using getElementById

I have an element as such:

<div id="admin">


Which has style of:

display: none;


Now, I'm trying to change that display on button press by defining and calling

var admin = document.getElementById('admin');
admin.style.display = "block";


This works just fine. When I change
admin
in both HTML and JS to something like
admin-panel
(like below), it breaks and throws me an error
admin is not defined(…)
.

<div id="admin-panel">
var admin = document.getElementById('admin-panel');
admin.style.display = "block";


Could anyone help me figure out why it works in the first instance but not the second?

EDIT

It seems to be working when place
var admin = document.getElementById('admin-panel');
inside the
show
and
hide
functions. Is this because the variable is not within their scope in the code below?

var adminView = {
init : function() {
var admin = document.getElementById('admin-panel');
this.adminBtn = document.getElementById('admin-toggle');
this.adminCancel = document.getElementById('admin-cancel');
this.adminSave = document.getElementById('admin-save');

this.adminCatName = document.getElementById('admin-cat-name');
this.adminCatUrl = document.getElementById('admin-cat-url');
this.adminCatClicks = document.getElementById('admin-cat-clicks');

this.adminBtn.addEventListener('click', function(){
catController.adminDisplay();
});

this.render();
},

render: function() {
var currentCat = catController.getCurrentCat();
this.adminCatName.value = currentCat.name;
this.adminCatClicks.value = currentCat.clickCount;
this.adminCatUrl.value = currentCat.img;
},

show: function() {
admin.style.display = "block";
},

hide: function() {
admin.style.display = "none";
}

};

Answer

Remove var from admin variable to make it global access .

Comments