Ask Your Question
0

What is the method of generating a new div element at the cursor's location without using jQuery?

asked 2022-05-28 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-05-15 21:00:00 +0000

huitzilopochtli gravatar image

Here is an example of how to generate a new div element at the cursor's location using JavaScript without using jQuery:

  1. First, create a function that will create a new div element and append it to the body of the HTML document:
function createDiv() {
  let newDiv = document.createElement("div");
  document.body.appendChild(newDiv);
}
  1. Next, create an event listener that will capture the mouse click event:
document.addEventListener("click", function(event) {
  // Code to be executed when mouse click event occurs
});
  1. Within the event listener function, update the coordinates of the new div element by setting its left and top CSS properties based on the clientX and clientY coordinates of the mouse click event:
document.addEventListener("click", function(event) {
  let newDiv = document.createElement("div");
  document.body.appendChild(newDiv);

  newDiv.style.left = event.clientX + "px";
  newDiv.style.top = event.clientY + "px";
});
  1. Finally, call the createDiv() function when the event listener is triggered to generate the new div element:
document.addEventListener("click", function(event) {
  createDiv();

  let newDiv = document.createElement("div");
  document.body.appendChild(newDiv);

  newDiv.style.left = event.clientX + "px";
  newDiv.style.top = event.clientY + "px";
});
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: 2022-05-28 11:00:00 +0000

Seen: 13 times

Last updated: May 15 '22