Error: Type Error - 'style' is not defined in the Progress Bar Project

Having recently started learning Javascript, I have been engaging with various tutorials and projects in order to gain familiarity with the language. One particular tutorial that caught my attention is a Progress-Bar tutorial by "dcode" available at this link: https://www.youtube.com/watch?v=QxQRtwAtqKE. I've been following along with it, but unfortunately, I encountered an error in my JavaScript code that the instructor did not face.

The issue seems to be revolving around the style method within the update function in the JavaScript section. I attempted to relocate the update function's position (even placing it above setValue() at one point) in case it wasn't being read correctly in its current placement. However, this adjustment didn't resolve the error. Since I meticulously followed the tutorial step-by-step, I'm puzzled as to where I might be going wrong. Could there be something crucial that I missed?

Below is the provided code with some minor modifications made by me: Javascript code:

// JavaScript source code

//creating a class for the progess bar (HP bar)
class ProgressBar {
    constructor(element, initialValue = 0) { 
        this.valueElem = element.querySelector('.HP-value');
        this.fillElem = element.querySelector('.HP-bar-fill');

        this.setValue(initialValue);
        
    }
    
    setValue(newValue) {
        if (newValue < 0) {
            newValue = 0;
        }

        if (newValue > 100) {
            newValue = 100;
        }

        this.value = newValue;
        this.update();
    }

    update() {
        const percentage = this.value + '%';

        this.fillElem.style.width = percentage;  
        this.valueElem.textContent = percentage;
        
        
    }
}


const pb1 = new ProgressBar(document.querySelector('.HP'), 80); 

body
{
}

.HP {
    position: relative;
    width: 300px;
    height: 40px;
    border: 2px solid black;
}

.HP-bar-fill {
    height: 100%;
    background: #36ed1a;
    transition: width 0.5s;
}

.HP-value {
    position: absolute; 
    width: 100%;
    height: 100%;

    display: flex;
    align-items: center;
    justify-content: center;

    font-weight: bold;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>HealthBar</title>
</head>
<body>
    <h1>Your HP</h1>
    <div class="HP">
        <div class="HP-value">50%</div>
        <div class="HP-bar-fill"></div>

    </div>


    <script src="js/script.js"></script>
</body>
</html>

Answer №1

There seems to be a typo in your JavaScript code where you have misspelled 'constructor' as 'contructor'. Due to this mistake, the constructor function is not being called properly, causing an error when trying to set the width of 'fillElem'. To resolve this issue, make sure to correct the spelling of 'constructor' in your JS code:

//creating a class for the progress bar (HP bar)
class ProgressBar {
    constructor(element, initialValue = 0) { 
      console.log('constructor called');
        this.valueElem = element.querySelector('.HP-value');
        this.fillElem = element.querySelector('.HP-bar-fill');
        
        this.setValue(initialValue);

        //console.log(this.valueElem);
       
    }

    setValue(newValue) {
        if (newValue < 0) {
            newValue = 0;
        }

        if (newValue > 100) {
            newValue = 100;
        }

        this.value = newValue;
        this.update();
    }

    update() {
        const percentage = this.value + '%'; // 50%
        this.fillElem.style.width = percentage;  //Error displays for me here but not the instructor.
        this.valueElem.textContent = percentage;
        
        
    }
}


const pb1 = new ProgressBar(document.querySelector('.HP'), 80); 
//calls the value from user to display the new percentage. 
//In this case it should go from 50% to 80%.

For further reference, check out the fiddle link: https://jsfiddle.net/0b7cs35x/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

What is the most effective way to determine if a statement is either false or undefined?

What is the most effective way to determine if a statement is not true or undefined, sometimes without necessarily being a boolean? I am attempting to improve this code. var result = 'sometimes the result is undefined'; if (result === false || ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

Error in Bootstrap table implementation leading to truncation of tbody height due to data-detail-view property

I'm currently working on integrating Bootstrap-Table's detailView feature into my project. However, when I enable data-detail-view="true" for my table, the height of the table element shrinks to 0. Strangely, clicking on any column with ...

Prevent the sender from receiving notifications from Firestore

Data is transmitted to firestore by the sender firestore saves the data firestore shares the data with all connected clients, sender included Is there a method for the sender to not receive the notification? OR If the sender does get the notification, is ...

The left margin is malfunctioning

As a newcomer to css, I am struggling with adding margin-left to my paragraph and <h2>, and it's not taking effect. I have a 700px div and I want to add a 10px margin-left to both <p> and <h2> in relation to the image. Despite my e ...

The pre-save function in Mongoose does not seem to be working properly when using discrimin

I am facing an issue where the pre save hook is not being called before saving the owner in mongoose. Is there a workaround for this problem? const baseOptions = { discriminatorKey: '__type', collection: 'users' } const Base = ...

Issue with importing styles within a media query

I am having trouble importing a style that is based on a media query. When I try to import the styles, it doesn't seem to work. However, if I directly include the styles within the media query itself, they show up on the page. For reference, you can ...

Extract the <img> element from the Angular model property

I'm currently leveraging Angular to display some HTML content: <p class="description" ng-model="listing.Description"></p> When the content is rendered, it includes images within the text, which is acceptable. However, now I aim to ident ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...

JavaScript counter that keeps updating without pause

How can I create a live and continuous number counter on my website? After seeing the question above, I am interested in implementing a similar feature but with a slight twist. I am looking to have a counter that increments by 15.8 cents per second start ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...

Unusual spacing problem detected on iPad device

When I visit my demo site on my iPad, I'm having a strange issue where the player seems to be shifted to the top. This is how it looks on my iPad Mini running iOS 6.1 and tested on both Chrome and Safari: Here is the link to the demo site (change the ...

AngularJS: The requested resource does not have the "Access-Control-Allow-Origin" header

Currently developing my web application using AngularJS, I have a file named script.js which contains the following code: var module = angular.module('project', ['ngRoute']); // setting up our routes module.config(function ($r ...

The post() method in Express JS is functioning flawlessly in Firebase cloud function after deployment, however, it seems to encounter issues when running on a

https://i.stack.imgur.com/bIbOD.pngI am facing an issue with my Express JS application. Despite having both post() and get() requests, the post() request is not working on my local machine. It keeps throwing a 404 error with the message "Cannot POST / ...

Utilize a single image to encompass the entire background/theme

As a beginner, I am eager to learn how to use html and css. I understand the importance of being able to style an entire webpage in order to prevent issues like page overload or cache problems. Are there any easy-to-understand examples available for begi ...

Separating the logic of identical schemas and implementing multi-tenancy in Node.js using Mongoose

In the system I am developing, there are two key requirements: Each client needs to be completely isolated from one another Clients can have multiple subsidiaries which they should be able to switch between without needing to re-authenticate, while ensuri ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...