Dynamically added div with length = 0? - javascript

so I am trying to check if I already added the a div with the same id and if I did, I chage its color to red. But for some reason my divs have a length of 0 and the if clause is never true.
I've been doing some research and this is very often due to a float, but I don't have one. I am just positionting my divs absolutely and appending them to the body.
Please have a look, any help I will be grateful for!
Thanks.
<body>
<style>
#box {
background: url('a.gif') no-repeat;
width: 50px;
height: 30px;
position: absolute;
top:210px;
left: 0;
}
#grid {
background: url('grid.gif') no-repeat;
width: 423px;
height: 240px;
margin-left: 4px;
}
#stand {
background: black;
width: 4px;
height: 240px;
margin-left: 23px;
}
#hstand {
/*horizontal stand for the carrier*/
width: 423px;
margin-left: 27px;
height: 4px;
background: black;
}
</style>
<script>
$(function() {
$('#box').click(function(e) {
var i = 0;
while (i < 50) { //specifying the cycles for the box' movement
var hstandWidth = $("#hstand").width() + 27; //getting the current x-coordinates
//array to randomly select x-coordinates from
var items = Array(hstandWidth - (50) * 1, hstandWidth - (50) * 2, hstandWidth - (50) * 3, hstandWidth - (50) * 4, hstandWidth - (50) * 5, hstandWidth - (50) * 6, hstandWidth - (50) * 7, hstandWidth - (50) * 8);
//variable with the x-coordinates, which are randomly fetched from the array
var moveLeft = items[Math.floor(Math.random() * items.length)];
//array to randomly select y-coordinates from
var items2 = Array(30, 30 * 2, 30 * 3, 30 * 4, 30 * 5, 30 * 6, 30 * 7);
//variable with the y-coordinates, which are randomly fetched from the array
var moveTop = items2[Math.floor(Math.random() * items2.length)];
// y-achs movement
$(this).animate({
"top": "" + moveTop + "px"
}, 80);
// x-achs movement with the callback function which should add the colored div to every position the box has been
// create closure to capture moveTop and moveLeft values for later callback
// use different named variables xmoveTop and xmoveLeft to distinguish the
// closure variable from the outer for loop variable
(function(obj, xmoveTop, xmoveLeft) {
$(obj).animate({
"left": "" + xmoveLeft + "px"
}, 80, function() {
if ($("#" + xmoveLeft + xmoveTop + "").length > 0) {
$("#" + xmoveLeft + xmoveTop + "").css("background", "red");
} else {
$("<div style='position: absolute; top: " + xmoveTop + "px; left: " + xmoveLeft + "px; background: blue; width: 50px; height: 30px;' id='" + xmoveTop + xmoveLeft + "'></div>").appendTo("body");
console.log($("#" + xmoveLeft + xmoveTop + "").length);
}
});
})(this, moveTop, moveLeft);
//get the box to the initial position
$(this).animate({
"left": "0px"
}, 80);
$(this).animate({
"top": "210px"
}, 80);
//mark cycle passed
i++;
}
});
});
</script>
</head>
<body>
<div id="box"></div>
<div id="stand">
<div id="grid"></div>
</div>
<div id="hstand"></div>
</body>

