I am trying to code a little game and therefore trying to move an object in a certain area. To get somewhat of a border I am trying to add up positions. However I will simplify this for you and this is what does not work: (in JS)
parseInt( $('#w'+w ).css( 'top' ) + $('#w'+w ).css( 'height' ) )
this should just add up the top position with the height of this element. When I print this out it will tell me it is 100. But when I print height and top without adding them up its height = 500 and top = 100 ( This is how it is in the css code ).
If i swap height and top and add this up the result is 500, so the first element. I got similar calculations, which fit. Any suggestions what went wrong in my code?
You are probably concatenating strings:
// $('#w' + w).css('top') returns the string "100px"
// $('#w' + w).css('height') returns the string "500px"
parseInt("100px" + "500px") // 100
parseInt("500px" + "100px") // 500
I suggest that you change your code to this:
parseInt($('#w' + w).css('top')) + parseInt($('#w' + w).css('height'))
for top use position:
var position = $('#w'+w ).position();
console.log( "left: " + position.left + ", top: " + position.top );
for height or width use jQuery width() and height():
console.log( "width: " +$('#w'+w ).width() + ", height: " + $('#w'+w ).height() );
Related
I am trying to get the position of an element dropped onto the canvas using the following code.
var x = $(".partitiondrop").position();
alert("Top position: " + x.top + "\nLeft position: " + x.left);
The above works fine. I would like to know if I can get the Right and Bottom positions in the same way so that I can have the area bound by the element as I need to check which elements fall inside this element.
var $partitiondrop = $(".partitiondrop");
var position = $partitiondrop.position();
position.bottom = position.top + $partitiondrop.height();
position.right = position.left + $partitiondrop.width();
alert("Top position: " + position.top + "\nLeft position: " + position.left + "\nBottom position: " + position.bottom + "\nRight position: " + position.right);
U can always add width to x.left position and add height to x.top position.
To get the position of any element by its ID you can do the following
var elementID; //Already obtained via attr(id) method or so
var $element = $("#" + elementID);
var position = $element.position();
position.bottom = position.top + $element.height();
position.right = position.left + $element.width();
var top_position=position.top;
var left_position=position.left;
var bottom_position=position.bottom;
var right_position=position.right;
In Jquery, it can be done using the following code
var p = $( "elementId" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
Right Position:
$(window).width() - ($('.partitiondrop').offset().left + $('.partitiondrop').width());
Bottom Position:
$(window).height() - $('.partitiondrop').offset().top;
I am trying to achieving a parallax effect using JavaScript.
I have a primary header in which its height is determined by the height of the browser to make it full height. I then want to push down the secondary header by however much the height is of the primary header.
This is what I have so far:
var primaryHeader = document.getElementById('primary-header');
var secondaryHeader = document.getElementById('secondary-header');
primaryHeader.style.height = (window.innerHeight || document.documentElement.clientHeight) - 40 + 'px';
secondaryHeader.style.marginTop = primaryHeader + 40 + 'px';
window.onresize = function() {
primaryHeader.style.height = (window.innerHeight || document.documentElement.clientHeight) - 40 + 'px';
secondaryHeader.style.marginTop = primaryHeader + 40 + 'px';
};
When I try to apply the margin to the secondary header it does not seem to work. Am I doing anything fundamentally wrong?
Here is an example fiddle: http://jsfiddle.net/d79TT/
Thanks.
The issue is here:
secondaryHeader.style.marginTop = primaryHeader.style.height + 40 + 'px';
You are doing string concatenation, instead of addition.
Because primaryHeader.style.height returns something like 172px, which is a string, so the end result would be:
172px40px
instead of
212px
This question already has answers here:
jQuery x y document coordinates of DOM object
(3 answers)
Closed 8 years ago.
I have section and article for displaying contents. My code is:
<section id = "examples">
<article id="item_1">
...
</article>
<article id="item_2">
...
</article>
<article id="item_3">
...
</article>
<article id="item_4">
...
</article>
...
</section>
How can I get the x and y co-ordinates of all the articles?
Easy to do with jQuery
$('article').each(function() {
var element = $(this);
var position = element.position();
console.log( "left: " + position.left + ", top: " + position.top );
}
you can use instead pure js as #koningdavid pointed out in the same way
var elements = document.getElementsByTagName('article');
for(var i = 0; i < elements.length; i++)
{
var element = elements[i].getBoundingClientRect();
console.log( "left: " + element.left + ", top: " + element.top );
}
Live: http://jsfiddle.net/HMHbE/1/
Pure Javascript method
document.querySelector('#item_1').getBoundingClientRect() // for example for #item_1
element.getBoundingClientRect
The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.
The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.
https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
You could do it with jQuery using position or offset:
$('article').each(function(){
var position = $(this).position();
console.log("top: " + position.top + " left: " + position.left);
});
LIVING DEMO
Take into account that position is relative to the document and offset calculates the coordinates relative to the parent offset element.
I would try this in javascript:
// element is each article
// then you can use element.top and element.left for the x and y
var element = document.getElementById('Item_1');
var ele = element.getBoundingClientRect();:
You can use getBoundingClientRect() javascript function
var div = document.getElementById("item_1");
var position = div.getBoundingClientRect();
alert("Coordinates: " + position.left + "px," + position.right+"px,"+ position.top + "px," + position.bottom + "px" );
I would like to implement behaviour such that a mouseover/hover event is triggered when the mouse pointer hovers over a certain div, but such that the mouseout event tiggers not when the pointer leaves the div, but when it leaves the area 10px ourside the div.
Is there any way of achieving this that doesn't involve creating a larger parent div to bind the mouseout event to?
My comment got me interested to see if it was possible and it's actually quite easy. No idea how well it would run in different browsers and with lots of divs but it works in this example:
http://jsbin.com/exulef/2/edit
var hello = $('#hello');
var position = hello.offset();
var height = hello.height();
var width = hello.width();
$(document).mousemove(function(e) {
if (hello.data('inside')) {
if ((e.pageX < position.left - 10 || e.pageX > position.left + width + 10) ||
(e.pageY < position.top - 10 || e.pageY > position.top + height + 10)) {
hello.text(position.top + " : " + position.left + " : " + e.pageX + " : " + e.pageY + " Outside")
.data('inside', false);
}
}
else {
if ((e.pageX > position.left && e.pageX < position.left + width) &&
(e.pageY > position.top && e.pageY < position.top + height)) {
hello.text(position.top + " : " + position.left + " : " + e.pageX + " : " + e.pageY + " Inside")
.data('inside', true);
}
}
});
hello is just a square div. Would be quite easy to turn into a plugin as well which I might do later, lol.
Edit - I did make this into a plugin in the end: http://jmonkee.net/wordpress/2011/09/07/jquery-extended-hover-plugin/
There is a way to do that without an external div, but it imply that your div will have a margin even when not hovered.
It uses the fact that the padding is inside the div, and the margin is outside.
When nothing happens, we have a margin, we have to go inside the div to hover.
When it's hovered, the margin becomes padding, this way we're inside the div for a little bit more when the mouse leaves the div.
When we're leaving the padding, it's back to margin.
The css is something like:
.a{
margin:10px;
}
div.b{
padding:10px;
margin:0;
}
Note that it's important to have a b selector that's a bit more specific in order to have it apply without using important and without taking attention of the order.
The js would be:
$(".a").bind("mouseenter",function(){
$(this).addClass("b");
}).bind("mouseleave",function(){
$(this).removeClass("b");
});
Example here: http://jsfiddle.net/ynecV/
Hmm, I would go with wrapping desired div in another one and binding mouseout on it - it would be most reliable solution.
BUT, if you insist on not creating another div, then I would bind custom mousemove handler that would be binded (on document) on mouseenter over div, and would detect the fact that mouse move away from div bounding box for more than 10px. If so, mousemove handler would fire custom jQuery event and then it would unbind itself.
I am creating an animation that changes the value of a background image. It is working perfectly if I hard code in the coordinates, but I am trying to modify it so that it simnply increments the position by 20px.
Here's the code I am using to retrieve the original Y position - works perfectly:
$('.rss,.twitter,.jquery').each(function(){
// Returns "##px" and "##px"
var backgroundPositions = $(this).css('background-position').split(" ");
// Retrieve the original Y position
$(this).data("originalYpos", backgroundPositions[1].slice(0, -2));
});
Now I am trying to increment the value of originalYpos by 20px but this isn't working:
var animateNum = function() {
$('.rss,.twitter,.jquery').animate({
var YPos = $(this).data('originalYpos')+20;
backgroundPosition: 0 + "px " + YPos + "px"}, 400, "easeOutCirc");
};
I do believe it is because the declaration of var Ypos isn't allowed inside the .animate(), but I need to refer to $(this), meaning the value of each of the 3 individual selectors as they are being animated.
Any suggestions are greatly appreciated!
Try:
var animateNum = function() {
$('.rss,.twitter,.jquery').animate({
backgroundPosition: "0 " + ($(this).data('originalYpos')+20) + "px"
}, 400, "easeOutCirc");
};
Why store the old value at all:
From http://api.jquery.com/animate/
Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.
So, the code below should work (although I haven't tried it myself)
var animateNum = function() {
$('.rss,.twitter,.jquery').animate({
backgroundPosition: "+=20px"
}, 400, "easeOutCirc");
};
Should be like this:
var animateNum = function() {
$('.rss,.twitter,.jquery').animate({
backgroundPosition: $(this).data('originalYpos')+20 + "px"}, 400, "easeOutCirc");
};