How to position divs on top ads on Amazon.com - javascript

I want to position some divs on top of all ads on Amazon.com like this:
This is for a project of mine. The above picture was achieved through getting the coordinates of the ads using getBoundingClientRect and creating divs, setting top and left based on these coordinates, and appending the divs to document.body. However, since they have absolute position and are children of document.body, they do not move with the ads. For example, if I resize the window, this happens
Also, in product pages, this happens without doing anything.
I have also tried appending the divs to the parents of the iframes/ads, but I can never seem to make them appear outside of their parent. I have tried suggestions from various links, such as making position:absolute, setting bottom or top, making the parents position:relative but nothing has worked. There has been one instance of the div appearing outside of the parent but it was in some random position above it like this.
I seriously don't know how to accomplish this. Ideally, the div would be a sibling of the iframe or something like that, so I don't have to deal with the divs not moving when the window resizes. I just can't seem to get anything work, though.
// Here is the code for appending to parent of iframes.
// The divs just end up overlaying the ad.
function setStyle(element, styleProperties) {
for (var property in styleProperties) {
element.style[property] = styleProperties[property];
}
}
// Regex for getting all the parents of all the iframes
var placements = document.querySelectorAll('div[id^=\'ape_\'][id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var debugDiv = document.createElement('div');
debugDiv.id = iframe.id + '_debug_div';
setStyle(debugDiv, {
'backgroundColor': '#ff0000',
'height': '30px',
'display': 'block',
'position': 'absolute',
'top': '-30px',
'zIndex': '16777270',
});
alert(placement.id)
placement.style.position = 'relative'
placement.appendChild(debugDiv);
}
edit:
Here's the getBoundingClientRect code:
function setStyle(element, styleProperties) {
for (var property in styleProperties) {
element.style[property] = styleProperties[property];
}
}
function createDiv(iframeId, top, left, width) {
var div = document.createElement('div');
div.id = iframeId + '_debug_div';
setStyle(div, {
'backgroundColor': '#ccffff',
'backgroundColor': '#ff0000',
'height': '30px',
'width': width.toString() + 'px',
'display': 'block',
'position': 'absolute',
'top': (top - 30).toString() + 'px',
'left': left.toString() + 'px',
'zIndex': '16777270'
});
return div;
}
var placements = document.querySelectorAll('div[id^=\'ape_\'][id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var iframeRect = iframe.getBoundingClientRect();
iframeWidth = iframeRect.right - iframeRect.left;
var debugDiv = createDiv(iframe.id, iframeRect.top, iframeRect.left, iframeWidth);
document.body.appendChild(debugDiv);
};
This doesn't work properly when the window is resized. It also does not work properly on product pages for some ads.