You create your div with id="xmoveTop + xmoveLeft" but you search for it with id="xmoveLeft + xmoveTop".
So change this line :
if ($("#" + xmoveLeft + xmoveTop + "").length > 0) {
$("#" + xmoveLeft + xmoveTop + "").css("background", "red");
To :
if ($("#" + xmoveTop + xmoveLeft + "").length > 0) {
$("#" + xmoveTop + xmoveLeft + "").css("background", "red");

You search for
"#"+xmoveLeft + xmoveTop +""
but you create the id with
" id='"+ xmoveTop + xmoveLeft +"'"
Since they are created as strings you do not use the sum but concatenated strings..
Wrap them in parenthesis, so you get the actual sum ..
"#"+ (xmoveLeft + xmoveTop) +"" and id='"+ (xmoveTop + xmoveLeft) +"'

Related

more chaotic upward movement

I have a heart movement on my page starting from the bottom of the page. Each randomly generates the size and speed of movement.
How can I make them, instead of appearing at the bottom of the page, appear when you click on the specified place, and move not evenly, but more chaotically and disappear before reaching the end?
var love = setInterval(function() {
var r_num = Math.floor(Math.random() * 40) + 1;
var r_size = Math.floor(Math.random() * 30) + 10;
var r_left = Math.floor(Math.random() * 100) + 1;
var r_time = Math.floor(Math.random() * 5) + 5;
$('.bg_heart').append("<div class='heart' style='width:" + r_size + "px;height:" + r_size + "px;left:" + r_left + "%;background:#ff94a7;-webkit-animation:love " + r_time + "s ease;-moz-animation:love " + r_time + "s ease;-ms-animation:love " + r_time + "s ease;animation:love " + r_time + "s ease'></div>");
$('.bg_heart').append("<div class='heart' style='width:" + (r_size - 10) + "px;height:" + (r_size - 10) + "px;left:" + (r_left + r_num) + "%;background:#ff94a7;-webkit-animation:love " + (r_time + 5) + "s ease;-moz-animation:love " + (r_time + 5) + "s ease;-ms-animation:love " + (r_time + 5) + "s ease;animation:love " + (r_time + 5) + "s ease'></div>");
$('.heart').each(function() {
var top = $(this).css("top").replace(/[^-\d\.]/g, '');
var width = $(this).css("width").replace(/[^-\d\.]/g, '');
if (top <= -100 || width >= 150) {
$(this).detach();
}
});
}, 500);
html,body{
height:100%
}
.bg_heart {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden
}
.heart {
position: absolute;
top: -50%;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-m-transform: rotate(-45deg);
transform: rotate(-45deg)
}
.heart:before {
position: absolute;
top: -50%;
left: 0;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
.heart:after {
position: absolute;
top: 0;
right: -50%;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
#-webkit-keyframes love {
0%{top:110%}
}
#-moz-keyframes love {
0%{top:110%}
}
#-ms-keyframes love {
0%{top:110%}
}
#keyframes love {
0%{top:110%}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header-plugin"></div>
<div class="bg_heart"></div>
To fly more chaotically use setInterval. You can also change the speed to whatever you need.
var brd = document.createElement("DIV");
document.body.insertBefore(brd, document.getElementById("board"));
const duration = 3000;
const speed = 0.5;
const cursorXOffset = 0;
const cursorYOffset = -5;
var hearts = [];
function generateHeart(x, y, xBound, xStart, scale)
{
var heart = document.createElement("DIV");
heart.setAttribute('class', 'heart');
brd.appendChild(heart);
heart.time = duration;
heart.x = x;
heart.y = y;
heart.bound = xBound;
heart.direction = xStart;
heart.style.left = heart.x + "px";
heart.style.top = heart.y + "px";
heart.scale = scale;
heart.style.transform = "scale(" + scale + "," + scale + ")";
if(hearts == null)
hearts = [];
hearts.push(heart);
return heart;
}
var down = false;
var event = null;
document.onmousedown = function(e) {
down = true;
event = e;
}
document.onmouseup = function(e) {
down = false;
}
document.onmousemove = function(e) {
event = e;
}
document.ontouchstart = function(e) {
down = true;
event = e.touches[0];
}
document.ontouchend = function(e) {
down = false;
}
document.ontouchmove = function(e) {
event = e.touches[0];
}
var before = Date.now();
var id = setInterval(frame, 5);
var gr = setInterval(check, 100);
function frame()
{
var current = Date.now();
var deltaTime = current - before;
before = current;
for(i in hearts)
{
var heart = hearts[i];
heart.time -= deltaTime;
if(heart.time > 0)
{
heart.y -= speed;
heart.style.top = heart.y + "px";
heart.style.left = heart.x + heart.direction * heart.bound * Math.sin(heart.y * heart.scale / 30) / heart.y * 100 + "px";
}
else
{
heart.parentNode.removeChild(heart);
hearts.splice(i, 1);
}
}
}
function check()
{
if(down)
{
var start = 1 - Math.round(Math.random()) * 2;
var scale = Math.random() * Math.random() * 0.8 + 0.2;
var bound = 30 + Math.random() * 20;
generateHeart(event.pageX - brd.offsetLeft + cursorXOffset, event.pageY - brd.offsetTop + cursorYOffset, bound, start, scale);
}
}
html,body{
height:100%
}
#keyframes heartfade {
0% {
opacity : 1;
}
50% {
opacity : 0;
}
}
.heart {
z-index : 999;
animation : heartfade 6s linear;
position : absolute;
}
.heart:before,
.heart:after {
content : "";
background-color : #ff94a7;
position : absolute;
height : 30px;
width : 45px;
border-radius : 15px 0px 0px 15px;
}
.heart:before {
transform : rotate(45deg);
}
.heart:after {
left : 10.5px;
transform : rotate(135deg);
}

