Update position of div while scrolling - javascript

For another stack question I have tried to write a short script. It should track the position of a div .list_item while scrolling and apply the .offset().top to another div.
To test if the function is fired I have written a console.log inside my code, which was never seen again. Why does my function do not fire while scrolling?
$(document).ready(function() {
// fire function everytime the window is scrolled
$(window).scroll(function(){
// set element to relate to
var list_items = $('div.list_item');
// get each position
list_items.each(function() {
// store offset().top inside var
var list_item_position = $(this).offset().top;
// select previous dropdown_list item
$(this).prev().find('ul.dropdown_list').css({
// apply offset top
top: list_item_position + "px"
});
});
// write to console to track changes
console.log('positions updated');
}); // .scroll
}); // document.ready
Suggestions appreciated!
JSFIDDLE DEMO

As pointed out by #Carlos Delgado in the comments, $(window).scroll tracks, if the windows is being scrolled, while setting the first line to $('#wrapper').scroll tracks, if the #wrapper is being scrolled, which works perfect.
Thanks for pointing this out and the other helpful comments!

Related

Javascript Sticky Element onscroll avoid jumping

I'm trying to fix an element when I scroll down.
The code works fine but as you can see at the following link, the bar with the 3 yellow buttons jumps when it is about to reach the Top!
There seems to be some template css class causing this problem,
but I can't figure out which one
This is the code
var fixmeTop = $('.pulsanti').offset().top;
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
if (currentScroll >= fixmeTop) {
$('.pulsanti').css({
position: 'fixed',
top: '0',
zIndex: '1020'
});
} else {
$('.pulsanti').css({
position: 'relative'
});
}
});
thank you everyone
I think the problem is that fixmeTop is assigned before some elements are loaded:
var fixmeTop = $('.pulsanti').offset().top;
My chrome console outputs this:
> fixmeTop
< 2314.3374633789062
> $('.pulsanti').offset().top;
< 3207.5623779296875
You can see that the fixmeTop variable is not the real element position.
Maybe you need to assign it in body.onload()?
Update
After executing fixmeTop = $('.pulsanti').offset().top; in the chrome console after the page is loaded, I can verify that the element is sticking smoothly to the top of the page.
Adding this code fragment will create a handler function to be called when the window's load event fires. That will happen after everything (divs, images) is loaded. This way the fixmeTop will contain the true element position.
window.onload = function () {
fixmeTop = $('.pulsanti').offset().top;
}
You can keep the variable declaration in the original script, or remove it and add var here.
Also, bear in mind that it will not work until everything on the page is loaded and that it will not be valid when anything on the page moves - eg. page resize, divs rearranged. You would have to add listeners for every such event to adjust the value accordingly. Something like this may be useful:
function updateFixmeTop() {
fixmeTop = $('.pulsanti').offset().top;
}
window.addEventListener("resize", updateFixmeTop);
edit: changed element body to window in event listener
Hope it helps!
Update2
Let's say you added the code for resize event listener and scrolled past the point where the element should stick to the top. If you were to resize window fixmeTop would be assigned a value that corresponds to the element being on top of the page, and not the original element position.
To fix this you may want to add a dummy element without any margin or padding:
<div id="elementJustBeforeFixmeTop"></div> <! -- dummy element -->
<div class="pulsanti"> <! -- sticky element -->
...
</div>
And refer to its position instead of the sticky element
fixmeTop = $('#elementJustBeforeFixmeTop').offset().top;
This way you will store the scroll position at which you want the element to stick and it will not be different if the element is already at the top.
You may want to check if your page doesn't change its layout somewhere else and also update the fixmeTop value there to ensure it's always pointing at the right element.

Move mouse to trigger a hover event in CasperJS

I can't understand, why mouse::move() doesn't work. For example on this page.
As you can see, there are 10 elements and after moving mouse cursor at the every picture you will see detailed information. I have a set of every element id. I want to move cursor on every element, then selector "div#hover_item_descriptors" will be updated and I will work with it. It's my code:
this.eachThen(ids, function(resp){
var id = resp.data;
this.then(function(){
this.mouse.move('span#' + id + '_name'); //moving at the name of element
});
this.waitUntilVisible('div#hover_item_descriptors div#sticker_info', function(){
// it`s never work, because moving doesn't work
});
});
Why does it not work?
I'd stumbled at this too, figured it out thanks to this issue: https://github.com/n1k0/casperjs/issues/208
It turns out if you are hovering cursor over an element that is not in the viewport, hover event won't work.
So, to make it work, set viewport height that is guaranteed to exceed page height, for example:
var casper = require('casper').create({
viewportSize : { width: 1280, height: 5000 }
});

Jquery scroll problems

I have some uncommon wishes about scrolling in the page I'm making. I already tried a lot of things, but those aren't working like they should. All I want is that when people use their scroll wheel (wherever their cursor stands) the search-results are scrolling.
I've uploaded my result so far at http://www.veylau.be/testzone/scrollfix/searchtwee.html
Just click the search button to see the dummy results.
Problems:
1) With the script I'm using now I'm having a sort of a parallax effect. I just want the results to scroll, not the rest of the page.
2) When the rest of the page is done scrolling, it isn't possible to scroll through anymore.
3) is it possible to catch the scroll-event when the cursor is over the #googleMap or the #mapContainer div? I tried like this, but only the second one is executing.
$("#mapContainer").scroll(function(event){...});
$(window).scroll(function(event){...});
Thank you very much for your help guys!
You can catch the $(window).scroll(function(event){...}); and inside this function check if the mouse is hover the mapContainer with the check if($("#mapContainer:hover").length>0)
You can do something like tracking the mouse movement , and when scroll occurs setting the position to the last known position
I have tried a sample, Here is my code , Not perfectly refined. still i think this may help
var MouseposX;
var MouseposY;
$(window).bind("mousemove", function (event) {
MouseposX = event.pageX;
MouseposY = event.pageY;
});
$(window).scroll(function (event) {
placeDiv(MouseposX, MouseposY);
});
function placeDiv(x_pos, y_pos) {
var d = document.getElementById('searchResults');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
}
Check the fiddle
http://jsfiddle.net/46WLt/3/

