syzd
syzd

Reputation: 163

How to define several "id"s in one javascript code?

The following script written for a progress bar, is assigned to a div with id=container1. This is while I have several divs with ids like container2, container3 and ... which all should be referred to this script.

How can I assign this script to all divs?

var bar = new ProgressBar.Line(container1, {
  strokeWidth: 4,
  easing: 'easeInOut',
  duration: 1400,
  color: '#66cc33',
  trailColor: 'transparent',
  trailWidth: 1,
  svgStyle: {
    width: '100%',
    height: '100%',
    position: 'absolute'
  }
});

bar.animate(1.0); // Number from 0.0 to 1.0

Upvotes: 0

Views: 72

Answers (3)

Zmen Hu
Zmen Hu

Reputation: 805

It depends on the API of ProgressBar. You have to read the API document or the definition of ProgressBar.Line to figure out if new ProgressBar.Line(option) could return the same instance each time.

Upvotes: 0

Benjamin Pajk
Benjamin Pajk

Reputation: 101

If I understand your question correctly you want several progressBar instances referenced to the same options object.

var progressBarOptions={
  strokeWidth: 4,
  easing: 'easeInOut',
  duration: 1400,
  color: '#66cc33',
  trailColor: 'transparent',
  trailWidth: 1,
  svgStyle: {
    width: '100%',
    height: '100%',
    position: 'absolute'
  }
}

var bar1 = new ProgressBar.Line(container1, progressBarOptions);
var bar2 = new ProgressBar.Line(container2, progressBarOptions);
var bar3 = new ProgressBar.Line(container3, progressBarOptions);

Upvotes: 1

Bálint
Bálint

Reputation: 4039

If you don't use closures, then each of these containers are accessible from the window object and you can use array access to get the objects:

var containerCount = 5;
for (var i = 1; i <= containerCount; i++) {
    var bar = new ProgressBar.Line(window["container" + i, {
        // Stuff here
    }
}

If you do use closures then you need to put these in an object and use the same thing but replacing the window with the object's name.

Upvotes: 0

Related Questions