Here is the setup I am working with:
<div id="admin">
This element has the following style applied to it:
display: none;
I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript code:
var admin = document.getElementById('admin');
admin.style.display = "block";
Initially, this solution works correctly. However, when I modify admin
to admin-panel
, as shown below, it stops working and throws an error stating admin is not defined(…)
.
<div id="admin-panel">
var admin = document.getElementById('admin-panel');
admin.style.display = "block";
If anyone could assist me in understanding why it functions in the first scenario but fails in the second, I would greatly appreciate it.
UPDATE
It appears that moving
var admin = document.getElementById('admin-panel');
inside the show
and hide
functions resolves the issue. Could this be due to variable scoping challenges as seen in the revised code snippet 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";
}
};