Explain me that difference in pixels? - javascript

There is element
var stickyBar=$('#sticky_bar');
Which has on load position:fixed, so I getting distance between stickyBar top and document top:
var initial=stickyBar.offset().top - $(window).scrollTop();
But, when I do this:
$(window).scroll(function(){
alert(initial+", " + (stickyBar.offset().top - $(window).scrollTop()))
});
These values are different: difference is 61px.
I can't get from where it comes from.

Per the documentation, jQuery's offset() does not account for margins, borders, or paddings. You should make sure you don't have any margins, borders, or paddings affecting the outcome.
You get the values of these margins, borders, and paddings by using
parseInt($("#sticky_bar").css("padding-top"))
and its variants. Then account for those values in your code.

Try making sure through an inspector application that all values on the element (CSS Box Model) are 0. Went through Michal's fiddle and agree, the problem is somewhere on your end. User error.

Related

element.scrollTop has different behavior across browsers while setting a very large value

I want to scroll to bottom without triggering layout/reflow.
So I tried to set a fixed large number(Number.MAX_SAFE_INTEGER or 1000000000000000) to scrollTop, which caused different behavior across browsers:
Firefox(59.02)/Safari(11.1): scroll to top
Chrome(66.0.3359.139): scroll to bottom
Here's the Example.
Is this a bug or there's something I went wrong...?
Instead you can try with scrollTop to the calculated height of the page.
It is simpler and straight forward.
Steps to follow
1. Find the height of the document / any container div
var containerHeight= $("#box").height();
scrollTop with containerHeight.
document.querySelector('#box').scrollTop = containerHeight;
This will surely work with any behaviour mismatch.
This could be caused by the different max values for elements across browsers. For instance, in Chrome the limit is 33554428px. A complete list was given here: What's the maximum pixel value of CSS width and height properties?

Get actual content height with Javascript (or jQuery)

There are many ways of getting the height of a document, but due to different browser implementations most of them (I believe) return the highest of a number of values ... which is fine most of the time.
In my case I have a number of elements on the page that I know to be a smaller height than the window and viewport heights. What I'm trying to get is the actual height of all the rendered elements.
Things that don't work (with testing in Firefox):
$(document).height(); // gives the window height
document.body.scrollHeight; // gives 7, its always 7 I don't know why
document.body.offsetHeight; // also gives 7
document.documentElement.clientHeight; // sometimes gives window height
document.documentElement.scrollHeight; //gives window height
document.documentElement.offsetHeight; generally gives a value in the range of 23
At present I'm thinking that the way around this might be to insert a div with height: 0 at the bottom of my page and grab $(div).offset().top, but I feel that this is highly likely to go wrong at some point in the future.
So before I do that ...
Is there a way of knowing the content height when it's less than the window height?
EDIT:
People have asked for clarification. Heres a jsFiddle example of what I want / the results I'm getting.
https://jsfiddle.net/8Lu2zcw8/1/
Running that results in the same value for Win Height: and Doc Height being written out to the console.
EDIT2:
My issue was due to the body not wrapping the content correctly due to floated and absolutely positioned elements, as pointed out by #tim-vermaelen in the comments to his solution.
I suggest you use $(document.body).height().
In CSS you have to put:
html,
body { height: 100%; }
This will only give correct results in case of body padding, margin and borders of the body element are 0. When direct children are floating or put on position absolute, the height of these elements doesn't count. Hence for floating elements you always clearfix the parent to solve these wrapping issues.
If not you can use $(document.body).outerHeight(includeMargin)
$(document).height() will give you content size, not window's. If it gives you window's size, then you probably messed up your CSS. Also, you can try $('body').height()

How to open website at specific point on page in HTML?

beginner programmer so apologies if this is really obvious!
How can i get my website to open at a specific point on the page (in HTML)?
I can't find what this is called anywhere! Not Anchor etc. The website will be wider and longer than most screens. I want the screen/viewport to open at the very centre of a 2500x2500 pixel background.
I am working in DreamWeaver CC on Mac OS X 10
Thanks in advance!!
p.s no code to post, this is my first port of call in putting this together
You can get the client's screen with $(window).width() & $(window).height() , it's jQuery code so you'll have to add a balise script to the jQuery lib on your web page. Can you tell me more about what you want to do ? I have trouble understanding. You don't want any anchor but you want ? Apoligies for not understanding.
Try this bit of Javascript to fire when the page loads
window.onload = function(){
window.scrollTo(1250, 1250);
}
The window.scrollTo(x-coord,y-coord) function takes two parameters, x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left and y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.
I picked 1250, because that's 2500 divided by 2, but you may have to tweak that a little if you want that spot in the middle of the screen. You will have to get the screen's viewport and do some math.
(hint: window.innerWidth & window.innerHeight gives you the dimensions including the scroll bar; document.documentElement.clientWidth and document.documentElement.clientHeight is without the scrollbar)
The documentation for window.scrollTo() is here: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
Some info about the viewport dimensions can be found here: http://ryanve.com/lab/dimensions/
As bryguy said, you can calculate the center of your screen and use scrollTo(). Alternatively, if you have a particular element that you want to scroll to, give the element an id and use the scrollIntoView() function. You can also center an invisible div positioning the div absolutely and setting the top and left values to 50%:
HTML
<div id="scrollToMe" style="position: absolute; top: 50%; left: 50%;"></div>
JS
window.onload = function() {
document.getElementById('scrollToMe').scrollIntoView();
};
You can do this without jQuery. You can use the native JavaScript function window.scrollTo() to scroll to the center.
To calculate the center of the screen all you have to do is:
For vertical center
Determine the height of the viewport: The height of the viewport is stored at document.documentElement.clientHeight.
Determine the height of the entire document: You can use document.documentElement.offsetHeight or document.body.scrollHeight to get the height of the entire document.
Calculate: Now simply subtract the viewport height from the document height and divide it by two like this:
(document.documentElement.offsetHeight - document.documentElement.clientHeight)/2
For horizontal center
Determine the width of the viewport: The width of the viewport is stored at document.documentElement.clientWidth.
Determine the width of the entire document: You can use document.body.scrollWidth to accomplish this.
Calculate: Now simply subtract the viewport width from the document width and divide it by two like this:
(document.body.scrollWidth - document.documentElement.clientWidth)/2
Now time to scroll
Finally, you'll want to make the window scroll to the calculated point.
window.scrollTo(centerWidth, centerHeight);
If you want to do all of it in one step, you'd do:
window.scrollTo( (document.body.scrollWidth - document.documentElement.clientWidth)/2, (document.body.scrollHeight - document.documentElement.clientHeight)/2 );
Please note that we've used document.documentElement.clientHeight (and clientWidth) and they give you the viewport size without the scrollbars. If you wish to include the scrollbars you'll have to use other variables. You can find examples of how to get those measurements on the internet.
For more information: Center a one page horizontally scrolling site in browser (not centering a div)

