You could try using a different method of placing that listener do run only after the DOM’s content has loaded.
document.addEventListener("DOMContentLoaded", function(event) {
function loadDefault() {
console.log("Loading default border parameters.");
borderStyle = document.getElementById("borderStyle");
borderStyle.value = defaultBorderStyle;
borderStyle.addEventListener("change",updateBorderStyle,false);
}
function updateBorderStyle(event){
console.log("Border Style: "+event.target.value);
var borderStyle = document.getElementById("borderPreview");
borderStyle.style.borderStyle = event.target.value;
}
}
I’m new to javascript and I have a problem, I’m training javascript with HTML and when the page loads, for a brief moment, an error pops with the message “no item selected”, the code is the following:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
var defaultBorderStyle = "solid";
var borderStyle;
window.addEventListener("load",loadDefault,false);
function loadDefault() {
console.log("Loading default border parameters.");
borderStyle = document.getElementById("borderStyle");
borderStyle.value = defaultBorderStyle;
borderStyle.addEventListener("change",updateBorderStyle,false);
}
function updateBorderStyle(event){
console.log("Border Style: "+event.target.value);
var borderStyle = document.getElementById("borderPreview");
borderStyle.style.borderStyle = event.target.value;
}
</script>
</head>
<body>
<div>
<label for="borderStyle">Border Style:</label>
<select id="borderStyle" style="width:175px;">
<option value="dotted">Dotted</option>
<option value="dashed">Dashed</option>
<option value="solid" selected>Solid</option>
<option value="double">Double</option>
<option value="groove">Groove</option>
<option value="ridge">Ridge</option>
<option value="inset">Inset</option>
<option value="outset">Outset</option>
<option value="none">None</option>
<option value="hidden">Hidden</option>
</select>
</div>
</div>
<div id="previewBox">
<div id="borderPreview"></div>
</div>
</body>
The error pops for just a moment, I had to record the screen to print it, and when the page finish loading it disappears:
error
Uh, that’s not an error. It’s just the console saying that it’s not attached to anything yet (“no item”) because it’s still initiating the loading of the page.