real-time resizing in Parallax Scrolling - javascript

I was using the stellar.js in my project.
There is a question - under the "realtime resize" requirement( do not reload page ).
when I using the resize function to calculate the new position LEFT in horizontal scrolling below:
$(window).resize(function(){
var newPos = element.position().left*100; //Get NEW Position ...
element.css("left", newPos); //It's not working ...
});
the elements with "data-stellar-ratio" will not be overwrite.
How do i do to slove this problem ?
Thanks for your help.
Under the requirement below
-> When resizing browser then recalculate the element position in real-time ( NO Reload page )
-> So, I will recalculate position and overwrite new position to element.
-> But, the element which use data-stellar-ratio attribute can not be overwrite new position.(example in comment)
here is my problem. thank you for your help again.

Your question is very unclear. But, if you wish to change the data-stellar-ratio attribute, you would do it like this.
element.attr('data-stellar-ratio', 2);
element must be a jQuery object.

To you refer
_repositionElements: function() in stellar.js
if (this.options.horizontalScrolling) {
var bSize = this.options.refWidth,bResize = $(window).width(),bRatio = this.options.formula(bResize, bSize);
newPositionLeft = (scrollLeft + particle.horizontalOffset + this.viewportOffsetLeft + particle.startingPositionLeft - particle.startingOffsetLeft + particle.parentOffsetLeft) * -(particle.stellarRatio + fixedRatioOffset - 1) + particle.startingPositionLeft;
newPositionLeft *= bRatio; //all element reposition in here
newOffsetLeft = newPositionLeft - particle.startingPositionLeft + particle.startingOffsetLeft;
}
bSize = resizing browser before
bResize = resizing browser after
bRatio = resize ratio
newPositionLfet = all element position left
newPositionTop = the same to newPositionLeft

Related

Set div width based on scroll position

The code:
http://codepen.io/anon/pen/EjrpMM
So, i'm working on an interesting problem. I am working with a 2000px HTML document, that has a modal placed ontop of it.
The width of the div lightbox is 80%, and it's sitting positioned fixed.
The goal is, when scrolling down the page, to control the width of the div based on the scroll position. At the bottom of the page, it's only a third in size.
I've had trouble figuring out the proper equation or formula for this, and was seeking help.
Currently, I've been trying to look at the window.pageYOffset, to add 2.5% to the div while increasing, and minus 2.5% when scrolling back up, to bring it back to it's 80% width.
However, something isn't working right. I was seeing if the community had any ideas to help solve the problem.
I'm not using any frameworks for this.
Here's my javascript:
var lightBox = document.getElementById('lightBox'),
count = 80,
num = window.pageYOffset;
document.addEventListener('scroll', function(e) {
var offset = window.pageYOffset;
num >= offset ? count += 2.5 : count -= 2.5;
num = offset;
lightBox.style.width = count + '%';
});
View the code here, in this codepen
http://codepen.io/anon/pen/EjrpMM
Thank you!
You just have to change
+= 2.5 and -=2.5 to += 0.7 and -= 0.7
When I checked your code I did this and it worked.
Scroll event fired once on scroll independently on how much you've scrolled. E.g. if you've scrolled 1px scrollbar, or scrolled 100px using mousewheel scroll event will be fired once.
So if you need stable results you will need to calculate your div width depending on scroll position (window.pageYOffset).
Check this codepen fork. I've assumed that in the end of page div width should be 50%.
Core part is:
var lightBox = document.getElementById('lightBox');
var upperBound = 80;
var lowerBound = 50;
var tickValue = (upperBound - lowerBound) / window.innerHeight;
document.addEventListener('scroll', function(e) {
var offset = window.pageYOffset;
var count = upperBound - offset * tickValue;
lightBox.style.width = count + '%';
});
Important note: for crossbrowser way to get innerHeight you can check this answer
This is a simple equation. Let f : scroll |-> f(scroll) be the function that gives you the width of your div. You want f(0) = 0.8, f(2000)= 1/3.
Let's say you want the progression to be linear so f(scroll) = a*scroll + b, you can easily deduce that b = 0.8 and a = (1/3 - 0.8)/2000 = -0.000233. Now for any scroll value, you can find the width of your div.
Now you can change the values when you want, f(scroll) = (minWidth-maxWidth)/pageLength * scroll + maxWidth.

