1

I'm new with using JavaScript and my colleague introduced me to jQuery. Right now I'm testing how to utilize the variables I declare to create progress bars during runtime, and I can't figure out how I can create a <div> with its respective counter together with the CSS for animating the progress bar.

Please check variable counter2 as it is being treated as a string rather than its value inside.

I hope this make sense to everyone and thank you for checking this item.

function clickme2(){
        var values1 = [40,30];
        for (counter2 = 0; counter2 <= 1; counter2++) {
          var css =$(".progressbar[counter2]{height: 20px; background: #4169E1; width: 0; text-align: center; border: 1px;} ")
          $("head").append(css)
          var div =$("<br> <p id = progressnum>this is a progress bar [counter2]</p><div class = 'pp'><div class='progressbar[counter2]'> </div></div>");
          $("body").append(div);
            $('.progressbar').animate(
              {
                width: values1[counter2] + "%"
              },
              {
                duration: 500
              }
            );

        }
      }
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  </head>
  <style type='text/css'>
  </style>
  
  <body>
    <br>
      <button id="add" onclick="clickme2()">Add</button>
    <br>
   
   <script>
    //refer to my javascript code
   </script>
   
   </body>
</html>

1 Answer 1

1

To use a variable in a string, you either have to concatenate it, or use a template literal. If you just stick it inside a string, it will be treated as a string, as that is how javascript is designed.

//concatenation
var x = 'me';
var aString = 'Please say hello to '+ x;

//template literal
var x = 'me';
var aString = `Please say hello to ${x}`;
Sign up to request clarification or add additional context in comments.

3 Comments

Hello, thank you for replying to my query, I tried it on my end but it didn't work the way I imagine it.
this is the display result: "counter ${x}"
@Marcus Take note that that version does not use single or double quotes. It uses the accent mark. You must use the accent mark for template literals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.