Getting element position in IE versus other browsers - javascript

We all know IE6 is difficult. But there seems to be disparate behavior in positioning in later versions of IE as well, when compared with Firefox or other browsers. I have a simple pair of javascript functions which finds the position of an element, and then displays another element in relation to the first element. The idea is to get the second element, which is somewhat larger, to appear in front of the first element when the mouse hovers over it. It works fine, except on all versions of Internet Explorer, the position of the second element appears different than in Firefox.
The code to get the position of an element is:
function getPosition(e)
{
var left = 0;
var top = 0;
while (e.offsetParent) {
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
}
And the actual rollover display code is:
var pos = getPosition(elem1);
elem2.style.top = pos.y - 8;
elem2.style.left = pos.x - 6;
In Firefox, elem2 appears directly over elem1, as I want it to. But in IE7 or IE8 it appears way off. What is the reason this occurs, and is there a way to fix it?

elem2.style.top = pos.y - 8;
CSS requires a unit. +'px'.
(There could conceivably be differences between IE and other browsers depending on how exactly elem2 is positioned.)

As Pointy commented the best thing is to go and look up the jQuery (or YUI that is probably more readable) code. There are normalization needed mainly by the IE quirksmode (but it's not the only issue). For instance (but I'm not sure) I think you need to add to the left/top total amount borders' size of each positioned absolute/relative elements you encounter in the while loop, but in IE6 you need to add borders only if position is absolute at least in quirksmode.
Your code might work without adding more normalization only if you use the DOCTYPE (either Transitional or Strict) as very 1st line of your HTML pages and you reset body/html border/margins and padding. In other words use this line at the beginning of your pages:
<!DOCTYPE...
and in your CSS:
html, body {margin: 0; padding: 0; border-width: 0;}
These anyway might not suffice.

Related

change start position of horizontal scrollbar without jquery

In Jquery I'm aware you can move the scrollbars' starting location. Is this possible with pure javascript? To clarify, when the user loads the page I simply want the horizontal scrollbar to start scrolled all the way to the right, instead of starting at the left. If there are cross-browser issues, I'm particularly concerned with this working in Chrome.
document.body.scrollLeft = ( divRef.scrollWidth - divRef.offsetWidth ) / 2 ;
NOTE:
This can give odd results with IE8 and earlier.
I've made an example with a div, you can easily adjust this to your body tag, or another div, please see the demo.
var a = document.getElementById('body');
console.log(a.clientWidth)
function moveWin(a) {
window.scrollTo(a.clientWidth,0);
}
moveWin(a)
DEMO
SIDENOTE:
To select the body, simply use
var a = document.getElementsByTagName('body')[0]

Content flicker/jump on infinite scroll/loop

I am looking for help / a point in the right direction / or a solution for a flicker/jump, when scrolling on a looping/infinite website, which can be seen in this fiddle.
What seems to be causing the jump is:
"$(window).scrollTop(half_way - child_height);", and what could also be a Chrome windows scrollTop bug, but it is happening in all browsers at the moment.
If I remove "- child_height" there is no longer a flicker but the page no longer scrolls correctly, which can be seen in this fiddle.
Also, on the very first scroll the right hand column jumps up by three boxes - also because of 'half_way', which I can fix by giving it a "bottom: -600px;"
The full code:
http://jsfiddle.net/djsbaker/j3d8r/1/
var num_children = $('#up-left').children().length;
var child_height = $('#up-left').height() / num_children;
var half_way = num_children * child_height / 2;
$(window).scrollTop(half_way);
function crisscross() {
$('#up-left').css('bottom', '-' + window.scrollY + 'px');
$('#down-right').css('bottom', '-' + window.scrollY + 'px');
var firstLeft = $('#up-left').children().first();
var lastLeft = $('#up-left').children().last();
var lastRight = $('#down-right').children().last();
var firstRight = $('#down-right').children().first();
if (window.scrollY > half_way ) {
$(window).scrollTop(half_way - child_height);
lastRight.appendTo('#up-left');
firstLeft.prependTo('#down-right');
} else if (window.scrollY < half_way - child_height) {
$(window).scrollTop(half_way);
lastLeft.appendTo('#down-right');
firstRight.prependTo('#up-left');
}
}
$(window).scroll(crisscross);
Okay - here is a 'working' version - and by works I mean it less flickery than before. I thought it was flicker free, and it was when I was on battery power, but plugged into the mains and the CPU is fast enough to get flicker.
As I mentioned, to get rid of the flicker you need to clone the objects, manipulate them and then replace them into the DOM, rather than just manipulating the DOM directly.
I did this by getting the contents of <div id="content"> manipulating them and then replacing them into that <div>.
Also, it's a good idea to only find things in the DOM once, and from then on use a reference to that object rather than searching repeatedly. e.g.
var leftSide = $(clone).find('.up-left');
....
lastRight.appendTo(leftSide);
....
$(leftSide).css('bottom', '-' + window.scrollY + 'px');
rather than:
lastRight.appendTo('#up-left');
$('#up-left').css('bottom', '-' + window.scrollY + 'px');
Searching the DOM is relatively slow, and so storing references can improve performance/reduce flicker.
Storing the object also makes the code easier to understand (imho) as you can easily see that you're referencing the same thing, rather than possibly different things.
I still get flickering in chrome on windows with Danack solution. For this site I would control all the scrolling (you already scroll manually one of the sides), and give elements absolute positions.
Or if you insist on using the browser scrolling, may be use animations: animate the height of the last elements till 0px then use appendTo, and then animato from 0px to the normal height...
This might be a long shot, but I had the same flickering when working with infinitescroll,
and ended up using imagesLoaded.I ended up appending the additional images (now loaded) with a fade in, and that prevented them from flickering because of the fact they were loaded.
So maybe by using the imagesloaded - or a callback on the images, you can solve the flickering. It does decrease the speed though. I can image that if you want to scroll through everything as fast as possible, this might not be the solution. Good luck!
A solution would be to not use the native scrolling functionality but to simulate scrolling. This would be done by setting the overflow of your content to "hidden" in addition with capturing the "mousewheel" event on it and triggering some action when it is called. I started to try this out here (using MooTools instead of jQuery since I'm more fimilar with it). It's currently just "working" on the left side by altering the margin-top of the first element.
My next steps would be:
Check if the negative margin-top of the first element is bigger than the height of it and move it to the right side if so.
Same logic for the last box on the right side with a negative margin-bottom.
This has some downsides, though. Simulating scrolling doesn't feel as natural as the native scrolling functionality and clicking the mousewheel doesn't work. These might be solveable but it would require some more coding to get it to work smoothly. Anyway, in the end you would have a solution without any flickering and with no sticky scrollbar at the side (An idea for a replacement could be a small area on the side that triggers the scrolling on mouseover).

offsetParent is different

For chrome and ff this script works perfect, when it comes to the horrible ie. there is a problem
function getY(oElement) {
var curtop = 0;
if (oElement.offsetParent) {
while (oElement.offsetParent)
{
curtop += oElement.offsetTop;
oElement = oElement.offsetParent;
}
}
else if (oElement.y) {
curtop += oElement.y;
}
return curtop;
}
I'm tried some debugging and found out that the parent of chrome and ff is <Li> which is correct, but the parent of ie is <body>
please help anyone?
Ok, i did some more digging and found that ie doesnt support offsetparent with position:relative; but I do need this css for other reason, any walkaround?
I used to use a script similar to this all the time to determine the position of the element. Since then I have moved to using jQuery which has two awesome and very cross browser compliant functions for determining position:
position() - http://api.jquery.com/position/ - gets the position of the element relative to the parent.
offset() - http://api.jquery.com/offset/ - gets the position of the element relative to the document.
I was a little reluctant to use jQuery at first because I didn't want to spend the time learning it and because I'd already written so many code snippets on my own that did things like this. When I did try jQuery I learned it within a day and I love it and now use it for all my JavaScript projects.
This might not be the answer you are looking for, but jQuery does have position finding functions.

javascript: finding the absolute size of an anchored link

I need to calculate the position, height and width of every anchored link in my page. I know how to find the x,y coords, but I have a problem with the height and width. The problem appears when the link has children inside (images, divs etc), so heightOffset and widthOffset won't work. Is there a way to do this without going on all the children and calculating their sizes?
EDIT:
Here is some code to demonstrate what I mean (the press function is called whenever the mouse is being pressed):
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
function getHeight(elem) {
if (elem.style.pixelHeight) {
return elem.style.pixelHeight;
} else {
return elem.offsetHeight;
}
}
function getWidth(elem) {
if (elem.style.pixelWidth) {
return elem.style.pixelWidth;
} else {
return elem.offsetWidth;
}
}
function press(e)
{
x= e.pageX;
y= e.pageY;
window.alert(x+","+y);
var links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++){
var pos = findPos(links[i]);
window.alert(x+","+y+" "+pos[0]+" " + pos[1] + " "+links[i].offsetWidth+ " "+links[i].offsetHeight);
if (x >= pos[0] && x <= pos[0] + getWidth(links[i]) && y >= pos[1] && y <= pos[1] + getHeight(links[i])){
window.alert(links[i].href);
i = links.length;
}
}
}
When I encounter a link with an image for instance it doesn't return me the right size.
Thanks
offsetWidth/Height do very much work on links that contain images, as long as you haven't done anything weird like overflowing or positioning the images or other child content so that they fall out of the content area of their parent.
Your code isn't using offsetHeight on IE, it's using pixelHeight, which doesn't do what perhaps you think it does. Stick with offsetHeight.
Conversely, you are using event.pageX/Y, which is a non-standard extension IE doesn't have. Sadly the only reliable way to get page-relative co-ordinates from an event is to use clientX/Y and adjust for viewport scrolling.
I don't really know why you are going to the effort of enumerating link positions when for a mouse click/down event you can quite reliably get the element that was clicked on using event.target/srcElement. In fact this is the only reliable way to do it. Consider a link that has split over two text lines. Now what you've got is a non-rectangular region; you can't test whether a particular mouse position lies within that area using a simple x and y range test.
The correct properties are offsetHeight (not heightOffset) and offsetWidth (not widthOffset).
Those properties should correctly return the sizes you're after, because the children would expand the elements to fit, assuming overflow is set to visible. There's no need to calculate the sizes of the children in any situation.
offsetHeight and offsetWidth aren't part of any standard but most browsers seem to have them implemented anyway.
Since you're having problems with Safari and offsetHeight, maybe you could try the getClientRects() method:
http://www.quirksmode.org/dom/tests/rectangles.html
var dims = links[i].getClientRects()[0];
var width = dims.right - dims.left;
var height = dims.bottom - dims.top;
Can't say I've ever used getClientRects(), however. It sounds like the results may be closer to clientWidth and clientHeight.
FURTHER EDIT
I figured out a workaround. The following does not work:
<a href="#">
<img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" alt="" />
<!-- onclick handler alerts with size 250x15 -->
</a>
But wrapping a <span> tag around the <img> tag, like so:
<a href="#"><span>
<img onclick="press(event);" src="http://sstatic.net/so/img/logo.png" />
<!-- onclick handler alerts with size 250x61 -->
</span></a>
Fixes the problem. At least, it does in Chrome but like I said before Chrome and Safari share the WebKit rendering engine, so it should work for Safari too.
You should not use the values in elem.style.* to determine the size of an element. These values are CSS styles and aren't reliable. Use only offsetWidth and offsetHeight.
To get the position of an element, use the answers to this question: Retrieve the position (X,Y) of an HTML element

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I'm building an auto-follow div that is bound to the $(window).scroll() event. Here is my JavaScript.
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"));
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if(scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2))+"px");
console.log("Setting margin-top to "+$("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
This code assumes that there is this CSS rule in place
#ActionBox {
margin-top: 15px;
}
And it takes an element with the id "ActionBox" (in this case a div). The div is positioned in a left aligned menu that runs down the side, so it's starting offset is approximately 200 px). The goal is to start adding to the margin-top value once the user has scrolled past the point where the div might start to disappear off the top of the browser viewport (yes I know setting it to position: fixed would do the same thing, but then it would obscure the content below the ActionBox but still in the menu).
Now the console.log shows that the event is firing every time it should and it's setting the correct value. But in some pages of my web app the div isn't redrawn. This is especially odd because in other pages (in IE) the code works as expected (and it works every time in FF, Opera and WebKit). All pages evaluate (0 errors and 0 warnings according to the W3C validator and the FireFox HTMLTidy Validator), and no JS errors are thrown (according to the IE Developer Toolbar and Firebug). One other part to this mystery, if I unselect the #ActionBox margin-top rule in the HTML Style explorer in the IE Developer Tools then the div jumps immediately back in the newly adjusted place that it should have if the scroll event had triggered a redraw. Also if I force IE8 into Quirks Mode or compatibility mode then the even triggers an update.
One More thing, it works as expected in IE7 and IE 6 (thanks to the wonderful IETester for that)
I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.
One solution would be to add a position: fixed to the CSS definition, but I see this won't work for you
Another solution would be to position the ActionBox absolutely (to the document body) and adjust the top.
Updated the code to fit with the solution found for others to benefit.
UPDATED:
CSS
#ActionBox {
position: relative;
float: right;
}
Script
var alert_top = 0;
var alert_margin_top = 0;
$(function() {
alert_top = $("#ActionBox").offset().top;
alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);
$(window).scroll(function () {
var scroll_top = $(window).scrollTop();
if (scroll_top > alert_top) {
$("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
} else {
$("#ActionBox").css("margin-top", alert_margin_top+"px");
};
});
});
Also it is important to add a base (10 in this case) to your parseInt(), e.g.
parseInt($("#ActionBox").css("top"),10);
Try marginTop in place of margin-top, eg:
$("#ActionBox").css("marginTop", foo);
I found the answer!
I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).
The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS
#ActionBox {
position: relative;
float: right;
}
Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)
I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.
The correct format for IE8 is:
$("#ActionBox").css({ 'margin-top': '10px' });
with this work.
try this method
$("your id or class name").css({ 'margin-top': '18px' });

Categories

Resources