How to prevent element from exceeding his container borders

I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).
sometimes the square exceed his container border
How can I make sure that the square will never exceed his container?
function position() {
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin: 0;
padding-top: 30px;
}
#playSpace {
width: 90%;
height: 90%;
margin: 0 auto;
margin-top: 10px;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
You need to set position: relative; to the parent element and position: absolute; to the shape element. Then use max min value for random where max is the parent width/height and subtract the shape width/height ...
This is snippet before update
function position() {
var playSpace = document.querySelector('#playSpace');
var shape = document.getElementById("shape");
var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
var maxWidth = playSpace.offsetWidth - shape.offsetWidth;
var positionTop = Math.random() * (maxHeight - 0) + 0;
var positionLeft = Math.random() * (maxWidth - 0) + 0;
// think of this like so:
// var positionTop = Math.random() * (max - min) + min;
// more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}
#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
Updated after comment
Not sure how you added the size() function but probably the problem was with using ...cssText that you overwrote the changes. So now I changed the code with passing the element to the functions and then only change the single CSS statements which need to be changed.
function position(element) {
var playSpace = document.querySelector('#playSpace');
var shape = document.getElementById("shape");
var maxHeight = playSpace.offsetHeight - shape.offsetHeight;
var maxWidth = playSpace.offsetWidth - shape.offsetWidth;
var positionTop = Math.random() * (maxHeight - 0) + 0;
var positionLeft = Math.random() * (maxWidth - 0) + 0;
// think of this like so:
// var positionTop = Math.random() * (max - min) + min;
// more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
element.style.position = 'absolute';
element.style.top = positionTop + "px";
element.style.left = positionLeft + "px";
}
function size(element) {
var sizeMath = (Math.random() * 200) + 50;
element.style.width = sizeMath + "px";
element.style.height = sizeMath + "px";
}
document.getElementById("shape").onclick = function() {
size(document.getElementById("shape"));
position(document.getElementById("shape"));
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin:0;
padding-top: 30px;
}
#playSpace {
position: relative; /* add this line */
width: 90%;
height: 90%;
margin: 0 auto;
border: 1px black solid;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
You can use a specify the range (min/max) in Math.random function and then use this function Math.floor(Math.random() * (max - min + 1)) + min; to limit the returned value of the random function between min and max.
maxTop : height of the container - height of shape
maxLeft : width of the container - width of shape
minTop : 0
minLeft : 0
You need to use position:absolute and px value on shape for this to work
See code snippet:
function position() {
var minTop = 0;
var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight;
var minLeft = 0;
var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ;
var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop);
var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft);
var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
return position;
}
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.cssText = position();
}
#gameSpace {
width: 100%;
height: 470px;
background: blue;
margin: 0;
padding-top: 30px;
text-align:center;
}
#playSpace {
width: 90%;
height: 90%;
border: 1px black solid;
position:relative;
display:inline-block;
}
#shape {
width: 100px;
height: 100px;
background-color: red;
}
<div id="gameSpace">
<div id="playSpace">
<!-- here we put the shape -->
<div id="shape"></div>
</div>
</div>
With CSS calc, limit the position inside playSpace area (you can use different units, here % and px).
Then with offsetTop/offsetLeft, get the real position of the square and avoid negative positions (when positionTop < 100px or positionLeft < 100px).
function position() {
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
var position = "position:relative;top: calc(" + positionTop + "% - 100px);left: calc(" + positionLeft + "% - 100px);";
return position;
}
document.getElementById("shape").onclick = function() {
var shapeDiv = document.getElementById("shape");
shapeDiv.style.cssText = position();
var top = shapeDiv.offsetTop;// Result of calc(" + positionTop + "% - 100px) in px
if(top < 0) {
shapeDiv.style.top = '0px';
}
var left = shapeDiv.offsetLeft;// Result of calc(" + positionLeft + "% - 100px) in px
if(left < 0) {
shapeDiv.style.left = '0px';
}
}
Don't forget to add position: relative to #playSpace, to get offsetTop/left correct
#playSpace {
position:relative;/* mandatory */
}
You can get the parent element size, so that in your scirpt, use a condition to prevent the square to exceed.
function position() {
var maxWidth = document.getElementById("playSpace").offsetWidth;
var maxTop = document.getElementById("playSpace").offsetHeight;
var positionTop = Math.random() * 100;
var positionLeft = Math.random() * 100;
if (positionTop > maxTop) { positionTop = maxTop;)
if (positionLeft > maxWidth) { positionLeft = maxWidth;)
var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
return position;
}
I'm not sure if .offsetWidth and .offsetHeight works well, but you got the idea :)
By tweaking just a little your positionTop and positionLeft variable, I managed to keep the square inside. You just need to change the maximum % that it needs to have to not exceed the container. I found that 75% for the top and 80% for the left seems to be the max!
var positionTop = Math.floor(Math.random() * 75) ;
var positionLeft = Math.random() * 80;
Here's a fiddle
If you set the containing element to position: relative; and the inner element with position: absolute; the inner elements top left right and bottom properties will calculate from the borders of the containing element.
Here is a good source of css positioning.
In your case additional validation should be set to positionTop and positionLeft.
positionTop should be in the interval [( shapeHeight/2 ) - (100 - shapeHeight/2 ) ]
positionLeft should be in the interval [( shapeWidth/2 ) - (100 - shapeWeight/2 ) ]

