Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To make only the most recently added element respond to an onClick event while rotating around the center, you can use JavaScript to select the last child of the DIV and add an event listener to it. Here's an example:

  1. Add a DIV element with a class "container" in HTML.
<div class="container"></div>
  1. In JavaScript, select the container element and add a new child element to it whenever you want to add a new item.
const container = document.querySelector(".container");
const newItem = document.createElement("div");
container.appendChild(newItem);
  1. Select the last child element of the container and add an onClick event listener to it using addEventListener() method.
const lastItem = container.lastChild;
lastItem.addEventListener("click", onClickHandler);
  1. Define the onClickHandler() function to rotate the element around the center.
function onClickHandler() {
  // Rotate the clicked element around the center
  // ...
}
  1. You can use CSS to transform the element and rotate it around the center using the transform property.
.container div {
  transform: translate(-50%, -50%) rotate(0deg);
  position: absolute;
  left: 50%;
  top: 50%;
}
  1. In the onClickHandler() function, you can update the rotation angle of the clicked element and apply the new transformation to it.
function onClickHandler() {
  // Get the current rotation angle of the element
  const currentRotation = parseInt(this.style.transform.split("(")[1]);

  // Update the rotation angle by 45 degrees
  const newRotation = currentRotation + 45;

  // Apply the new transformation to the element
  this.style.transform = `translate(-50%, -50%) rotate(${newRotation}deg)`;
}

This way, only the most recently added element will respond to the onClick event, and it will rotate around the center when clicked.