I am using jquery and I am trying to find the position of the block relative to the parent:
$("*", document.body).click(function (e) {
var offset = $(this).position();
e.stopPropagation();
$("#result").text(this.tagName + " coords ( " + offset.left + ", " + offset.top + " )");
});
https://jsfiddle.net/gk8z18vg/3/
How to get the correct value? Why is offset left 11
You need to add position relative to the parent container so that the value doesn't concern the position from the entire document but just from the parent. The 11 offset looks like the offset of the container + the multiple borders.
#co {
position: relative;
}
Fixes it.
Also note that margin are not concerne when talking about position.
Hope that helps
Related
I'm trying to figure out how to get the value of an element width: 'min-content' in px. How is it calculated? I have a slide selector that modifies the css left property of a relative positioned element inside a div that has a max width of 1200px. I need to know if the difference between 1200px and left value has reached the minimum width of the element to stop it incrementing. Like:
styles.formato.width = 1200
styles.plato.posh contains the slide value for the left attribute
$('.menu-preview .menu-plato').css('max-width', styles.formato.width + 'px');
$('.menu-preview .menu-plato').css('min-width', 'min-content');
$('.menu-preview .menu-plato').css('width', 'calc(' + styles.formato.width + 'px - ' + (styles.plato.posh > 0 ? styles.plato.posh : (-styles.plato.posh)) + 'px)')
$('.menu-preview .menu-plato').css('left', styles.plato.posh + 'px');
This code just shrinks ".menu-plato" width to force break-words if it reachs the end of the parent div. But, as "left" max value is styles.formato.width, ".menu.plato" element just overflow parent.
What I want to achieve is:
if (element."min-width" <= (styles.formato.width - styles.plato.posh)){
//DON'T UPDATE LEFT PROPERTY BECAUSE CHILD IS USING MIN-WIDTH AS WIDTH VALUE
//SO IT CANNOT BE SHRUNK MORE AND LEFT ATTR WILL OVERFLOW THE ELEMENT TO THE RIGHT
}
I've tryed using some element node attrs like clientWidth or offSetWidth but failed because when the element width reachs the min-width value, they both hold the min-width value, but, as it's a slide selector and those attributes depends on the screen rendering, if you slide too fast, the calculations are wrong.
EDIT
There are more than one element with those classes, so what I've tryed is:
$('.menu-preview .menu-plato').each((index, element) => {
element.style.width = ('calc(' + styles.formato.width + 'px - ' + (styles.plato.posh > 0 ? styles.plato.posh : (-styles.plato.posh)) + 'px)');
if (element.offsetWidth <= (styles.formato.width - (styles.plato.posh > 0 ? styles.plato.posh : (-styles.plato.posh)))) {
if (styles.plato.posh >= 0) {
element.style.left = styles.plato.posh + 'px'
}
}
})
Thanks
And I want to get the width or distance or pixel that between the div and left side of of window/viewport.
And another width again between the div to the right side of the window.
I will use the width to create a left line and right line.
But I am poor in jQuery, I try offset but seems nothing happen.
So I back to 0 again so I didn't include fiddle here since I got nothing inside.
But I have attached with the image link as below, to explain my question.
Please help me on try to get the width, I can create the line myself.
Thank you.
var of = $(ele).offset(), // this will return the left and top
left = of.left, // this will return left
right = $(window).width() - left - $(ele).width() // you can get right by calculate
Maybe this can help you.
After all, .width() isn't the only answer, like innerWidth() or outerWidth()
There is two options
One is you can use red line as image and you can place the div over the red line.
Second one,
If you want to calculate:
Left div width = parent div width - child div offset;
Right div width = parent div width - child div offset + child div width;
var parentdiv = document.getElementById("ParentDivID");
var parentWidth = parentdiv.offsetWidth;
var childdiv = document.getElementById("childDivID");
var childWidth = childdiv.offsetLeft;
This is easier to do with POJ (plain old javascript). Get the position of the element on the screen. Then evaluate its left property. That will be the width of your left line. Then subtract its right property from the width of the screen. That will be the width of your right line.
var x = document.getElementById('myDiv').getBoundingClientRect();
var myLeftLineWidth = x.left;
var myRightLineWidth = screen.width - x.right;
For more information see this post.
If you want the width of the window instead of the screen, change screen.width to window.innerWidth. If you don't want the scrollbar, etc. to be included in the width, use document.documentElement.clientWidth. (For more info on these, see this.)
We can work out that where the box starts with .offset().
Next, we can work out where the box ends with .offset() + .width().
We now know where our box sits on the x-axis.
Now let's see what we have to the left of our box with .left which can run on our .offset().
We've now worked out how much space there is to the left and how wide our box is.
Finally, we can put what we've worked out together, we can get the page width $(window).width() and minus what there is to the left of our box (stage 2) and the width of our box (stage 1) and that will only leave what is to the right of our box.
That's the theory anyway now let's have a look at some code. You'll see I'm working out all the bits from the theory and then adding some visual representation.
calcSizes = function() {
var boxPos = $(".box").offset(),
toLeft = boxPos.left,
toRight = $(window).width() - ($(".box").width() + toLeft);
$(".left").width(toLeft + "px");
$(".right").width(toRight + "px");
console.log("Right: " + toRight + "px");
console.log("Left: " + toLeft + "px");
console.log("Width: " + $(".box").width() + "px");
console.log(
$(window).width() + "px = " +
toRight + "px + " +
toLeft + "px + " +
$(".box").width() + "px"
);
console.log(" ");
}
calcSizes();
body {
margin: 0
}
.box,
.indicator {
padding: 10px 0;
text-align: center
}
.box {
width: 100px;
background: #FF5722;
margin-left: 60%
}
.indicator {
background: repeating-linear-gradient( 45deg, #F44336, #F44336 10px, #D32F2F 10px, #D32F2F 20px);
overflow: hidden;
transform: translatey(-100%);
opacity: .8
}
.left {
float: left
}
.right {
float: right
}
button {
position: fixed;
top: 55px;
left: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">BOX</div>
<div class="left indicator">
LEFT
</div>
<div class="right indicator">
RIGHT
</div>
<button onclick="calcSizes()">
Recalculate
</button>
Hope this makes sense and helps you with your project.
You can do that with JavaScript, no need for jQuery:
var mydiv = document.getElementById('mydiv');
var offset = mydiv.getBoundingClientRect();
var offsetRight = document.documentElement.clientWidth - offset.right;
var offsetLeft = offset.left;
JSFiddle
am trying to make responsive menu related to div as you see in my jsfiddle Demo link,
my problem with arrow and menu position , i need to add class if menu closest to right border of container or even to left border or top border or bottom border , i mean change position of menu and change arrow position and also to make menu not ever come out of container..
Demo
This Is My Code :
var popupid,gid = 0;
$(".box").on("click",function(e){
e.preventDefault();
placeholder();
var self = $(this),
pos = self.position(),
selftop = pos.top,
selfleft = pos.left,
width = self.outerWidth(),
popup_Options = self.find(".popup");
popupid = 'placeholder-' + gid++;
popup_Options
.attr('placeholder', popupid)
.before('<div class="placeholder ' + popupid + '"></div>')
.appendTo('.Container');
popup_Options.css({
position: "absolute",
top: selftop + "px",
left: (selfleft + width) + 20 +"px"
}).show();
e.stopPropagation();
});
$('html').on('click',function(e)
{
placeholder();
});
function placeholder()
{
// Move back out of container
$('div[placeholder="'+popupid+'"]')
.appendTo('.placeholder.' + popupid)
.unwrap()
.removeAttr('placeholder')
.hide(); // Unset placeholder data
}
I want to read position relative to clicked element e.target instead of eventObject.pageX and eventObject.pageY.
var eventObject = null;
$(document).click(function(e){
eventObject = e;
//how to get position relative to e.target ??
});
Have you tried:?
var posX = $(this).position().left, posY = $(this).position().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
There are 2 methods of getting the position of an element depending on what you want.
This returns the position relative to the element's parent
$(eventObject.target).position().top;
$(eventObject.target).position().left;
And this is for the position relative to the document
$(eventObject.target).offset().top;
$(eventObject.target).offset().left;
The implementation differs depending on the position the element has (absolute or relative)
var targetRelativeX = eventObject.pageX - eventObject.target.offsetLeft;
var targetRelativeY = eventObject.pageY - eventObject.target.offsetTop;
i think it can your see here
$(document).ready(function(){
$("button").click(function(){
var x = $("p").position();
alert("Top position: " + x.top + " Left position: " + x.left);
});
});
Please have a look at the attached image.
As you can see i am showing a popover. Basically i want to change the placement of the popover depending up on the space available( left or right ). Right now its going outside of an image.
Its a fancy-box(iframe)
Showing the popover using this code.
// Position and show the message.
this.message
.css({
left: (tPosition.left + "px"),
top: ((tPosition.top + t.outerHeight()) + "px")
})
.show();
I would do something like this:
this.message
.css({
left : function () {
if ( tPosition.left + $(this).width() >= $(this).parent().width() ) {
return $(this).parent().width() - $(this).width();
}
else {
return tposition.left;
}
},
top : function () {
if ( tPosition.top + $(this).height() > $(this).parent().height() ) {
return $(this).parent().height() - $(this).height();
}
else {
return tposition.top;
}
}
});
Basically you need to check if the popup is going to exceed your containing box boundaries before you show it and adjust it appropriately. On the horizontal axis this is as simple as making sure that mouse position x + the width of the popup is not greater than the width of the parent container. On the vertical axis you want to make sure that mouse position y + the popup height is not greater than the parent container height.