Here is an example of creating a div next to the cursor position on a click:
view sample
It creates a div where I click inside the div container, but when clicked too close to the borders, a div is created outside the container. Created divs should be displayed completely inside the container, even if the cursor is too close to the border. What do I need to change or add? :)
Problem - > MyImage is Out of the Box
Goal → Red dots indicate clicks made
Note. I do not need red dots. I just put it there to show that when I click on this place, the result will be imagediv
HTML:
<div id="contain">
</div>
JavaScript:
$(function() {
$("#contain").click(function(e) {
var x = e.pageX + 'px';
var y = e.pageY + 'px';
var img = $('<img src="" alt="myimage" />');
var div = $('<div>').css({
"position": "absolute",
"left": x,
"top": y
});
div.append(img);
$(document.body).append(div);
});
});
CSS
#contain{
height:300px;
width:300px;
border: 1px solid black;
}