Updating position of fixed element on scroll event on unresponsive page - javascript

I have a large page running a lot of javascript which also contains a fixed position floating element. The floating element updates its position based on the user's current scroll position, via a function which fires on the scroll event.
The issue I am having is that due to the size and complexity of the page, there is a delay before the code in the scroll event is executed, and this causes the fixed element to noticeably jump when scrolling quickly or using the mouse wheel.
See jsfiddle: http://jsfiddle.net/jorsgj2b/1/ (The use of setTimeout simulates the delay in executing the function on the real page.)
<div class="header"></div>
<div class="main"></div>
<div class="float"></div>
.header {
width: 100%;
height: 200px;
background-color: #787878;
}
.main {
width: 100%;
height: 1400px;
background-color: lightblue;
}
.float {
position: fixed;
width: 100px;
height: 50px;
top: 233px;
right: 25px;
background-color: red;
z-index: 2;
}
$(function() {
$(window).scroll(function() {
setTimeout(updateFloat, 50);
});
});
var updateFloat = function() {
var mainTop = $('.main').offset().top;
var scrollPos = $(window).scrollTop();
var floatOffset = 25;
var newTop = (scrollPos > mainTop)
? floatOffset + 'px'
: mainTop + floatOffset - scrollPos + 'px';
$('.float').css('top', newTop);;
}
I am at a bit of a loss as to how to resolve this. I have tried updating the margin instead of top position, as well as switching between absolute and fixed positioning. Perhaps there is a way to use css transitions to help, however I haven't managed to get them to work here.

You might add position: sticky to your css to that the stickiness is done by browsers that support it (only Firefox and Safari according to caniuse.com).
You'll always be limited to the fidelity of the scroll events so you may always see a bit of a delay, but you could improve things a little by caching values instead of looking them up each time updateFloat() is called. For example
var mainElement = $('.main');
var windowElement = $(window);
var floatElement = $('.float');
var updateFloat = function() {
var mainTop = mainElement.offset().top;
var scrollPos = windowElement.scrollTop();
var floatOffset = 25;
var newTop = (scrollPos > mainTop)
? floatOffset + 'px'
: mainTop + floatOffset - scrollPos + 'px';
floatElement.css('top', newTop);
}
The problem might also be related to browser trying to re-layout the page because the .float element is in the same render layer as the other divs. You can fix that by adding a style that tells the browser to put the .float element in its own render layer (resulting in much faster rendering due to GPU compositing). The most common trick is to add transform: translateZ(0); to your style, but there's also a proposed style will-change that is supported by several browsers. So you should update your css like this
.float {
will-change: scroll-position;
transform: translateZ(0);
position: fixed;
width: 100px;
height: 50px;
top: 233px;
right: 25px;
background-color: red;
z-index: 2;
}
Note that adding render layers increases memory usage so don't go overboard with it. It also sometimes impacts other features, like anti-aliasing of text.

Related

Mouse-Following Tooltip gets Farther Away the Smaller the Window

