Jakub Moz
Jakub Moz

Reputation: 137

Can I add class to dynamically created two.js element?

I am using the code showed below to create 46 small circles within a wrapper (div) draw-shapes;

let elem = document.getElementById('draw-shapes');
let params = { width: 1024, height: 768 };
let two = new Two(params).appendTo(elem);

for (let i = 1; i < 47; i++) {
  circle = two.makeCircle(x, y, radius);
  circle.fill = 'green';
  circle.stroke = 'white';
  circle.linewidth = 1;
  circle.id = i;
}

All drawings are made with the Two.js library. I read in the documentation I can change the id of the created element, but I also need to assign a class to each element. I have tried everything from pure js setAttribute to jQuery .attr and .addClass methods, but none of them worked, so I started to wonder if this is even possible to do? If someone knows a way, please let me know how. Thank.

Upvotes: 5

Views: 471

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

There is not internal utility or property to get to the DOM node of each Two element.

But the id you specify is indeed added as two-<specified-id> to the actual node.

So you can use the normal document.getElementById.

So in your case

let elem = document.getElementById('draw-shapes');
let params = {
  width: 300,
  height: 300
};
let two = new Two(params).appendTo(elem);

for (let i = 1; i < 20; i++) {
  const circle = two.makeCircle(i * 10, i * 10, 40);
  circle.fill = 'green';
  circle.stroke = 'white';
  circle.linewidth = 1;
  circle.id = `two-circle-${i}`;
}
two.update();

// add classname to every fifth element;
for (let i = 1; i < 20; i += 5) {
  const circleNode = document.getElementById(`two-circle-${i}`);
  circleNode.classList.add('classname');

  circleNode.addEventListener('mouseover', function() {
    const path = two.scene.getById(this.id)
    path.scale = 1.2;
    two.update();
  });

  circleNode.addEventListener('mouseout', function() {
    const path = two.scene.getById(this.id)
    path.scale = 1;
    two.update();
  });
}
.classname {
  stroke-width: 5;
  stroke: red;
  fill:yellow;
  cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.6.0/two.js"></script>

<div id="draw-shapes"></div>

Upvotes: 2

Related Questions