Skip to content
Advertisement

Appending an Element on Mousedown Into Specific Div Element Only

I am trying to add circles when the event mousedown is generated into the square-one (grey square) only. If the mouse hovers outside of the square-one, it should not insert any circles anywhere else such as square-two(green square).

Question: How can I set the limits for the circles such that they are only inserted within the square-one boundaries? Thank you for your help.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

When I use your code, the circles aren’t being put where I actually click.

That is because you’re using the mouse’s position (which is relative to the page) to detect where you will put the circles, but then you append them to the

graySquare, which doesn’t start at (0,0). If you append them to the .contaner instead, you’ll be ok.

JavaScript

Then regarding the set the limits for the circles such that they are only inserted within the square-one boundaries, you need to get the position (x and y), width and height of the squareOne and only proceed if the click occurs within those.

JavaScript

I used this to get the position of the div, and this to get its width and height (although they ended up being the same solution).

EDIT!

I kept thinking about this and there’s a more obvious, more elegant solution (to me at least). You add the event listener to the graySquare and not the whole document.

JavaScript

Then you don’t need the ugly part where you check if the mouse is within the limits.

You can even bind the same function to different squares. Check the updated snippet.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement