Javascript/jQuery Drag and Drop Limit parent - javascript

got the following problem. i need the following just to be drag/dropable in the green area.
should be something like that:
limit($(this).parent());
but thats not working, im using this for dnd:
$('#dragThis').draggable({
drag: function () {
var offset = $(this).offset();
var xPos = Math.abs(offset.left);
var yPos = Math.abs(offset.top);
$('#posX').val('x: ' + xPos);
$('#posY').val('y: ' + yPos);
},
stop: function (event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
var left = Math.abs(Stoppos.left);
var top = Math.abs(Stoppos.top);
$('#posX').val('x: ' + left);
$('#posY').val('y: ' + top);
}
});
hope someone can help me with that ;) thx so far
http://jsfiddle.net/DGbT3/1850/
///////////////
Update - getting correct x/y Position and just allow inside green area:
http://jsfiddle.net/DGbT3/1858/

You can use containment option for this which constrains dragging to within the bounds of the specified element or region.:
$('#dragThis').draggable({
drag: function() {
var offset = $(this).offset();
var xPos = Math.abs(offset.left);
var yPos = Math.abs(offset.top);
$('#posX').val('x: ' + xPos);
$('#posY').val('y: ' + yPos);
},
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
var left = Math.abs(Stoppos.left);
var top = Math.abs(Stoppos.top);
$('#posX').val('x: ' + left);
$('#posY').val('y: ' + top);
$('#info').val('x: ' + left + ' y: ' + top);
},
containment: $("#content")
});
Example

If you want to get the position according to its parent then use .position(), then check if the xPos and yPos are bigger than 0 and smaller that its parent's width..
$('#dragThis').draggable({
drag: function() {
var offset = $(this).position();
var xPos = offset.left;
var yPos = offset.top;
$('#posX').val('x: ' + xPos);
$('#posY').val('y: ' + yPos);
if(xPos < 0 || xPos > $(this).parent().width())
console.log("outside");
},
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
var left = Stoppos.left;
var top = Stoppos.top;
$('#posX').val('left: ' + left);
$('#posY').val('top: ' + top);
if(xPos < 0 || xPos > $(this).parent().width())
console.log("outside");
}
});
NOTE: there is a typo in your #content css position..

Related

jQuery : Get All DOM elements come under the selected part (Rectangle) like zooming plugins of jQuery

I want all the DOM elements (which can be overlapped by others too) to be listed out which falls under the selection. The thing I tried giving me at a fixed coordinate (with overlapped ones) but I need it to give me for full rectangle.
https://jsfiddle.net/mantrig/3tqqy0gt/
var flag=0;
$("#enable-show").click(function(){
if(flag==0) {
$(document).bind('mousemove', function(e){
$('#tail').css({
left: e.pageX - 80,
top: e.pageY-50,
});
var $elements = GetAllElementsAt( e.pageX , e.pageY);
var html="";
$elements.each(function() {
html += $(this)[0].id + "<br />";
$("#result").html(html);
});
$("#tail").show();
});
flag++;
}
else {
$(document).bind('mousemove', function(e){
$("#tail").hide();
});
flag=0;
}
});
function GetAllElementsAt(x, y) {
var $elements = $("body *").map(function() {
var $this = $(this);
var offset = $this.offset();
var l = offset.left;
var t = offset.top;
var h = $this.height();
var w = $this.width();
var maxx = l + w;
var maxy = t + h;
$("ul").append("<li>" + $this[0].id + " (" + $this[0].tagName + ")" + " [l:=" + l + ",t:=" + t + ",h:=" + h + ",w:=" + w + ",maxx:=" + maxx + ",maxy:=" + maxy + "]</li>");
return (y <= maxy && y >= t) && (x <= maxx && x >= l) ? $this : null;
});
return $elements;
}
Can anyone help with it?

Calculating positioning of the parent Div

Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation

Having issues with mousemove and images in Jquery

How can I make the other images also follow the mouse? Not all at the same time, but when I click on the selected image.
How can I calculate the distance where the mouse moved when I click on the image?
See link below.
HTML:
<div id="squarelocation"></div>
<div class="square 1">1</div>
<div class="square 2">2</div>
<div class="square 3">3</div>
Jquery:
$(document).ready(function () {
var i = true;
$(document).on('click', function () {
$(this)[i ? 'on' : 'off']('mousemove', follow);
i = !i;
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$(".2").offset({
left: e.pageX,
top: e.pageY
});
}
});
I suggest you to bind a click event to the square class like this:
var clickedImage;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and assign the context to a variable, so that you can refer to it whenever you needed. And then in your code, refer to that context instead of the hardcoded '.2':
$(clickedImage).offset({
left: e.pageX,
top: e.pageY
});
This way, the image clicked will be referred to, instead of just '2' following the mouse all the time.
Same for calculating the distance between the clicked origin and the current position, you can save the original spot on clicking the image:
var initialX;
var initialY;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and do the calculation in the 'follow' function, of course how the calculation should be is up to you, but here is an example:
var distanceX = xPos - initialX;
var distanceY = yPos - initialY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('#squaredistance').html("Distance from origin: " + distanceX + ", " + distanceY);
Hope this help. jsfiddle: http://jsfiddle.net/FW9jV/1/
You could add an 'active' class for the active square. I added an example.
The active square will always be moving until you click to deactivate it.
http://jsfiddle.net/fG6kr/1/
$(document).ready(function () {
var i = true;
$('.square').on('click', function () {
if( $(this).hasClass("active"))
{
$(this).removeClass("active");
$(document).off('mousemove');
}
else
{
$(this).addClass("active");
$(document).on('mousemove', follow);
}
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('.active').offset({
left: e.pageX,
top: e.pageY
});
}
});
demo
$(function() {
$('.square').click(function(){
$(this).toggleClass('sel');
});
$(document).on('mousemove', function(e){
$(".sel").offset({left: e.pageX+10, top: e.pageY+10});
});
});

How to resize a div based on mouse location?

I'm trying to make a div that expands left, right, up, and down depending on where the mouse is. But when I move the mouse, the div just pops up and doesn't do anything. What is wrong in what I'm doing?
(function() {
document.onmousemove = function(e) {
draw(e);
};
function draw(e) {
var method = [
e.pageX ? e.pageX : e.clientX,
e.pageY ? e.pageY : e.clientY
];
var X = method[0],
Y = method[1];
var html = '<div class="box" style="padding-top:' + Y + ';padding-bottom:' + Y + ';padding-left:' + X + ';padding-right:' + X + '"></div>'
;
document.body.innerHTML = html;
}
})();​
You forgot the unit px:
(function() {
document.onmousemove = function(e) {
draw(e);
};
function draw(e) {
var method = [
e.pageX ? e.pageX : e.clientX,
e.pageY ? e.pageY : e.clientY
];
var X = method[0],
Y = method[1];
var html = '<div class="box" style="background-color:red;padding-top:' + Y + 'px;padding-bottom:' + Y + 'px;padding-left:' + X + 'px;padding-right:' + X + 'px"></div>'
;
document.body.innerHTML = html;
}
})();​
(I've also added a red background in order to make the DIV visible)
jsFiddle: http://jsfiddle.net/8LUwp/
X and Y are numbers. CSS lengths require units. Add some px.
CSS length attributes (padding, margin, height, width etc.) require units - px, em etc. So just having:
padding-top:10
is invalid. Instead you need to add units:
padding-top:10px
So in your case the line setting the html should read:
var html = '<div class="box" style="padding-top:' + Y + 'px;padding-bottom:' + Y + 'px;padding-left:' + X + 'px;padding-right:' + X + 'px"></div>';
You were missing px suffix with the x and Y
(function() {
document.onmousemove = function(e) {
draw(e);
};
function draw(e) {
var method = [
e.pageX ? e.pageX : e.clientX,
e.pageY ? e.pageY : e.clientY
];
var X = method[0],
Y = method[1];
var html = '<div class="box" style="padding-top:' + Y +"px" + ';padding-bottom:' + Y +"px" + ';padding-left:' + X +"px" + ';padding-right:' + X +"px" + '"></div>'
;
document.body.innerHTML = html;
}
})();​

Use jQuery set .css RIGHT if #foo + offset left is greater than page width

Ok, so I am trying to use jQuery to get the innerWidth() of an element #preview. I want to create a conditional that says IF x offset LEFT + #preview width is greater than page width, give it style right: z where z = #preview width + xOffset.
I apologize my code below is a mess and the syntax for .css ("right", (rightFloat + xOffset) + "px") (line 125) is off, but that's part of my problem.
<script>
$(document).ready(function(){
//append "gallery" class to all items with "popup" class
imagePreview();
$(".popup").addClass("gallery");
});
//The overlay or pop-up effect
this.imagePreview = function() { /* CONFIG */
xOffset = 40;
yOffset = 40;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.preview").click(function(e) {
return false;
});
$("a.preview").hover(function(e) {
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
var rightFloat = e.pageX + ("#preview").innerWidth;
$("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
$("#preview").hide().css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px").fadeIn("2000");
while ((left + 400) > window.innerWidth) {.css("right", (rightFloat + xOffset) + "px")
}
}, function() {
this.title = this.t;
$("#preview").remove();
});
$("a.preview").mousemove(function(e) {
var top = e.pageY - yOffset;
var left = e.pageX + xOffset;
var rightFloat = e.pageX + ("#preview").innerWidth;
//flips the image if it gets too close to the right side
while ((left + 400) > window.innerWidth) {.css("right", +(rightFlaot + xOffset) + "px")
}
$("#preview").css("top", top + "px").css("left", left + "px");
});
};
</script>
Try using http://api.jquery.com/offset/
if($('#preview').offset().right<0){
var right = parseInt($(window).width()) - e.pageX + xOffset;
$("#preview").css("top", top + "px").css("right", right + "px");
}else{
var left = e.pageX + xOffset;
$("#preview").css("top", top + "px").css("left", left + "px");
}
I made these fixes because I couldn't get your code to work in jsfiddle:
var xOffset = 40;
var yOffset = 40;
$("a.preview").bind('mouseover',function(e){
var rightFloat = parseFloat(e.pageX)+$("#preview").innerWidth();
var ptop = parseFloat(e.pageY) - yOffset;
var pleft = parseFloat(e.pageX) + xOffset;
$("#preview").css({"top":ptop + "px","left":pleft + "px"});
});
There's the fixes for the top half but I have no idea what you're trying to do with the bottom part (with the while loop). Can you explain what functionality you want?

Categories