Search code examples
javascriptjqueryhtmlcursor

How to append a div to where a user has clicked on the page in jQuery


I am having trouble appending a div to anywhere a user has clicked on the page

For example

If a user clicks on the side of the page it should append a div on the exact spot they clicked and if they clicked in the middle of the page it should append a div to the exact spot they clicked and so on and so forth

Here's the code I have so far

$('body').click(function(e){
        console.log("X: " + e.pageX + " Y: " + e.pageY);
});

this is for getting the x, y cords for where the user has clicked

Any help would be much appreciated

Thanks,

Arnav 😀


Solution

  • In order to listen to click event first add the listener to document. On click, create new element and set the left and top property with values of x and y co-ordinates.

    document.addEventListener('click', function(e) {
        const div = document.createElement('div');
        div.innerHTML= `<span>New Content</span>`;
        div.style.position = "absolute";
        div.style.left = e.x + 'px';
        div.style.top = e.y + 'px';
        document.body.appendChild(div);
    });