Dealing with scroll bars and jquery .width() method

jQuery's .width() method doesn't seem to account for scroll bars. This is problematic for me, since I'd like to set the width of some children to equal the width of their parent. I used jQuery similar to the following:
$('#contentDiv').width($('#containerDiv').width())
In this example, #contentDiv is the element I'd like to size, and I want to set it to have the width of #containerDiv, which is its parent element. My problem is that this cuts off the side of #contentDiv, as seen in this fiddle.
In my actual code, I have several elements that I'm sizing with jQuery, which all need to fit in the scrollable div, so just setting the css of #contentDiv to 100% is not an option. What's the best way of dealing with scroll bar widths of divs in jQuery?
The best solution I found while working around this solution is this:
http://chris-spittles.co.uk/?p=531
jQuery is all powerful and everything but sometimes a small dash of native JS is all you need to render pixel perfect pages... I hope you will find this solution helpful!
UPDATED:
None of the jQuery width-finding methods account for the scroll bar. In my original example, using .innerWidth(true) LOOKS like it works, but only because it returns and object, which causes width to fail and the inner contents size themselves to fit in the available space, because the example wasn't very good. However, it's possible to write a function to compute the available space in a div with a scroll bar in it, which can then be used to position the contents as you wish.
To write that function, I took advantage of the fact that, when a div is appended to a div with a scroll bar in it, it takes up the full available width (i.e. the inner width of the parent minus the width of the scroll bar).
The function looks like this:
function noScrollWidth(div){
var measureDiv = $('<div id="measureDiv">');
div.append(measureDiv);
var width = measureDiv.outerWidth();
measureDiv.remove();
return width
};
I then use this to size my content div:
$('#contentDiv').width(noScrollWidth($('#containerDiv')));
Working fiddle.
Try this:
$('#contentDiv').width($('#containerDiv')[0].clientWidth)
For more information about that solution, see this StackOverflow answer.
Another approach I'd try is setting both elements' box-sizing property to 'border-box', and see whether setting your contentDiv's width to 100% then works the way you want.
Now that fewer projects worry about crufty old browsers anymore, 'border-box' can make things easier to work with. Be sure to test multiple browsers on multiple platforms, though, because I'm not sure they all handle scrollbars the same way.

jQuery offset top doesn't work correctly

I'm trying to create an script draw something in an element by mouse and I'm using Raphaeljs to do that.
For correct drawing I need to find top and left of ‍input‍‍ element. I'm using var offset = $("#input").offset(); to get left and top.
But the top value isn't correct. It's 10px lower than ‍‍the real top distance. I think the 10px maybe change in different resolutions then I can't add 10px to it normally then I want to know how can I fix the problem!
I uploaded my test here.
The jQuery .offset() function has this limitation:
Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.
The body in this case has a 10px top border, which is why your drawing is off by 10 pixels.
Recommended solution:
var offset = $("#input").offset();
x = x - offset.left - $(document.body).css( "border-left" );
y = y - offset.top + $(document.body).css( "border-top" );
After fighting with this for a while and reviewing various potential answers I have concluded that jQuery offset().top (and presumably DOM API that it uses) is too unreliable for general use. Not only is it documented as excluding html level margins, but it also returns unexpected results in several other cases.
position().top does work, but it may not be practical / possible to design the page so that it is equivalent.
Fortunately I have found that element.getBoundingClientRect().top gets the position relative to the viewport perfectly. You can then add on $(document).scrollTop() to get the position from the top of the document if required.
I have two different solutions:
1) You can calculate above element's total height with outerHeight(true) method. This method will calculate height with margins, paddings and borders.
And this won't create conflict, it will return true value.
Here is jsFiddle example.
html
<div class="header"></div>
<div class="nav"></div>
<div class="myEle"></div>
jQuery
var myEleTop = $('.header').outerHeight(true) + $('.nav').outerHeight(true);
2) If you defined top css to the element which is postioned relative to the body, you can use this value too:
parseInt($('#myEle').css('top'));

Categories