I've just revamped my tooltip code due to issues with the position altering depending on the size of it's parent (mostly due to using offsetX/Y instead of pageX/Y, but page was being weird, too). So I decided to just have one tooltip for each of my site's pages, parented to the main div, and just feed it different text depending on what the mouse is hovering over (I'll be dealing with the visibility part later).
And it's worked quite well so far, but the only issue is that, the smaller I make my window, the farther the tooltip is from my mouse, until it's not even in view anymore.
Here's the JavaScript coding I've done for it.
var body = document.getElementsByClassName("test");
var tooltip = document.getElementById("tooltip");
body[0].addEventListener("mousemove", tooltipMove)
function tooltipMove(event) {
var x = event.pageX;
var y = event.pageY;
tooltip.style.top = (y + -900) + "px";
tooltip.style.left = (x + -875) + "px";
}
The CSS coding for the tooltip:
.tooltip {
visibility: hidden;
width: 170px;
background-color: white;
background-image: url("images/tooltipbackground.png");
color: black;
text-align: center;
border-style: groove;
border-color: #f4bb4c #ffd966 #ffd966 #f4bb4c;
border-radius: 2px;
padding: 5px 5px;
position: absolute;
z-index: 1;
}
.notfound:hover .tooltip {
visibility: visible;
}
And the HTML:
<div class="test" style="top: 70px; position: relative; height: 100%; width: 100%;">
<h1>TEST</h1>
<img src="images/pagenotfound.png">
</div>
<div style="width: 1px; height: 1px; position: relative;">
<span class="tooltip" id="tooltip">testing</span>
</div>
I should mention the body's (which has the "notfound" class) height is 900px, and it's width 600px, in case that's one of the problems.
The 1 pixel div is just what I'm using to "host" the tooltip, not sure if it's causing any problems as well. I inspected the page in order to see it, and it never seemed to slide around with the window size.
Any sort of help would be greatly appreciated. I've tried to switch it from pageX/Y to clientX/Y, but it's the same issue. And using offset causes it's position to shift depending on what I'm hovering over, which is the reason I'm revamping the code in the first place.
I've also tried to change the tooltip's position from absolute to, well, anything else (after resizing it's parent so it doesn't get squashed), but that hasn't helped.
Another thing I should mention is that, for some reason, the shifting doesn't seem to happen in the Y axis, it's only when I squish the window horizontally that the tooltip shifts, at least from what I've noticed.
I had thought changing the tooltip's position to fixed had made it disappear, but I just couldn't see it due to the massive repositioning I had done to it. Once I deleted that it was visible and fine, and better yet, it stays in it's proper position no matter the screen size!
Also note: I had to change pageX/Y to clientX/Y, as using page made the tooltip shift vertically when squished.
<div style="height: 1px; width: 1px; position: relative;">
<span class="tooltip" id="tooltip" style="position: fixed;">Placeholder</span>
</div>
for (i = 0; i < tip.length; i++) {
tip[i].addEventListener("mousemove", tooltipMove)
tip[i].addEventListener("mouseleave", defaultVis)
}
function tooltipMove(event) {
var x = event.clientX;
var y = event.clientY;
tooltip.style.visibility = "visible";
tooltip.style.top = (y + -50) + "px";
tooltip.style.left = (x + -200) + "px";
}
function defaultVis() {
tooltip.style.visibility = "hidden";
}

Div following cursor paints pixels on screen in Safari (bug?)

I've used the following code to make a div that follows the cursor with easing applied to the movement:
CSS
#cursor {
position: absolute;
width: auto;
height: auto;
white-space: nowrap;
pointer-events: none;
transition: opacity 200ms;
cursor:none!important;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index:99999999;
color:white;
backface-visibility: hidden;
}
JavaScript/jQuery:
$(document).on("mouseover mousemove", function (event) {
mouseX = event.pageX;
mouseY = event.pageY - $(window).scrollTop();
cursorWidth = $cursor.width();
cursorHeight = $cursor.height();
});
requestAnimationFrame(performAnimation);
var performAnimation = function() {
var distX = mouseX - cursorX;
var distY = mouseY - cursorY;
cursorX = cursorX + (distX * speed);
cursorY = cursorY + (distY * speed);
$cursor.css({
left: cursorX + "px",
top: cursorY + "px"
});
request = requestAnimationFrame(performAnimation)
}
It works as intended in Chrome, but on Safari it leaves traces of the text in the div on top of the screen, i. e. the elements underneath the cursor z-index wise. Here's a video showing the behaviour.
Is this a known bug with Safari and can it be avoided somehow? I'm not sure if this has to do with the requestAnimationFrame() function or if it's something else. I tried applying backface-visiblity:none; to the #cursor itself through CSS, as this sometimes solves these type of issues, but in this case it's not doing anything.
The problem had to do with the #cursor being a child of a container that was fixed on top of the whole page. Removing this container and placing #cursor without a container on it's own fixed the issue.
For some reason I thought it was practical to have the cursor wrapped in this container so that I could add classes through JS to the container instead of the cursor itself to manipulate it's style. But I ended up adding the styling classes to a <span> inside #cursor instead.

How do I make one div scroll slower or faster than other items on the page, using pure CSS or CSS/JS (without JQuery)?