Why is my precision web layout imprecise?

I am having a problem modifying HTML with Javascript. An example can be found here: https://jsfiddle.net/02mwyvyo/
My goal is to move a specific element down the page. I am trying to do this by inserting a spacer div before the target element. The spacer div's style attributes are style="display: inline-block; width=1px; height=100px;".
Here is the code I am using:
function describeDOMRect(rect) {
return "{ top: " + rect.top + ", left: " + rect.left + ", bottom: " + rect.bottom + ", right: " + rect.right + " }"
}
function addVerticalSpacer() {
var div = document.getElementsByClassName("target-div")[0]
var bounds = div.getBoundingClientRect()
console.log("old bounds: " + describeDOMRect(bounds))
var spacerHeight = 100
var newTop = bounds.top + spacerHeight
var spacer = document.createElement("div")
spacer.className = "spacer"
spacer.setAttribute("style", "display: inline-block; width: 1px; height: " + spacerHeight + "px;")
div.parentNode.insertBefore(spacer, div)
bounds = div.getBoundingClientRect()
console.log("new bounds: " + describeDOMRect(bounds))
}
And here are the CSS properties applied to div:
div {
border: none;
border-width: 0;
padding: 0;
margin: 0;
}
When I run the code above, this is what I see in the console:
old bounds: { top: 26, left: 8, bottom: 26, right: 729 }
new bounds: { top: 112, left: 8, bottom: 112, right: 729 }
Notice the old top position is 26, so I expect the new top to be 126, but it is 112.
Why is this happening? What can I do to correct it?
You are actually inserting the spacer div between Some text and Some more text. Since it is an inline-block it is appended at the end of the first line.

