Skip to content

Instantly share code, notes, and snippets.

@krisclarkdev
Last active October 17, 2016 15:37
Show Gist options
  • Save krisclarkdev/570f16c015063db2742fb413c4f429b4 to your computer and use it in GitHub Desktop.
Save krisclarkdev/570f16c015063db2742fb413c4f429b4 to your computer and use it in GitHub Desktop.
Example showing how to get the X&Y from a mouse click and place a DIV at that location
var dynamicDivIDs = new Array();
function random() {
return Math.floor(Math.random() * 10000) + 1;
}
function newDivID() {
var newIDPrefix = 'dynamicDiv';
var newID = newIDPrefix + random();
for(i=0; i<dynamicDivIDs.length;i++) {
if(dynamicDivIDs[i] == newID) {
i=0;
newID = newIDPrefix + random();
}
}
dynamicDivIDs.push(newID);
return newID;
}
function createDiv(event) {
placeDiv(event.clientX, event.clientY);
}
function placeDiv(x_pos, y_pos) {
var newID = newDivID();
var d = document.createElement('div');
d.id = newID;
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
d.innerHTML = "ID = " + newID;
document.getElementsByTagName('body')[0].appendChild(d);
}
document.addEventListener("click", createDiv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment