I have a jQuery var that sits within an .on('scroll') method. The var is detecting the top position of a div, that has a position of absolute. However, on scroll, the position changes to fixed, which results in the value changing (which I do not want), instead, I want to lock in the original value of the variable.
So, for example, if fixedTop has an initial value of 500, how can I lock that value in, regardless of the fact that the value changes on scroll due to it having a position of fixed?
Thanks.
$(window).on('load scroll resize', function() {
// Vars
var fixed = $('.mydiv');
var fixedTop = fixed.offset().top;
}
Simply move those variables OUTSIDE of the scroll listener and remove the load event from the event listener also.
$(document).ready(function(){
var fixed = $('.mydiv');
var fixedTop = fixed.offset().top;
$(window).on('scroll resize', function() {
console.log(fixed, fixedTop)
});
});
Related
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.
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!
I'm using window.onresize to calculate the appropriate coordinates for my buttons on my page. The buttons are placed in the div called <div>trinity</div>. The coordinates of the buttons are relatively calculated according to the height and width of the "trinity" div.
The trinity div resizes correctly when the window is being resized, but the inner code of the window.onresize = function () doesn't seem to fire off. In other words my xml_button_create(window.myValue,height,width,false) isn't firing off. In this function I use jQuery to adjust the coordinates of my buttons.
Any help would be appreciated.
Here is my code.
window.onresize = function () {
// get HEIGHT and WIDTH of navigation div
var height= $("#trinity").height();
var width= $("#trinity").width();
// CREATE BUTTONS
xml_button_create(window.myValue,height,width,false);
};
If you are using jQuery to adjust the coordinates, try to use it for the eventbinding too.
$(document).ready(function() {
$( window ).resize(function() {
alert("Resize");
});
});
Otherwise have a look at this to detect resize on all html elements.
http://benalman.com/projects/jquery-resize-plugin/
With jQuery resize event, you can now bind resize event handlers to elements other than window, for super-awesome-resizing-greatness!
I have a button back-to-top that is affixed to the left side of the screen - it uses scrollTop to slide-scroll to the top of the page when it's clicked. When the page the loads, the button is visible and does not cover anything that is readable etc.
When a user scrolls down the page, the button goes over certain DIVs that have text content. When the button goes into such a DIV I want it to hide using .hide(). Can't get it to work, here's what I have:
var p = $('a.back-to-top');
var position = p.position();
if(position == $('#about-me')){
$('a.back-to-top').hide();
}
Is if(position == $('#about-me')) the correct way to check if the button's position is in the #about-me DIV? Or, should I create a variable similar to position for the DIV?
EDIT: A messy but simple fiddle
You will need to do this check inside of a callback .. probably $(window).scroll so that it is checked each time the window scrolls; otherwise, it is only checked when the page loads.
I don't think you want to use position either as that is position relative to parent. Instead, you probably want .offset. This returns an object with top and left members. An == comparison does not make sense, especially to a jQuery object. You want to use:
$(window).on('scroll', function () {
var offset = $("a.back-to-top").offset().top;
var within = $("#about-me").offset().top;
if (offset >= within && offset <= within + $("#about-me").height()) {
$("a.back-to-top").hide();
}
else {
$("a.back-to-top").show();
}
});
The offset of .back-to-top changes with scrolling if it has a fixed position, but the offset of the static block does not change, so you can do this comparison.
See it in action: http://jsfiddle.net/QnhgF/
http://api.jquery.com/position/ - position() method returns a position object which has .left and .top properties. So basically, you can't compare position to some object returned by a selector. Instead, you should compare the "top" property values of both elements.
For example you have:
var p = $('a.back-to-top');
var position = p.position();
Also get this:
var aboutMePosition = $('#about-me').position();
And then you can compare:
aboutMePosition.top and position.top whichever way you need.
I'm using the following code to allow users to resize a DIV element vertically, but when the click and drag the handle, text and other elements on the page get selected as if the user was just clicking and highlighting everything on the page. Is there a way to prevent this from happening as this looks very bad? This is being used with Prototype.js.
function DragCorner(container, handle) {
var container = $(container);
var handle = $(handle);
// Add property to container to store position variables
container.moveposition = {y:0};
function moveListener(event) {
// Calculate how far the mouse moved
var moved = { y:(container.moveposition.y - event.pointerY()) };
// Reset container's x/y utility property
container.moveposition = {y:event.pointerY()};
// Update container's size
var size = container.getDimensions();
container.setStyle({height: size.height + moved.y + 'px'});
}
// Listen for 'mouse down' on handle to start the move listener
handle.observe('mousedown', function(event) {
// Set starting x/y
container.moveposition = {y:event.pointerY()};
// Start listening for mouse move on body
Event.observe(document.body,'mousemove',moveListener);
});
// Listen for 'mouse up' to cancel 'move' listener
Event.observe(document.body,'mouseup', function(event) {
Event.stopObserving(document.body,'mousemove',moveListener);
console.log('stop listening');
});
}
Following up your earlier question and answer, add a small handle element and make it as the only element that can be selected and draggable. Also I guess you made that div's position as relative and handle position as absolute. Right??
Adding the following to the DIV fixed this:
onselectstart="return false;"