Try using the resize eventlistener, with a DOM MutationObserver:
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function( obj, callback ){
if( !obj || !obj.nodeType === 1 ) return; // validation
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
callback(mutations);
})
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( window.addEventListener ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
window.onchange = function(){
observeDOM(document.body, () => {
window.addEventListener('resize', () => {
var placements = document.querySelectorAll('div[id^=\'ape_\'] [id$=\'placement\']');
for (var i = 0; i < placements.length; ++i) {
var placement = placements[i];
var iframe = placement.getElementsByTagName('iframe')[0];
var iframeRect = iframe.getBoundingClientRect();
iframeWidth = iframeRect.right - iframeRect.left;
var debugDiv = createDiv(iframe.id, iframeRect.top, iframeRect.left, iframeWidth);
document.body.appendChild(debugDiv);
}
});
});
}
It's a start. I think the issue with the misplaced bars on the product pages may be fixed by using the onload listener too, although I can't reproduce those issues for whatever reason. If it's not matching some ads altogether, that's likely due to your query selector, but I can't help fix that unfortunately.
The code for the DOM observer is from here - it should detect changes more accurately than onchange, especially for things like flex, where elements can get reordered in the DOM on mobile view. You may also want to wrap this in document.addEventListener("DOMContentLoaded", ... to wait until everything's loaded (at the sacrifice of IE8), or just use jQuery's $(document).ready() (which is compatible with IE8) - however, if you're not already using jQuery, don't import it just for this one function!
Also, you may want to do something about the padding on the body, which may be the cause of the misalignment in some cases. You should probably get it using window.getComputedStyles, and compensate for it. Once again, however, I can't reproduce these errors.

I think, that you want to select the image of the ad.
const adImages = document.querySelectorAll('your ad images');
for (var i = 0; i < adImages.length; ++i) {
adImages[i].parent.insertAdjacentHTML('afterbegin', 'your html');
}
You basicaly set the first child of that parent element on the top.

Related

Converting Jquery to Vanilla JS - floating elements

//First function -> Makes a heading float when scrolled past it
if (window.matchMedia('(min-width: 767px)').matches) {
$(function(){
var topBlockheight=$('.site-header').height();
// Check the initial Position of the fixed_nav_container
var stickyHeaderTop = $('.float-h2').offset().top;
var stopFloat = $('#stop-float').offset().top;
$(window).scroll(function(){
if( ( $(window).scrollTop() > stickyHeaderTop-topBlockheight && $(window).scrollTop() < stopFloat-topBlockheight )) {
$('.float-h2').css({position: 'fixed', top: '200px'});
}
else {
$('.float-h2').css({position: 'relative', top: '0px'});
}
});
});
}
// Adds Hover effect for boxes
if (window.matchMedia('(min-width: 767px)').matches) {
$(document).ready(function(){
$(".thumb-cta").mouseover(function(){
max_value=4;
random_value= Math.floor((Math.random() * max_value) + 1);
$(this).attr("data-random",random_value);
});
})
}
These are my two only functions in jQuery from my site which i decided to try to rewrite in vanilla JS. The reason for this decision is because I dont want a 90kb file (jquery main file) to be loaded for 2 basic functions (basic but still can't do them, yes I know).
I've tryed to re write them using http://youmightnotneedjquery.com and https://www.workversatile.com/jquery-to-javascript-converter and i ended up with this code, which does not have any errors in the console, but still does not work :((
let el = document.getElementById("masthead");
let topBlockheight = parseFloat(getComputedStyle(el, null).height.replace("px", ""))
var rect = document.getElementById("float-h2").getBoundingClientRect();
var offset = {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX,
};
var brect = document.getElementById("stop-float").getBoundingClientRect();
var boffset = {
top: rect.top + window.scrollY,
left: rect.left + window.scrollX,
};
window.scroll(function(){
if( ( window.scrollTop() > rect-topBlockheight && window.scrollTop() < stopFloat-topBlockheight )) {
document.getElementById("float-h2").css({position: 'fixed', top: '200px'});
}
else {
document.getElementById("float-h2").css({position: 'relative', top: '0px'});
}
});
Any ideas how I can move on, because I'm really stuck
hope this work for you
if (window.matchMedia('(min-width: 767px)').matches) {
//Note: if "site-header" is more than one element remove [0] and create a loop
var topBlockheight=document.getElementsByClassName('site-header')[0].offsetHeight
var stickyHeaderTop = document.getElementsByClassName('float-h2')[0].offsetTop;
var stopFloat = document.getElementById('stop-float').offsetTop;
window.addEventListener("scroll", function(){
if( ( window.scrollY > stickyHeaderTop-topBlockheight && window.scrollY < stopFloat-topBlockheight )) {
document.getElementsByClassName('float-h2')[0].style.position = 'fixed'
document.getElementsByClassName('float-h2')[0].style.top = '200px'
}
else {
document.getElementsByClassName('float-h2')[0].style.position = 'relative'
document.getElementsByClassName('float-h2')[0].style.top = 0
}
});
}
// Adds Hover effect for boxes
if (window.matchMedia('(min-width: 767px)').matches) {
document.onreadystatechange = function(){
if(document.readyState === "interactive") {
document.getElementsByClassName('thumb-cta')[0].addEventListener("mouseover", function(){
max_value=4;
random_value= Math.floor((Math.random() * max_value) + 1);
this.setAttribute("data-random",random_value);
});
}
}
}
Details
jQuery
in jQuery to select elements by className or tagName it's enough to write $('.element') or $('tag') but in Vanillajs to select elements you can use document.getElementsByClassName('elements') or document.getElementsByTagName('elements') which return found elements sharing the same className or tagName in an array if you want to select only one element you can write the element index like document.getElementsByClassName('elements')[0] but if you want to select all elements you will be need to create a loop
var el = document.getElementsByClassName('elements')
for(var i = 0; i < el.length; i++) {
el[i].style.padding = '25px';
el[i].style.background = 'red';
}
and because of id is unque name for the element you don't need to any extra steps you can select it diectly select it like document.getElementById('id')
that was about selecting elements
height() method which uses get the element height - in Vanillajs js to get the element height you can use offsetHeight property or getComputedStyle(element, pseudo|null).cssProp
Example
element.offsetHeight, parseInt(getComputedStyle(element, null).height)
offset() method which uses to return coordinates of the element this method have 2 properties top, left in Vanillajs to get the element offset top you can use offsetTop propery directly like element.offsetTop
jQuery provides a prototype method like css() which provide an easy and readable way to styling elements like in normal object propery: value - in Vanillajs to styling elements you will be need to use style object like element.style.prop = 'value' and you will be need to repeat this line every time you add new css property like
el.style.padding = '25px';
el.style.background = 'red';
//and they will repeated as long as you add new property
if you don't want to include jQuery into your project and need to use this method you can define it as prototype method for HTMLElement, HTMLMediaElement
Example 1: for styling one element
//for html elements
HTMLElement.prototype.css = function(obj) {
for(i in obj) {
this.style[i] = obj[i]
}
}
//for media elements like video, audio
HTMLMediaElement.prototype.css = function(obj) {
for(i in obj) {
this.style[i] = obj[i]
}
}
//Usage
var el = document.getElementsByClassName('elements')[0]
el.css({
'padding': '25px',
'background-color':
})
if you wants to add this style for multiple elements you can define it as prototype method for Array
Example 2: for multiple elements
Array.prototype.css = function(obj) {
for(i = 0; i < this.length; i++) {
if (this[i] instanceof HTMLElement) {
for(r in obj) {
this[i].style[r] = obj[r]
}
}
}
}
//Usage
var el1 = document.getElementsByClassName('elements')[0]
var el2 = document.getElementsByClassName('elements')[1]
[el1, el2].css({
'background-color': 'red',
padding: '25px'
})
jQuery allow you to add events directly when selecting element like $('.element').click(callback) but in Vanillajs you can add events with addEventListener() or onevent proprty like document.getElementById('id').addEventListener('click', callback) , document.getElementById('id').onclick = callback
$(document).ready(callback) this method uses to make your code start working after loading the libraries, other things it's useful to give the lib enough time to loaded to avoid errors - in Vanilla js you can use onreadystatechange event and document.readyState protpety which have 3 values loading, interactive, complete
Example
document.onreadystatechange = function () {
if (document.readyState === 'interactive') {
//your code here
}
}
Your Coverted Code
at this line parseFloat(getComputedStyle(el, null).height.replace("px", "")) you don't need to replace any thing because parseInt(), parseFloat will ignore it
element.css() id don't know how you don't get any errors in the console when this method is undefined you will be need to define it as above to make it work
scroll event is not defined you will be need to use window.onscroll = callback like example above

Execute something while element is in view

I am using the Jquery inview plugin and I am trying to load some elements whenever the user reached the footer of the page. While doing this, I discovered a bug where if the user holds the scroll-click and drags the mouse towards the bottom, in some cases the elements will not load anymore until the footer is out of the view and then back into the view.
Here is the function that I have so far to load the elements when the footer is in the viewport:
//Infinite load function. Uses jquery.inview
$scope.addMoreElements = function(){
$scope.limitElementsPerPage += 16;
$('.footer').on('inview', function(event, isInView) {
if (isInView) {
// element is now visible in the viewport
$scope.limitElementsPerPage += 16;
} else {
// element has gone out of viewport
//do nothing
}
});
};
I am using Angularjs as well as jQuery for this project. Essentially, what I think I need is something that checks at about 1-2 seconds if the element is still in view. I am not exactly sure I should do this at the moment. This is what I tried to do to solve this issue:
$scope.$watch($('.footer'), function(){
$('.footer').on('inview', function(event, isInView) {
setTimeout(function(){
while(isInView){
console.log('test')
}
}, 1000);
});
});
This unfortunately, will crash the browser (I am not sure how I would go about doing this with the setTimeout or the other related functions).
Any help or ideas on how to do this would be greatly appreciated.
Thank you in advance.
InView adds a new event for elements, that triggers when the element enters the viewport. Probably some times you just have the footer in the viewport at all times, so that is why it fails.
I think you need to redesign the logic of the page to use the 'scroll' event on whatever element contains the added items and scrolls for the infinite view and in that event to check if the footer is in the viewport, not if it enters.
Personally I use this extension for checking if it is in the viewport:
(function($) {
$.inviewport = function(element, settings) {
var wh=$(window).height();
var wst=$(window).scrollTop();
var et=$(element).offset().top;
var eh=$(element).height();
return !(wh + wst <= et)&&!(wst >= et + eh);
};
$.extend($.expr[':'], {
"in-viewport": function(a, i, m) {
return $.inviewport(a);
}
});
})(jQuery);
Here are couple of functions you can use:
var getScrollY = function(){
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ?
document.documentElement.scrollTop : document.body.scrollTop;
return y;
}
function get_elem_y( elem ) {
var box = elem.getBoundingClientRect();
return box.top + getScrollY();
}
And then you can listen to the scroll event, assume footer is something like <div id="footer">...</div>
var footer = document.getElementById("footer"); // get footer
var b_foot_visible = false;
window.addEventListener("scroll", function() {
var y = get_elem_y(footer);
var pageHeight = ( window.innerHeight || document.body.clientHeight);
if((getScrollY() + pageHeight) > y ) {
// footer is visible
if(!b_foot_visible) {
// TODO: add something
b_foot_visible = true;
}
} else {
// footer is not visible
if(b_foot_visible) {
// TODO: remove something
b_foot_visible = false;
}
}
});
Thus, when the scrollY + pages height reaches the footer elements Y coordinate you can do something to display things for the footer.
You might also add check in the beginning to test if the footer is already visible.

Affect a div when is out of view?

Is there a way to affect a div that is out of view? Ex: when you scroll down the page and the div is no longer visible.
I have an embedded youtube video and I would like to mute it only when the video is no longer in view.
This will mute every video player that is not visible:
$(function() {
var $w = $(window), oldw = 0, oldh = 0, oldt = 0;
function checkVideoVisible() {
if (oldw !== $w.width() || oldh !== $w.height() ||
oldt !== $w.scrollTop()) {
oldw = $w.width();
oldh = $w.height();
oldt = $w.scrollTop();
var top = oldt, bottom = oldt + oldh;
$("video").each(function() {
var $this = $(this);
if ($this.offset().top + $this.height() >= top &&
$this.offset().top < bottom) {
$this.prop("muted", false);
} else {
$this.prop("muted", true);
}
});
}
}
Now to trigger the checking, you can either use a timer:
var timerId = setInterval(checkVideoVisible, 200);
}
Or handle the scroll event:
$w.on("scroll", checkVideoVisible);
}
In the latter case, you will also need to perform a check when any change is made to the dom.
Use this as its probably your best bet im guessing as you;ve posted no code that a pre-written lib will help you
JQ Visible Lib
To implement you need to give your element an id and reference it in script tags or in a js file like this:
$('#element').visible() will return true if visible.
You can then add the part to mute/pause the video based on that state.

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

scroll then snap to top

Just wondering if anyone has an idea as to how I might re-create a nav bar style that I saw a while ago, I just found the site I saw it on, but am not sure how they might have gotten there. Basically want it to scroll with the page then lock to the top...
http://lesscss.org/
Just do a quick "view source" on http://lesscss.org/ and you'll see this:
window.onscroll = function () {
if (!docked && (menu.offsetTop - scrollTop() < 0)) {
menu.style.top = 0;
menu.style.position = 'fixed';
menu.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
menu.style.position = 'absolute';
menu.style.top = init + 'px';
menu.className = menu.className.replace('docked', '');
docked = false;
}
};
They're binding to the onscroll event for the window, this event is triggered when the window scrolls. The docked flag is set to true when the menu is "locked" to the top of the page, the menu is set to position:fixed at the same time that that flag is set to true. The rest is just some simple "are we about to scroll the menu off the page" and "are we about back where we started" position checking logic.
You have to be careful with onscroll events though, they can fire a lot in rapid succession so your handler needs to be pretty quick and should precompute as much as possible.
In jQuery, it would look pretty much the same:
$(window).scroll(function() {
// Pretty much the same as what's on lesscss.org
});
You see this sort of thing quite often with the "floating almost fixed position vertical toolbar" things such as those on cracked.com.
mu is too short answer is working, I'm just posting this to give you the jquery script!
var docked = false;
var menu = $('#menu');
var init = menu.offset().top;
$(window).scroll(function()
{
if (!docked && (menu.offset().top - $("body").scrollTop() < 0))
{
menu.css({
position : "fixed",
top: 0,
});
docked = true;
}
else if(docked && $("body").scrollTop() <= init)
{
menu.css({
position : "absolute",
top: init + 'px',
});
docked = false;
}
});
Mu's answer got me far. I tried my luck with replicationg lesscss.org's approach but ran into issues on browser resizing and zooming. Took me a while to find out how to react to that properly and how to reset the initial position (init) without jQuery or any other library.
Find a preview on JSFiddle: http://jsfiddle.net/ctietze/zeasg/
So here's the plain JavaScript code in detail, just in case JSFiddle refuses to work.
Reusable scroll-then-snap menu class
Here's a reusable version. I put the scrolling checks into a class because the helper methods involved cluttered my main namespace:
var windowScrollTop = function () {
return window.pageYOffset;
};
var Menu = (function (scrollOffset) {
var Menu = function () {
this.element = document.getElementById('nav');
this.docked = false;
this.initialOffsetTop = 0;
this.resetInitialOffsetTop();
}
Menu.prototype = {
offsetTop: function () {
return this.element.offsetTop;
},
resetInitialOffsetTop: function () {
this.initialOffsetTop = this.offsetTop();
},
dock: function () {
this.element.className = 'docked';
this.docked = true;
},
undock: function () {
this.element.className = this.element.className.replace('docked', '');
this.docked = false;
},
toggleDock: function () {
if (this.docked === false && (this.offsetTop() - scrollOffset() < 0)) {
this.dock();
} else if (this.docked === true && (scrollOffset() <= this.initialOffsetTop)) {
this.undock();
}
}
};
return Menu;
})(windowScrollTop);
var menu = new Menu();
window.onscroll = function () {
menu.toggleDock();
};
Handle zoom/page resize events
var updateMenuTop = function () {
// Shortly dock to reset the initial Y-offset
menu.undock();
menu.resetInitialOffsetTop();
// If appropriate, undock again based on the new value
menu.toggleDock();
};
var zoomListeners = [updateMenuTop];
(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0];
var lastWidth = 0;
function pollZoomFireEvent() {
var widthNow = w.innerWidth || e.clientWidth || g.clientWidth;
if (lastWidth == widthNow) {
return;
}
lastWidth = widthNow;
// Length changed, user must have zoomed, invoke listeners.
for (i = zoomListeners.length - 1; i >= 0; --i) {
zoomListeners[i]();
}
}
setInterval(pollZoomFireEvent, 100);
})();
Sounds like an application of Jquery ScrollTop and some manipulation of CSS properties of the navbar element. So for example, under certain scroll conditions the navbar element is changed from absolute positioning with calculated co-ordinates to fixed positioning.
http://api.jquery.com/scrollTop/
The effect you describe would usually start with some type of animation, like in TheDeveloper's answer. Default animations typically slide an element around by changing its position over time or fade an element in/out by changing its opacity, etc.
Getting the "bouce back" or "snap to" effect usually involves easing. All major frameworks have some form of easing available. It's all about personal preference; you can't really go wrong with any of them.
jQuery has easing plugins that you could use with the .animate() function, or you can use jQueryUI.
MooTools has easing built in to the FX class of the core library.
Yahoo's YUI also has easing built in.
If you can remember what site it was, you could always visit it again and take a look at their source to see what framework and effect was used.

Categories

Resources