scrollTop value doesn't correlate to actual pixels - javascript

I'm having an issue with the scrollTop property in JavaScript and was hoping someone could help. According to MDN, the value corresponds to a pixel offset, which makes sense. What I'm having trouble with is the fact that it doesn't seem to be that simple. Here's a Codepen example: http://codepen.io/anon/pen/vGJZMV
I want to create a shrinking header effect in which the header shrinks up to a certain point upon scroll and then stops. Sounds simple enough (and should be). I'm listening to the 'scroll' event on my scrollable element and subtracting the value from the maximum header height, with some conditionals ensuring it stays between my desired amounts. I'm not using any kind of scalar multiplier on my difference function so, in my mind, there should be no parallax scrolling effect happening between the scrollable area and the header (though in my example, there clearly is). Any ideas?
EDIT:
To better clarify the problem, I want the header to shrink at the same rate the text scrolls so that the text does not go behind the header until the header is at its minimum height. The way it is now, the vertical translation of the content box effectively causes the text to move twice as fast as its scrollTop value because it's both scrolling and translating.

If by "parallax scrolling effect", you mean that the header shrinks slower than the content scrolls, then it is because of your CSS. In your CSS, you have a line that says transition all 0.3s ease for your header. This means that all properties will not have changes apply immediately, but will "animate" for 0.3s with an easing. Every time you change header height, it would take 0.3s, regardless of whatever is happening in the rest of the world.
If you remove that line, header should shrink at the same rate as your content.

After realizing what the real issue was (the text container translating vertically while also scrolling), I was able to resolve it by padding the top of the content container by the scroll amount, thereby pushing the text down to compensate for the container's vertical movement. This updated pen shows the result, in case anyone is interested:
http://codepen.io/sunny-mittal/pen/LNjgEK
The relevant changes to the previous code are surrounded with asterisks:
header.on 'scrolling' (_, howmuch) ->
if howmuch is 0
header.css 'height' 150
**content.css 'padding-top' 0**
else if howmuch >= 50
header.css 'height' 100
**content.css 'padding-top' 50**
else
header.css 'height' 150 - howmuch
**content.css 'padding-top' howmuch**

Related

How to trigger an image to move when users scroll the page?

