Ask Your Question
1

How can I make only the most recently added element within a DIV respond to an onClick event while rotating around the center?

asked 2023-05-29 06:58:07 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-29 07:18:02 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-29 06:58:07 +0000

Seen: 9 times

Last updated: May 29 '23