SVG animation with mousemove function inside setInterval function

I am trying to create something with SVG that responds to mouse movement combined with random movement.
you can check the code here
https://jsfiddle.net/hass/Lfv2yjyf/
$(document).ready(function(){
var d = document;
var mysvg = d.getElementById("mysvg");
var mx,my,random,xmid,ymid,input;
setInterval(function() {
//svg size
var svgw = $("svg").width();
var svgh = $("svg").height();
//center point of svg
xmid = svgw/2;
ymid = svgh/2;
//random numbers
random = {
a: Math.floor(Math.random()*25),
b: Math.floor(Math.random()*25),
c: Math.floor(Math.random()*25)
};
//add event to svg
mysvg.addEventListener("mousemove", function(e) {
//aqcuire mouse position relative to svg
mx = e.clientX;
my = e.clientY;
//add <path> to svg
input = '<path d="M ' + xmid + ',' + ymid + ' l ' + 0 + ',' + 0 + ' ' + ((mx-xmid)/2) + ',' + random.a + ' ' + ((mx-xmid)-((mx-xmid)/2)) + ',' + ((my-ymid)-random.a) + ' ' + '" stroke="orange" stroke-width="7" stroke-linejoin="round" fill="none" />';
});
//display datas
$("#status1").html("X Position : " + mx + "<br>Y Position: " + my + "<br><br>Center Point X: " + xmid + "<br><br>Center Point Y: " + ymid + "<br><br>Width: " + svgw + "<br>Height: " + svgh + "<br><br>Random Value a: " + random.a + "<br>Random Value b: " + random.b + "<br>Random Value c: " + random.c);
$("#mysvg").html(input);
}, 10);
});
My problem here is the random movement of the line at midpoint only responds when I move the mouse, I know it doesn't work because the random value is only acquired with mouse movement.
what I'm trying to do is I want the random movement even without the mouse movement.
so I want to know how I acquire the values of global object in setInterval every 10 milliseconds or whatever value I set at "setInterval" function but I prefer almost every millisecond so I could get the random vibrating effect.
I also tried to write the "path" outside of mousemove function and it works and this is something I wanted to achieve
https://jsfiddle.net/hass/d2L4hda5/
but the problem here is when I check the console (browser's development tool → console tab) the values of the mouse x and mouse y is "NaN". but the rendering works.
I cannot figure out what I'm missing here.
so I want to get some advice if second link is what I want to achieve and get the right values of mouse x and mouse y or any other technique that works best.
Regards.
I'm not entirely sure what you problem is here. Is your problem that you can't seem to see the values iof mx and my in your browser tools? How are you trying to read them? Note that they aren't global variables. They are local to the ready() function. So, for instance, you won't be able to see the value if you simply type mx into the console.
Note also, that you don't need to keep adding the mousemove event handler every time your interval timer function gets called. It can be totally independent. See below.
$(document).ready(function(){
var d = document;
var mysvg = d.getElementById("mysvg");
var mx,my,random,xmid,ymid,input;
//svg size
var svgw = $("svg").width();
var svgh = $("svg").height();
//center point of svg
xmid = svgw/2;
ymid = svgh/2;
//add event to svg
mysvg.addEventListener("mousemove", function(e) {
//aqcuire mouse position relative to svg
mx = e.clientX;
my = e.clientY;
});
setInterval(function() {
//random numbers
random = {
a: Math.floor(Math.random()*25),
b: Math.floor(Math.random()*25),
c: Math.floor(Math.random()*25)
};
//add <path> to svg
input = '<path d="M ' + xmid + ',' + ymid + ' l ' + 0 + ',' + 0 + ' ' + ((mx-xmid)/2) + ',' + random.a + ' ' + ((mx-xmid)-((mx-xmid)/2)) + ',' + ((my-ymid)-random.a) + ' ' + '" stroke="orange" stroke-width="7" stroke-linejoin="round" fill="none" />';
//display datas
$("#status1").html("X Position : " + mx + "<br>Y Position: " + my + "<br><br>Center Point X: " + xmid + "<br><br>Center Point Y: " + ymid + "<br><br>Width: " + svgw + "<br>Height: " + svgh + "<br><br>Random Value a: " + random.a + "<br>Random Value b: " + random.b + "<br>Random Value c: " + random.c);
$("#mysvg").html(input);
}, 10);
});
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
overflow: hidden;
}
#wrapper {
width: 100%;
min-height: 100%;
margin: 0 auto;
position: relative;
}
svg {
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin: 0 auto;
width: 100%;
height: 100%;
outline: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<p id="status1"></p>
<svg id="mysvg" width="300" height="300"></svg>
</div>

How to use % instead of px with draggable element?

I'm stucked and I need help. I'm making map with markers. I can add markers etc.
My main container have 100% width and height. When I click somewhere my marker has % values for example top: 34%; left: 35%;
After dragging marker new position have px value. I want to save % values.
Any ideas?
map.js
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
// $(maps).append('<div class="marker"></div>');
var marker = $('<div class="marker ui-widget-content"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker)
$('.marker').draggable().resizable();
}
map.click(function (e) {
// var x = e.pageX - this.offsetLeft;
// var y = e.pageY - this.offsetTop;
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
// $(this).append('<div class="marker"></div>');
AddPoint(x, y, this);
});
// drag function
$(".ui-widget-content").draggable({
drag: function( event, ui ) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
}
});
});
style.css
.wrapper {
margin: 0 auto;
width: 100%;
min-height: 400px;
overflow: hidden;
}
.map {
width: 100%;
position: relative;
}
.map > img {
max-width: 100%;
max-height: 100%;
}
.marker {
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
position: absolute;
left: 50%;
top: 50%;
z-index: 999;
}
#mapa {
width: 30px;
height: 30px;
border-radius: 50%;
background: rgba(255, 0, 0, 1);
z-index: 999;
}
some html code
<div class="wrapper">
<div class="map">
<img src="http://i.imgur.com/HtxXGR5.jpg" width="100%" height="auto" margin="15px 0;" alt="">
</div>
<button id="remove">Remove all markers</button>
</div>
If you want to capture the position, after the drag is ended (fire 1 time per drag) you can do this:
$('.marker').draggable({
stop: function() {
var offset = $(this).offset();
var mapOffest = $('.map').offset();
var x = ((offset.left - mapOffest.left)/ ($(".map").width() / 100))+"%";
var y = ((offset.top - mapOffest.top)/ ($(".map").height() / 100))+"%";
// We need to do something with thoses vals uh?
$(this).css('left', x);
$(this).css('top', y);
// or
console.log('X:'+x + '||Y:'+y);
}
});
Fiddle here
Take note that the event has been set on the marker directy, this was probably your mistake.
The little calcul needs to take care of the map offset, which you don't need if your map is a full width/height (window size)
If you need, or prefer use the drag event rather than the stop, theses lines won't have any effects
$(this).css('left', x);
$(this).css('top', y);
But you'll still be able to capture the position, the console values will be goods.
Hope it may helps you.
problem solved, DFayet thank's again
final code
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
var marker = $('<div class="marker"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker);
$('.marker').draggable({
stop: function(event, ui) {
var thisNew = $(this);
var x = (ui.position.left / thisNew.parent().width()) * 100 + '%';
var y = (ui.position.top / thisNew.parent().height()) * 100 + '%';
thisNew.css('left', x);
thisNew.css('top', y);
console.log(x, y);
}
});
}
map.click(function (e) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
AddPoint(x, y, this);
});
});

Categories