I am currently attempting to refactor this demonstration in an object-oriented manner, following the example found at: https://www.w3schools.com/howto/howto_js_progressbar.asp Here is my code:
document.getElementById("barButton").addEventListener("click", callMove);
function callMove(){
var bar1 = new ProgressBar();
bar1.move();
}
function ProgressBar() {
this.elem = document.getElementById("myBar"),
this.width = 1;
}
ProgressBar.prototype = {
constructor: ProgressBar,
move: function() {
this.id = setInterval(this.frame, 300);
},
frame: function() {
if(this.width >= 100) {
clearInterval(this.id);
}
else {
this.width++;
if(this.width >= 50) {
return;
}
this.elem.style.width = this.width + '%';
}
},
}
#myProgress {
width: 100%;
background-color: grey;
}
#myBar {
width: 1%;
height: 30px;
background-color: black;
}
<html>
<head>
<title>
This is a OO progress bar test.
</title>
<link rel="stylesheet" href="testOOProgressBar.css">
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
<button id="barButton">Click Me</button>
<script src="testOOProgressBar.js"></script>
</body>
</html>
However, when I click the button, the progress bar does not advance as expected; instead, I encounter
Uncaught TypeError: Cannot read property 'style' of undefined at frame
in the console. What could be the issue here? It appears that this.width
is not being passed from ProgressBar()
to its prototype.