css scrollLeft animate moves body vertically

Hi I am trying to write a function that horizontally scrolls a div to a specific point given a parameter. Everything functions properly except when the document/body is scrolled down and the function is executed by pressing a letter. When this happens the whole document/body is scrolled up to the top. I really can't figure out what I am doing wrong here but I don't want the page to scroll to the top.
an example of the code can be found at http://www.hokosounds.com/testRedesign/store-test.html#
Thanks for the help!
$(document).ready(function(){
$('a').click(function(e, _letter){
e.preventDefault();
var _letter = $(this).html();
scrollToLetter(_letter);
});
scrollToLetter = function(_letter) {
var _distance = $('#'+_letter+'Start').position().left+$('#store-nav-artist-names').scrollLeft();
$('#store-nav-artist-names').animate({
scrollLeft: _distance
}, 800);
};
});
The page will scroll to the top if you don't handle the click event to either return false or event.preventDefault http://api.jquery.com/event.preventDefault/
It will stop the behavior of a link being clicked.

javascript bind an event handler to horizontal scroll

Is there a way in javascript to bind an event handler to a horizontal scroll as opposed to the generic scroll event which is fired when the user scrolls horizontally and vertically? I want to trigger an event only when the user scrolls horizontally.
I searched around for an answer to this question, but couldn't seem to find anything.
Thanks!
P.S. My apologies if I'm using some terminology incorrectly. I'm fairly new to javascript.
UPDATE
Thanks so much for all your answers! In summary, it looks like you are all saying that this isn't supported in javascript, but I that I can accomplish the functionality with something like this (using jQuery) (jsFiddle):
var oldScrollTop = $(window).scrollTop();
$(window).bind('scroll', function () {
if (oldScrollTop == $(window).scrollTop())
//scrolled horizontally
else {
//scrolled vertically
oldScrollTop = $(window).scrollTop();
}
});​
That's all I needed to know. Thanks again!
Answering from my phone, so unable to provide code at the moment.
What you'll need to do is subscribe to the scroll event. There isn't a specific one for vertical/horizontal.
Next, you'll need to get some measurements about the current display area. You'll need to measure the window.clientHeight and window.clientWidth.
Next, get window.top and window.left. This will tell you where position of the viewport is, ie if it's greater than 0 then scroll bars have been used.
It's pretty simple math from here to get what you need. If no one else has provided a code example in the next few hours I'll try to do so.
Edit:
A bit further information.
You must capture the scroll event. You also need to store the initial window.top and window.left properties somewhere. Whenever the scroll event happens, do a simple check to see if the current top/left values differ from the stores value.
At this point, if either are different you can trigger your own custom events to indicate vertical or horizontal scrolling. If you are using jQuery, this is very easy. If you are writing js without library assistance, it's easy too but a little more involved.
Do some searches for event dispatching in js.
You can then write any other code you want to subscribe to your custom events without needing to tie them together with method calls.
I wrote a jQuery plugin for you that lets you attach functions to the scrollh event.
See it in action at jsfiddle.net.
/* Enable "scrollh" event jQuery plugin */
(function ($) {
$.fn.enableHScroll = function() {
function handler(el) {
var lastPos = el
.on('scroll', function() {
var newPos = $(this).scrollLeft();
if (newPos !== lastPos) {
$(this).trigger('scrollh', newPos - lastPos);
lastPos = newPos;
}
})
.scrollLeft();
}
return this.each(function() {
var el = $(this);
if (!el.data('hScrollEnabled')) {
el.data('hScrollEnabled', true);
handler(el);
}
});
}
}(jQuery));
It's this easy to use:
$('#container')
.enableHScroll()
.on('scrollh', function(obj, offset) {
$('#info').val(offset);
});
Please note that scroll events come very fast. Even if you click in the scrollbar to jump to a new position, many scroll events are generated. You may want to adjust this code to wait a short time and accumulate all the changes in position during that time before firing the hscroll event.
You can use the same scroll event, but within your handler use the scrollLeft function to see if the scrollbar moved horizontally from the last time the event was fired. If the scrollbar did not move then just return from your handler. Otherwise update your variable to the new position and take action.
You can check if the the x value of the page changes and ignore your y value.
If the x value changes: There is your horizontal scroll.
With page-load, store the initial scrollbar positions for both in two variables (presumably both will be 0). Next, whenever a scroll event occurs, find the scrollleft and scrolltop properties. If the scrollleft property's value is different and scrolltop's value is same as compared to their earlier values, that's a horizontal scroll. Then set the values of the variables to the new scroll values.
No, there is no special event for scroll horizontal (it is for global scroll), but you can try to check the position of content by property .scrollLeft and if it's different from the previous value it means that the user scrolled content horizontally.

Categories

Resources