Is there any way to make an image move up when users scroll the page? I have 2 square images (each 400px in wide and height), both are visible. The left image is fixed by position. The right image is positioned 200px below the left image. I need to make the right image to move up by 200px (get aligned with the left image) when we scroll the page. Then the it stays still on that position.
I found the one on this page is quite the same with what I'm trying to create http://jessandruss.us/#waiting The difference is my images are all visible, while on this page the overflow of the left image is hidden and it gets back to its original position when users scroll up.
Really appreciate any help on this matter. Thank you.
$(document).ready(function(){
var aligned = false; // A flag to tell us when the images are aligned
$(window).scroll(function(){
if($(this).scrollTop() == 192 ) { // when the window scroll to the alignment point...
aligned = true; // the images are aligned
}
if (aligned) { // if they're aligned...
$(".image-2").css("top", 8 + $(this).scrollTop()) // match .image-2's top css property
} // to the window's scrollTop value, +
// 8px for the body's margin.
})
})
Here's a JSFiddle with what I think you want.
There's simply a boolean to tell us when the images are lined up. When they are, image-2's CSS property 'top' is matched to the window's scrollTop value.
The boolean variable is currently hard coded to tell us when the images are lined up (I looked at the window's scrollTop value when they were lined up, 192 in this case). This isn't a great approach since it won't account for changes in the images' positions or sizes, but this should be enough to get to going.
EDIT
https://jsfiddle.net/eLdo0s3w/5/
Here's another method to achieve the same result. As long as having the second image position: fixed is OK, then it should be more efficient, and will hopefully avoid the jumping around that OP says happened with the first method.
It targets image-2's top CSS property and matches it to the window.scrollTop value, until image-2 reaches the necessary point.
Again, this code isn't very reusable, but it should work fine for a one-off situation. If anyone wants improve on it, please do so!
Sounds like you need to use jQuery to link the picture's transform: translateY() property with scrollTop(). It's a little hard to explain in words, but if you provide a jsfiddle I'll show you what I mean.

How to obtain clientWidth & clientHeight before DIV is visible

I want to obtain the dimensions of a DIV element (used to display a popup menu at the cursor position) while it's style.display='none;', however the dimensions of the DIV always return 0. The only way I seem to be able to get the dimensions is to make the DIV style.display='block;' at 0,0 and then move it to the required position, but that looks jumpy.
I've tried making the DIV visible outside of the visible screen area but that doesn't work. Is there a way to get the clientWidth and clientHeight values whilst the DIV is hidden?
If your DIV is not visible, you won't be able to get its dimensions.
However, there is a workaround. Your div has to be "visible", but that doesn't mean it's opacity and position have to be 1 and relative.
Set the opacity to 0 and the position to "absolute" and you'll be able to get the DIV dimensions.
EDIT
Since I think more people will have a similar problem, I feel I should explain my answer a little more.
If you try to get the size of a hidden element with JavaScript, you will always get 0.
So there are techniques to get the real size without displaying the element to the user. My favourite is the one I already wrote about above. Here are the more detailed steps:
you set the elements opacity to 0. This way it won't be displayed to the end user while you are getting the dimensions.
you set the element position to "absolute". This way it won't take up any space.
now it's safe to set the display to "inline-block".
you read the elements dimensions. This time you'll get the real values.
You set the display back to "hidden" and set the opacity and position back to its original values.
And now you have the size of a hidden element.
If you'd like to know the size of an element onscreen without it being visible you need it to be painted to the screen but not shown.
In order to get clientHeight and clientWidth you need it to be rendered so the calculations can be performed based on the screens current state (unless you have pre-programmed width and height, which I'm guessing you don't)
you can find out more information at MDN here
So you have options:
create your div offscreen using positioning (fixed or absolute) combined with z-index or opacity
use width: 0 and height: 0 and overflow: hidden then use scrollHeight and scrollWidth to find the overflow size
choose which option is best for your site, considering things like responsiveness and screen reflows and repaints

width of dynamically inserted div containing text

I have a script that dynamically inserts a div containing text in the dom. The text content is not known in advance.
I need to know the width of this div, but it seems that that the return value of document.defaultView.getComputedStyle(node, "").getPropertyValue("width") or node.offsetWidth cannot be trusted.
I used setInterval to log it, and the value changes over time. For instance, in my case it starts with 929px and then changes to 908px.
This div is in position absolute, it has whitespace nowrap, so I don't think it is being "pushed" by other dom elements or that it somehow changes once inserted.
Is there an elegant way to retrieve the width, or do I have to use an ugly setTimeout to retrieve it once the return value is stable ?
Try:
yourDOMElement.getClientBoundingRect()
This will return an object with top, left, right, bottom, height and width attributes. This should be cross-browser.
Note: If you are going to work with the position attributes (top, left, right, bottom, height) of the returned, take into account scroll offset if necessary.
Update: To ensure this works on older browsers that don't have the width/height attribute, calculate it subtracting right/bottom from left/top.
The viewport can change its size because of the scrollbar. Once the scrollbar appears, its width can no longer be used by the document. Force the scrollbar to exist before you measure the size by adding overflow: scroll or overflow-y:scroll to the <html> element.
The size of a block-level element is, by default, its container width minus margins and padding (even if it's positioned absolutely), which is ultimately the wiewport width unless you set a fixed width somewhere along the way.
Using jQuery, you should be able to do this:
var width = $("div-selector").width();
this is fairly easy?
open the page in a browser and press f12. With firefox there is a button "inspect element" on top and in chrome it's on the bottom. Click it and hover your mouse over it. This should give you the height and width in px. Never been wrong for me.
if it still doesn't show, click it and you can see it in the css panel of the console.

Applying position:absolute to a style via jQuery fails to center div horizontally upon first page load

This is a followup to my question here. I would like to understand why applying position:absolute to the CSS of a div via jQuery fails, while applying it in a static style works. Here are two jsfiddle examples:
Works: http://jsfiddle.net/jasper/Ty6Af/2/
No worky: http://jsfiddle.net/Ty6Af/3/
Note that the only difference between the two is where I apply position:absolute. Vertical centering always works, but horizontal centering does not work when the page loads for the first time. If you manually re-size the window the div will center correctly.
All of my testing has been on Chrome under Ubuntu thus far.
Anyway, I'm just now delving into the world of web development and these are exactly the kinds of 'quirks' that I need to begin understanding.
EDIT:
#Jasper found something interesting. If you make two calls to .css(), first applying position and subsequently applying a margin, it works. I would love to understand why. Here is an example: http://jsfiddle.net/jasper/Ty6Af/5/
So the issue is with how the width of the div is calculated by the browser depending on its position.
If the div is set to position : static (by default) then it's width is 100% of it's parents width and the element is not allowed to move around the page.
If the div is set to position : relative then it's width is 100% of it's parents width but it can be moved around with left.
If the div is set to position : absolute then its width is determined by the actual content of the div, for instance if there is only a 200px wide <span> element within the div then the div will be 200px wide.
You can test these observations by changing the CSS of your jsfiddle to specify position : relative (etc...) and remove the JavaScript that makes the div position : absolute, then use your Developer Tools to inspect the element and it's calculated width.
The problem with your code is that it sets the position : absolute at the same time it sets the margin of the element by using its width/height (which are calculated differently depending on the position of the element).
If you want to set the position of the div in JavaScript then you can do something like this:
$(function() {
//notice I cached the selector so it can be used in the future as well as set the position of the div
$signuparea = $('#signuparea').css({position : 'absolute'});
$(window).resize(function() {
$signuparea.css({
'margin-top' : '-' + Math.round($signuparea.height() / 2) + 'px',
'margin-left' : '-' + Math.round($signuparea.width() / 2) + 'px',
});
}).trigger('resize');
});
Here's a jsfiddle: http://jsfiddle.net/jasper/Ty6Af/8/
I believe the problem is that when you apply your left and right in your second fiddle, you have yet to add position absolute to the div. Hence, the browser has no idea what do with the left and right values and ignores them initially.
Practically speaking in your second fiddle, you only actually add the position:absolute on the resize trigger. So before you resize your actual div has no positioning.
If you instead add the position absolute on load it works fine:http://jsfiddle.net/Ty6Af/9/
Notice that if you give it position:relative from the start (like this http://jsfiddle.net/Ty6Af/11/ ) it allready applies both the left and right value. The reason you can't actually see the effect of "left" is because it is a block element.
I hope that answers your question, I'm not quite clear on where you are stuck.
http://jsfiddle.net/Ty6Af/7/ this should work, the trigger function in jquery has bugs with chrome so you have to run the function on load too.
The problem seems to be that position:absolute; negates the current layout and requires you to position it.....
See: http://jsfiddle.net/ZHaRD/
Which Jasper explains much more eloquently than myself!

Change CSS width using javascript (JQuery Tools Scrollable) center

I am using JQuery Tools Scrollable to build a full-page-width scrollable form, such that each page of the form scrolls all the way across the page, replaced by the next page sliding in from the right.
The problem I'm having is how to center each page such that it stays centered amidst browser resizing and in-browser zooming (Ctrl +/-). My code is based upon: http://flowplayer.org/tools/demos/scrollable/site-navigation.html
I've tried encasing my code in a div like this:
<div style="margin-left:-440px; padding-left:50%; width:50%; min-width:880px;">
But, because this div is itself positioned in the middle of the page, the scrolling pages don't slide all the way to the left edge - they cut out at the div's edge about 30% away from left, which looks bad.
The only conclusion I can think of is to dynamically alter the margin-left I've defined on div class="items" to make sure it's always equal to 50% - 440px but no less than 0.
How can I do this using javascript?
is the container div absolute or relative positioned? If it has a specific width, let's say "800px", then centering it horizontally is easy with auto margins on left and right, e.g. margin: 0 auto. Otherwise it gets tricker.
If you want to respond to resize in Javascript, in jquery I do something like $(window).resize(function() {}) (docs here) and inside of the handler function update some value in CSS. If you just want to increase the width but still have auto-margins, you could select your div and update the width property, e.g. $('.mydiv').css('width', '900px');. This would fire any time the window is resized.

Categories

Resources