All I want is to do is to make one element on the page (a div is easiest) scroll slower or faster than the other items on the page. For example, when scrolling, this particular div will move at 50% or 200% of the speed of the other items, etc.
It seems like such a simple, straightforward thing, but I can't find any examples of this. Also, I don't want to use JQuery, someone else's sketchy / overly complicated 3rd party plugin, etc. Just simple, clean, CSS and JS.
Ok, so thanks #ajaypane for the answer, but I actually figured out an even simpler way of doing this. I can't believe that nobody has done this - it's far less complicated than everything else I've seen.
JS
function parallax() {
var s = document.getElementById("floater");
var yPos = 0 - window.pageYOffset/5;
s.style.top = 50 + yPos + "%"; }
window.addEventListener("scroll", function(){
parallax();
});
CSS
.section { position: relative; width: 100vw; height: 15vw; }
.object-in-3d {
margin-left: 45vw;
width: 10vw;
height: 10vw;
background-color: #41ebf4; }
.float-center {
position: absolute;
top: 50%; }
#red { background-color: #f44141; }
#yellow { background-color: #f48342; }
#green { background-color: #f4dc41; }
#floater {}
HTML
<div class="section" id="red"> </div>
<div class="section" id="yellow">
<div class="object-in-3d float-center" id="floater"> </div>
</div>
<div class="section" id="green"> </div>
It's in codepen, here:
https://codepen.io/escapetomars/pen/EeLmpp
So I have managed to come up with this which is not too complex, however, it does scroll relative to the users scroll speed, but does work with scroll wheel, scrollbars, and keyboard.
It also scrolls up and down.
You can change the speed to suit your needs, but 10 worked for keeping it pretty much in view all the way down for my scroll speed, but left it behind when faster or using Page Down.
document.addEventListener("DOMContentLoaded", function DomContentLoaded(){
//Get the element you want to slow down;
var slowDiv = document.getElementById('slowDiv');
//Set its style.top to be the offsetTop so if style.top is not set, it will still work.
slowDiv.style.top = slowDiv.offsetTop + 'px';
//set the last scrollTop to use for direction
var lastScrollTop = 0;
//Get the element you are scrolling against
var relativeSpeedDiv = document.getElementById('main');
var moveLittle = function MoveLittle(speed, scrollY) {
//Get the current top of the slow element
var topVal = parseInt(slowDiv.style.top);
//Check scroll direction
if (isScrollingDown(scrollY)) {
topVal = topVal + speed;
} else {
topVal = topVal - speed;
}
//Set new top of slow element
slowDiv.style.top = topVal + 'px';
};
var isScrollingDown = function IsScrollingDown(scrollY) {
var retVal = false;
if (scrollY > lastScrollTop) {
retVal = true;
}
lastScrollTop = scrollY;
return retVal;
};
window.onscroll = function WindowScroll() {
//Send speed and current scroll Y
moveLittle(10, this.scrollY);
}
});
.biggestBig {
margin: auto;
align-self: center;
width: 90%;
min-height: 9999em;
}
.faded {
background: linear-gradient(gray, black);
}
.slow {
width: 2em;
height: 2em;
background-color: #ee9b0b;
position: absolute;
}
<div id="mainDiv" class="biggestBig faded">
<div id="slowDiv" class="slow"></div>
</div>

How to user controlled overlap images in JS

I'm desperately searching for solution for my client. I have graphic - something like that:
And I want to be able to take the line with circle in the center and drag it to right or left. And it will be hiding and unhiding my two full images. It's basically two images on the same place, just with another z-index I think.
I think it's possible to do it with JavaScript, but I don't know of any functions or methods for this option.
Here is my solution:
The HTML is pretty simple, just two divs for the images and one for the drag:
<div class="img" id="img1"></div>
<div class="img" id="img2"></div>
<div id="drag"></div>
For the CSS, the important part is to absolute position all the divs and give a background image.
As for the Javascript, with a little help from jQuery, we listen for the mouse events, make some calculations and adjust the CSS of the second image:
$('#drag').on('mousedown', function(e){
var $self = $(this),
dragPos = $self.position().left + $self.width()/2,
imgWidth = $('#img1').width();
$(document).on('mouseup', function(e){
$(document).off('mouseup').off('mousemove');
});
$(document).on('mousemove', function(me){
var mx = me.pageX - e.pageX + dragPos
$self.css({ left: mx });
$('#img2').css({
width: imgWidth - mx,
left: mx,
backgroundPosition: -mx + 'px 0px',
});
});
});
From there, I believe it's pretty easy to customize it and give it a unique look.
Hope this helps!
JsFiddle Demo
Something like this alphamask plugin may do the trick, though I'm not sure how simple it would be for you to implement in the manner of your slider example.
Actually quite simple. The first step is to make it work manually. I'd set it up as follows:
<div class="wrap" id="wrap1">
<div class="img-wrap img1"></div>
<div class="img-wrap img2"></div>
<div>
With CSS as follows:
.wrap {
position: relative;
width: 300px;
height: 300px;
}
.img-wrap {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
.img1 {
z-index: 1;
background: url(bg1.png) no-repeat 0px 0px;
}
.img2 {
z-index: 2;
background: url(bg1.png) no-repeat 0px 0px;
}
Now some JavaScript (with jQuery) to set a position (you can call this when you move a slider over the top later):
function setPosition(percentage){
// get the width of the container
var w = $('#wrap1').width();
// work out the width of left panel
var w1 = Math.floor(w * percentage);
// and the right panel
var w2 = w - w1;
// set the width of the right panel
// move it right by the width of the left panel
// and move the background back by the width of the left panel
$('#wrap1 .img2').css({
width: w2,
left: w1,
backgroundPosition: -w1 + 'px 0px',
});
}
You now just have to decide how to do the dragging. You could even just do it on mouseOver. Easy!

Switch div from fixed to absolute at bottom of browser

Im trying to add a footer at the bottom of this content that doesn't overlay the content but moves it up.
The only way I can see it working would be something like, when browser is at the bottom remove 'fixed' class on the left red '#work'.
js fiddle DEMO
Updated js fiddle DEMO
HTML
<div id="header-block">
Header-block, this sits here in the background
</div>
<div id="content">
<div id="work">
This content should be fixed when at the top
</div>
<div id="description">
This content should scroll -
</div>
</div><!-- end content -->
<div id="footer">
This should appear at the bottom
</div>
CSS
body {
margin: 0px;
padding: 0px;
}
#header-block {
background: green;
width: 100%;
position: fixed;
z-index: 1;
height: 300px;
top: 0;
}
#content {
margin-top: 300px;
width: 100%;
position: relative;
z-index: 2;
}
#work {
background: red;
width: 50%;
height: 100vh;
float: left;
position: absolute;
}
#description {
background: blue;
width: 50%;
height: 1200px;
float: right;
font-size: 30px;
}
#footer {
background: black;
width: 100%;
height: 100px;
position: absolute;
z-index: 3;
bottom: 0;
}
If I understand your question correct, this should do the trick (although it depends very much on JavaScript unfortunately).
// Fix work column on scroll
contentStart = $("#content").offset().top ;
contentSize = $("#content").height() ;
window.onscroll = function(){
if( window.XMLHttpRequest ) {
var position=window.pageYOffset;
// calculate the position of the footer and the actual seen window
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $("#footer").offset().top;
if ( position > 300 && !(docViewBottom >= elemTop)) {
$('#work').css({'position':'fixed', 'top':'0', 'height':'100vh'});
} else {
// if the footer is visible on the screen
if(docViewBottom >= elemTop) {
$('#work').css({ 'top': 0 - (docViewBottom - elemTop) }); // scroll the #main div relative to the footer
} else {
$('#work').css({'position':'relative', 'top': 'auto'}) ;
}
}
}
}
For further informations about the calculations, perhaps this question on stackoverflow is useful.
Edit: Andrew Haining posted his answer in between of my answer, perhaps give his link a try and maybe it's a better (more proper) solution. Unfortunately I haven't actualised this page when I was testing your code in JSFiddle and I didn't see his answer.
If you want to use my script, make sure you can test it with different resolutions. It works just fine for my resolution in JSFiddle, I didn't test any other.
I'm not 100% sure what you want, but if you remove the position: absolute and the bottom: 0 from the footer, and put a div with class='clearboth' above the footer, it seems to do what you need.
CSS
.clearboth {
clear: both;
}
This is a drawing of what I see on your fiddle;
Do you want the red and the blue to always be touching the black?
I don't see the red overlying the black
You should use jQuery to add a class containing the position:fixed value when the scroll position of the page is less than the inline position of the #work div. Once it scrolls past the position, remove the class and have the element fall back in line.
You can achieve this using the following jQuery methods.. .scrollTop() .offset().top() and $(window).height().
This tutorial will give you an understanding of what you need to do to achieve the necessary results, you will just have to change the calculation slightly using $(window).height(), $('#footer').height() and a few other changes to get what you desire.
Based on the question you asked i think this is what you mean. The red div should be fixed when it gets to the top but be absolute when it is below the top for scrolling and the black footer should be below the red while scrolling, check this code i have done for you. just add this jquery script and run it.
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function() {
$(window).scroll(function () {
console.log($(window).scrollTop());
if ($(window).scrollTop() >= 322) {
$('#footer').css("z-index","1");
$('#work').css(
{
"background": "red",
"width": '50%',
'height': '100vh',
'float': 'left',
'position': 'fixed',
'top': '0'
});
}
if ($(window).scrollTop() <= 322)
{
$('#work').css(
{
"background": "red",
"width": "50%",
"height": "100vh",
"float": "left",
"position": "absolute"
});
};
});
});
</script>
If not exactly a parallax, this is somewhat close to how parallax works, containers moving at different speeds, and some containers sitting fixed or scrolling when they attain a particular top/bottom offset in the viewport.
There's plugin that can do it. Skrollr
You can use Skrollr along with skrollrcss, and it'll make sure how the containers take position on screen based on scrolltop of the window and the container specifically.

Categories

Resources