Scrolling content in a div when it's passed

Trying to accomplish something like on this website:
http://www.strangelove.nl/cases/kpmg-meijburg
The part where the responsive design is showcased, the image inside the devices start to scroll when a visitor scrolls past that point. I've tried to replicate it and I see a .js in the footer which is probably contributing. For now I have the css and html working on my test page.
Any help is gladly appreciated.
Strangelove is using their own Kubrick-js, which is available here: Kubrick-js
If you just want to have the 'images scrolling inside of frame while scrolling by'-effect, you can do it like this:
$(window).scroll(function() {
var animStart = 0, // the point where the animation starts
animEnd = 500, // the point, where the animation ends
scrollStartPos = 0, // the position your inside scrolling element starts
scrollEndPos = -300, // the position your inside scrolling element should end
winPosY = window.pageYOffset, // the scroll distance from top of document
scrollElement = $('.picture'); // the element to scroll
if(winPosY > animStart && winPosY < animEnd) {
// how far through the animation are we?
var howFar = (winPosY - animStart) / (animEnd - animStart),
scrollPos = Math.round(scrollStartPos + howFar * (scrollEndPos - scrollStartPos));
scrollElement.css('top', scrollPos + 'px');
$('.show-stats').html('How far: ' + howFar + '<br>scroll Position: ' + scrollPos);
}
});
Here is a fiddle for it: Fiddle
hope that helps.

Check if object is within css border/ css wrapper

I would like to begin with saying i am new to the whole programming scene. This is my first jQuery project for ICT at school.
The project:
I have multiple draggable objects (images). They are in #wrapper, wrapper is in my style.css
Now i want to make it so that when the images are dragged over a background image (centered), located under the wrapper, they will change from image. I have done this successfully by getting the location of each object:
drag: function(){
var who = $("#draggable1");
var offset1 = who.offset();
var xPos1 = offset1.left;
var yPos1 = offset1.top;
$('#posX').text('x: ' + xPos1);
$('#posY').text('y: ' + yPos1);
Then check where the object is, and if its within the X and Y of my background picture, they change:
if(yPos1 > '115' && yPos1 < '578')
{
this.src = 'pinkward5.png'
}
And also code if the object is dropped outside of the background image, this will make it go back to its original place:
if(xPos1 < '717' || xPos1 > '1202')
{
who.animate({ 'top': offset1.top == '0', 'left': offset1.left == '0'}, 200, function(){
who.stop( true,true );
who.mouseup();
this.src = 'visionward.png'
});
BUT:
If i use another monitor with another resolution or leave the browser on the half of my screen, the coordinates change, and the code doenst work as it should because the offset changes.
My question:
How can i make that no matter what the resolution or window of the browser, the coordinates are the same. Maybe with percentages or check if the object is within the css border of the background image?
Thanks! i hope i have not violated the stackoverflow rules.
Why to hardcode the coordinates?
Simply call "offset()" on the background image to get the coordinates, exactly like what you did on the draggable element, and calculate the bounds with its width and height.
var bkgd = $('.whatever-you-name-the-background-image-class');
var bkgd_offset = bkgd.offset();
if(xPos1 >= bkgd_offset.left && xPos1 + who.width() <= bkgd_offset.left + bkgd.width() &&
yPos1 >= bkgd_offset.top && yPos1 + who.height() <= bkgd_offset.top + bkgd.height())
/* draggable inside background */;
else
/* not inside background */;

Getting Coordinates of an element on page scroll

I am having this problem where i have a set of 6 UL's having a common class x.Each of them consist of a specific section of the page.Now i have 6 menus that are related to each of the section.What i have to do is highlight the menu when its related section is in users view.
For this i thought that may be jQuery position(); or offset(); could have helped but they give the top and left of the element.I also tried using jQuery viewport plugin but apparently view port is big it can show more than one UL at a time hence i cant apply element specific logic here.I am not familliar to this but does anything changes of an element on scrolling?If yes then how to access it?
Please share your views.
Regards
Himanshu Sharma.
Is very easy to do it using jQuery and a dummy fixed HTML block that helps you find the current position of the viewport.
$(window).on("scroll load",function(){
var once = true;
$(".title").each(function(ele, index){
if($(this).offset().top > $("#viewport_helper").offset().top && once){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
once = false;
}
});
})
Check out a working example: http://jsfiddle.net/6c8Az/1/
You could also do something similar with the jQuery plugin, together with the :first selector:
$(window).on("scroll load",function(){
$(".title:in-viewport:first").each(function(){
var index = $(this).index(".title");
$(".current").removeClass('current')
$("#menu li").eq(index).addClass('current')
});
})
You can get the viewport's width and height via $(document).width() and $(document).height()
You can get how many pixels user scrolls via $(document).scrollTop() and $(document).scrollLeft
Combining 1 and 2, you can calculate where the viewport rectangle is
You can get the rectangle of an element using $(element).offset(), $(element).width() and $(element).height()
So the only thing left to you is to determine whether the viewport's rectangle contains (or interacts) the elements's rectangle
So the whole code may look like:
/**
* Check wether outer contains inner
* You can change this logic to matches what you need
*/
function rectContains(outer, inner) {
return outer.top <= inner.top &&
outer.bottom >= inner.bottom &&
outer.left <= inner.left &&
outer.right >= inner.right;
}
/**
* Use this function to find the menu related to <ul> element
*/
function findRelatedMenu(element) {
return $('#menu-' + element.attr('id'));
}
function whenScroll() {
var doc = $(document);
var elem = $(element);
var viewportRect = {
top: doc.scrollTop(),
left: doc.scrollLeft(),
width: doc.width(),
height: doc.height()
};
viewportRect.bottom = viewportRect.top + viewportRect.height;
viewportRect.right = viewportRect.left + viewportRect.width;
var elements = $('ul.your-class');
for (var i = 0; i < elements.length; i++) {
var elem = $(elements[i]);
var elementRect = {
top: elem.offset().top,
left: elem.offset().left,
width: elem.width(),
height: elem.height()
};
elementRect.bottom = elementRect.top + elementRect.height;
elementRect.right = elementRect.left + elementRect.width;
if (rectContains(viewportRect, elementRect)) {
findRelatedMenu(elem).addClass('highlight');
}
}
}
$(window).on('scroll', whenScroll);
Let's see if i understood well. You have a page long enough to scroll, and there is an element that when it appears in the viewport, you wanna do something with it. So the only event that's is triggered for sure on the time the element gets in the viewport is the 'scroll'. So if the element is on the page and the scroll is on the viewport, what you need to do is bind an action to the scroll event to check if the element is in the view each time the event is trigger. Pretty much like this:
$(window).scroll(function() {
check_element_position();
});
Now, in order for you to know if the element is in the viewport, you need 3 things. The offset top of that element, the size of the viewport and the scroll top of the window. Should pretty much look like this:
function check_element_position() {
var win = $(window);
var window_height = win.height();
var element = $(your_element);
var elem_offset_top = element.offset().top;
var elem_height = element.height();
var win_scroll = win.scrollTop();
var pseudo_offset = (elem_offset_top - win_scroll);
if (pseudo_offset < window_height && pseudo_offset >= 0) {
// element in view
}
else {
// elem not in view
}
}
Here, (elem_offset_top - win_scroll) represent the element position if there was no scroll. Like this, you just have to check if the element offset top is higher then the window viewport to see if it's in view or not.
Finally, you could be more precise on you calculations by adding the element height (variable already in there) because the code i just did will fire the event even if the element is visible by only 1 pixels.
Note: I just did that in five minutes so you might have to fix some of this, but this gives you a pretty darn good idea of what's going on ;)
Feel free to comment and ask questions

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Categories

Resources