Making animations in react without using Jquery - javascript

I am trying to create a on scroll fade animation in my website i am using reactjs for this although i didnt knew how to bring this effect so i found this jquery code to achive this effect but i want to bring this effect without jquery using plane react is it possible? here is the jquery code:
var html = $('html');
// Detections
if (!("ontouchstart" in window)) {
html.addClass("noTouch");
}
if ("ontouchstart" in window) {
html.addClass("isTouch");
}
if ("ontouchstart" in window) {
html.addClass("isTouch");
}
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
if (navigator.appVersion.indexOf("Trident") === -1) {
html.addClass("isEDGE");
} else {
html.addClass("isIE isIE11");
}
}
if (navigator.appVersion.indexOf("MSIE") !== -1) {
html.addClass("isIE");
}
if (
navigator.userAgent.indexOf("Safari") != -1 &&
navigator.userAgent.indexOf("Chrome") == -1
) {
html.addClass("isSafari");
}
// On Screen
$.fn.isOnScreen = function() {
var elementTop = $(this).offset().top,
elementBottom = elementTop + $(this).outerHeight(),
viewportTop = $(window).scrollTop(),
viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
function detection() {
for (var i = 0; i < items.length; i++) {
var el = $(items[i]);
if (el.isOnScreen()) {
el.addClass("in-view");
} else {
el.removeClass("in-view");
}
}
}
var items = document.querySelectorAll(
"*[data-animate-in], *[data-detect-viewport]"
),
waiting = false,
w = $(window);
w.on("resize scroll", function() {
if (waiting) {
return;
}
waiting = true;
detection();
setTimeout(function() {
waiting = false;
}, 100);
});
$(document).ready(function() {
setTimeout(function() {
detection();
}, 500);
for (var i = 0; i < items.length; i++) {
var d = 0,
el = $(items[i]);
if (items[i].getAttribute("data-animate-in-delay")) {
d = items[i].getAttribute("data-animate-in-delay") / 1000 + "s";
} else {
d = 0;
}
el.css("transition-delay", d);
}
});
});
is there any way that i can bring this effect from react only or do i have to use :
import $ from jquery
thanks in advance

Related

header hide on scroll - delay on scroll up

I want to add a delay to this header when the user scrolls 200px up: https://codepen.io/iabhinavr/pen/BaKxvRx
If see the codepen, right now it only delays on scrolls down.
This is what I have tried:
// menu hide on scroll
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 350;
var thresholdScrollUp = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
curScrollBottom = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && curScroll > threshold) {
header.classList.add('hide');
jQuery('#site-header-sticky-wrapper').addClass('hide');
}
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp) {
jQuery('#site-header-sticky-wrapper').removeClass('hide');
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();
I added:
var thresholdScrollUp = 200;
and changed:
else if (curDirection === 1)
to:
else if (curDirection === 1 && curScrollBottom > thresholdScrollUp)
Any help would be appreciated
Your provided code pen code work differently. Checkout this one
(function(){
var doc = document.documentElement;
var w = window;
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var lastY = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 200;
var checkScroll = function() {
curScroll = w.scrollY || doc.scrollTop;
if(curScroll > prevScroll) {
// scrolled down
curDirection = 2;
}
else {
//scrolled up
curDirection = 1;
}
if(curDirection !== prevDirection) {
toggled = toggleHeader();
} else {
lastY=curScroll
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if(curDirection === 2 && (curScroll-lastY) > threshold) {
lastY=curScroll
header.classList.add('hide');
}
else if (curDirection === 1 && (lastY-curScroll) > threshold) {
lastY=curScroll
header.classList.remove('hide');
}
else {
toggled = false;
}
return toggled;
};
window.addEventListener('scroll', checkScroll);
})();

Scrolling issues on mac os

So I have write a script for my portfolio website to scroll to section by index. It works on every tested browser and smartphone but on a mac device it does not work probably instead to scroll to the next sections it is going automatically to the second next section.
Hopefully someone can help me.
var anchorPoints = [];
var anchorLocation = [];
var anchorIndex = 0;
var waiting = false;
var canScroll = true;
var offset = 0
window.onload = function () {
anchorPoints = document.getElementsByClassName("js-anchor");
for (i = 0; i < anchorPoints.length; i++) {
getLocation = anchorPoints[i].getBoundingClientRect();
getLocation = getLocation.top - offset;
anchorLocation.push(parseInt(getLocation));
}
}
$(document).on('mousewheel DOMMouseScroll', function (e) {
if (detectMobile() == true) {
return;
}
if ((waiting || canScroll == false)) {
return;
}
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('section.active');
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
waiting = true;
if (delta < 0) {
anchorIndex += 1;
if (anchorIndex > (anchorPoints.length - 1)) {
anchorIndex = 0;
}
scrollTo({
top: anchorLocation[anchorIndex],
left: 0,
behavior: 'smooth'
});
console.log(anchorIndex);
console.log('scrolling down');
} else {
anchorIndex -= 1;
if (anchorIndex < 0) {
anchorIndex = anchorPoints.length - 1;
}
scrollTo({
top: anchorLocation[anchorIndex],
left: 0,
behavior: 'smooth'
});
console.log(anchorIndex);
console.log('scrolling up');
}
setTimeout(function () {
waiting = false;
}, 1000);
});

Overriding element.style{width: ;} value in jquery sticky nav

The issue that I am having is getting my sticky nav to span the entire width of the page. I am using the jquery sticky nav plugin from http://stickyjs.com/ - I have tried setting the width to 100% but there is an element.style property that is overriding the containers width. After researching this issue it seems that this element.style value comes from the javascript for this plugin. I am new to code and I have limited javascript knowledge so any guidance on how to change/remove that element.style value would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.sticky.js"></script>
</head>
<body>
<div class="wrapper">
<header id="sticker" class="clearfix">
<img src="img/logo.png" alt="Conference Logo">
<nav>
<ul class="monquan">
<li>Schedule</li>
<li>Locations</li>
<li>Workshops</li>
<li>Register</li>
</ul>
</nav>
</header>
</div>
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
</body>
</html>
There is the HTML for my project and below is the jquery.sticky.js code that I believe holds the answer to my problem.
// Sticky Plugin v1.0.4 for jQuery
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Improvements by Leonardo C. Daronco (daronco)
// Created: 02/14/2011
// Date: 07/20/2015
// Website: http://stickyjs.com/
// Description: Makes an element on the page stick on the screen as you scroll
// It will only set the 'top' and 'position' of your element, you
// might need to adjust the width in some cases.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var slice = Array.prototype.slice; // save ref to original slice()
var splice = Array.prototype.splice; // save ref to original slice()
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
wrapperClassName: 'sticky-wrapper',
center: false,
getWidthFrom: '',
widthFromWrapper: true, // works only when .getWidthFrom is empty
responsiveWidth: false,
zIndex: 'auto'
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0, l = sticked.length; i < l; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
//update height in case of dynamic content
s.stickyWrapper.css('height', s.stickyElement.outerHeight());
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement
.css({
'width': '',
'position': '',
'top': '',
'z-index': ''
});
s.stickyElement.parent().removeClass(s.className);
s.stickyElement.trigger('sticky-end', [s]);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.stickyElement.outerHeight()
- s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop !== newTop) {
var newWidth;
if (s.getWidthFrom) {
newWidth = $(s.getWidthFrom).width() || null;
} else if (s.widthFromWrapper) {
newWidth = s.stickyWrapper.width();
}
if (newWidth == null) {
newWidth = s.stickyElement.width();
}
s.stickyElement
.css('width', newWidth)
.css('position', 'fixed')
.css('top', newTop)
.css('z-index', s.zIndex);
s.stickyElement.parent().addClass(s.className);
if (s.currentTop === null) {
s.stickyElement.trigger('sticky-start', [s]);
} else {
// sticky is started but it have to be repositioned
s.stickyElement.trigger('sticky-update', [s]);
}
if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
// just reached bottom || just started to stick but bottom is already reached
s.stickyElement.trigger('sticky-bottom-reached', [s]);
} else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
// sticky is started && sticked at topSpacing && overflowing from top just finished
s.stickyElement.trigger('sticky-bottom-unreached', [s]);
}
s.currentTop = newTop;
}
// Check if sticky has reached end of container and stop sticking
var stickyWrapperContainer = s.stickyWrapper.parent();
var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing);
if( unstick ) {
s.stickyElement
.css('position', 'absolute')
.css('top', '')
.css('bottom', 0)
.css('z-index', '');
} else {
s.stickyElement
.css('position', 'fixed')
.css('top', newTop)
.css('bottom', '')
.css('z-index', s.zIndex);
}
}
}
},
resizer = function() {
windowHeight = $window.height();
for (var i = 0, l = sticked.length; i < l; i++) {
var s = sticked[i];
var newWidth = null;
if (s.getWidthFrom) {
if (s.responsiveWidth) {
newWidth = $(s.getWidthFrom).width();
}
} else if(s.widthFromWrapper) {
newWidth = s.stickyWrapper.width();
}
if (newWidth != null) {
s.stickyElement.css('width', newWidth);
}
}
},
methods = {
init: function(options) {
var o = $.extend({}, defaults, options);
return this.each(function() {
var stickyElement = $(this);
var stickyId = stickyElement.attr('id');
var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName;
var wrapper = $('<div></div>')
.attr('id', wrapperId)
.addClass(o.wrapperClassName);
stickyElement.wrapAll(function() {
if ($(this).parent("#" + wrapperId).length == 0) {
return wrapper;
}
});
var stickyWrapper = stickyElement.parent();
if (o.center) {
stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
}
if (stickyElement.css("float") === "right") {
stickyElement.css({"float":"none"}).parent().css({"float":"right"});
}
o.stickyElement = stickyElement;
o.stickyWrapper = stickyWrapper;
o.currentTop = null;
sticked.push(o);
methods.setWrapperHeight(this);
methods.setupChangeListeners(this);
});
},
setWrapperHeight: function(stickyElement) {
var element = $(stickyElement);
var stickyWrapper = element.parent();
if (stickyWrapper) {
stickyWrapper.css('height', element.outerHeight());
}
},
setupChangeListeners: function(stickyElement) {
if (window.MutationObserver) {
var mutationObserver = new window.MutationObserver(function(mutations) {
if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) {
methods.setWrapperHeight(stickyElement);
}
});
mutationObserver.observe(stickyElement, {subtree: true, childList: true});
} else {
if (window.addEventListener) {
stickyElement.addEventListener('DOMNodeInserted', function() {
methods.setWrapperHeight(stickyElement);
}, false);
stickyElement.addEventListener('DOMNodeRemoved', function() {
methods.setWrapperHeight(stickyElement);
}, false);
} else if (window.attachEvent) {
stickyElement.attachEvent('onDOMNodeInserted', function() {
methods.setWrapperHeight(stickyElement);
});
stickyElement.attachEvent('onDOMNodeRemoved', function() {
methods.setWrapperHeight(stickyElement);
});
}
}
},
update: scroller,
unstick: function(options) {
return this.each(function() {
var that = this;
var unstickyElement = $(that);
var removeIdx = -1;
var i = sticked.length;
while (i-- > 0) {
if (sticked[i].stickyElement.get(0) === that) {
splice.call(sticked,i,1);
removeIdx = i;
}
}
if(removeIdx !== -1) {
unstickyElement.unwrap();
unstickyElement
.css({
'width': '',
'position': '',
'top': '',
'float': '',
'z-index': ''
})
;
}
});
}
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(method) {
if (methods[method]) {
return methods[method].apply(this, slice.call(arguments, 1));
} else if (typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error('Method ' + method + ' does not exist on jQuery.sticky');
}
};
$.fn.unstick = function(method) {
if (methods[method]) {
return methods[method].apply(this, slice.call(arguments, 1));
} else if (typeof method === 'object' || !method ) {
return methods.unstick.apply( this, arguments );
} else {
$.error('Method ' + method + ' does not exist on jQuery.sticky');
}
};
$(function() {
setTimeout(scroller, 0);
});
}));
Please let me know if there is anything else I can provide to make answering this easier and I appreciate any input.
I strongly suggest not to change the library file, it will pretty much defeat the purpose of you using a library in the first place. A library is designed to work in a specific way and mostly follows a rigid code, meaning if you change a single component the repercussions might be bad or worse non-debuggable.
If you want, you must always override the code with your own custom files. In your case, after the <script src="js/jquery.sticky.js"></script> create a js file of your own say, <script src="js/custom.js"></script> and add this there(this is just a basic example)
element.css({"width":"100%"});
OR adding the same line onto your internal <script> in your HTML(where you have initiated the stickybar) will also work well.

Easy Smooth Scroll Plugin: How do I offset scroll?

I am using the Easy Smooth Scroll Plugin for Wordpress.
Below is the .js file that the plugin uses:
var ss = {
fixAllLinks: function() {
var allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) && ((lnk.pathname == location.pathname) || ('/' + lnk.pathname == location.pathname)) && (lnk.search == location.search)) {
ss.addEvent(lnk, 'click', ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() != 'a') return;
anchor = target.hash.substr(1);
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}
if (!destinationLink) destinationLink = document.getElementById(anchor);
if (!destinationLink) return true;
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent && (thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty - cypos) / ss.STEPS);
ss.INTERVAL = setInterval('ss.scrollWindow(' + ss_stepsize + ',' + desty + ',"' + anchor + '")', 10);
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},
scrollWindow: function(scramount, dest, anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0, wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
window.scrollTo(0, dest);
clearInterval(ss.INTERVAL);
location.hash = anchor;
}
},
getCurrentYPos: function() {
if (document.body && document.body.scrollTop) return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
if (window.pageYOffset) return window.pageYOffset;
return 0;
},
addEvent: function(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent) {
var r = elm.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}
ss.STEPS = 25;
ss.addEvent(window, "load", ss.fixAllLinks);
The live page is here: http://iamjoepro.com/album/promaha/
I have the smooth scroll scrolling to an anchor, but I would like to offset it by the height of my fixed header (120px)
I am no javascript expert, I'm hoping this is easy for someone, but I can't decipher where to add the offset in my .js file?
I had a similar issue and found that the following solution worked for me.
Change the line:
var desty = destinationLink.offsetTop;
to read:
var desty = destinationLink.offsetTop - 120;
(where '120' is the height in pixels of your fixed header)
Then, remove the line:
location.hash = anchor;
(otherwise, the page will scroll to your 120px offset but then return back to the location of the anchor)
Hope this helps!

How to make this floating menu work only when specific #divs become visible?

I needed to make a floating menu, I searched online and found a script here http://www.jtricks.com/javascript/navigation/floating.html
/* Script by: www.jtricks.com
* Version: 1.12 (20120823)
* Latest version: www.jtricks.com/javascript/navigation/floating.html
*
* License:
* GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*/
var floatingMenu =
{
hasInner: typeof(window.innerWidth) == 'number',
hasElement: typeof(document.documentElement) == 'object'
&& typeof(document.documentElement.clientWidth) == 'number'};
var floatingArray =
[
];
floatingMenu.add = function(obj, options)
{
var name;
var menu;
if (typeof(obj) === "string")
name = obj;
else
menu = obj;
if (options == undefined)
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: 0,
targetTop: 0,
distance: .07,
snap: true,
updateParentHeight: false
});
}
else
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: options.targetLeft,
targetRight: options.targetRight,
targetTop: options.targetTop,
targetBottom: options.targetBottom,
centerX: options.centerX,
centerY: options.centerY,
prohibitXMovement: options.prohibitXMovement,
prohibitYMovement: options.prohibitYMovement,
distance: options.distance != undefined ? options.distance : .07,
snap: options.snap,
ignoreParentDimensions: options.ignoreParentDimensions,
updateParentHeight:
options.updateParentHeight == undefined
? false
: options.updateParentHeight,
scrollContainer: options.scrollContainer,
scrollContainerId: options.scrollContainerId,
confinementArea: options.confinementArea,
confinementAreaId:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '#'
? options.confinementArea.substring(1)
: undefined,
confinementAreaClassRegexp:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '.'
? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
: undefined
});
}
};
floatingMenu.findSingle = function(item)
{
if (item.id)
item.menu = document.getElementById(item.id);
if (item.scrollContainerId)
item.scrollContainer = document.getElementById(item.scrollContainerId);
};
floatingMenu.move = function (item)
{
if (!item.prohibitXMovement)
{
item.menu.style.left = item.nextX + 'px';
item.menu.style.right = '';
}
if (!item.prohibitYMovement)
{
item.menu.style.top = item.nextY + 'px';
item.menu.style.bottom = '';
}
};
floatingMenu.scrollLeft = function(item)
{
// If floating within scrollable container use it's scrollLeft
if (item.scrollContainer)
return item.scrollContainer.scrollLeft;
var w = window.top;
return this.hasInner
? w.pageXOffset
: this.hasElement
? w.document.documentElement.scrollLeft
: w.document.body.scrollLeft;
};
floatingMenu.scrollTop = function(item)
{
// If floating within scrollable container use it's scrollTop
if (item.scrollContainer)
return item.scrollContainer.scrollTop;
var w = window.top;
return this.hasInner
? w.pageYOffset
: this.hasElement
? w.document.documentElement.scrollTop
: w.document.body.scrollTop;
};
floatingMenu.windowWidth = function()
{
return this.hasElement
? document.documentElement.clientWidth
: document.body.clientWidth;
};
floatingMenu.windowHeight = function()
{
if (floatingMenu.hasElement && floatingMenu.hasInner)
{
// Handle Opera 8 problems
return document.documentElement.clientHeight > window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
}
else
{
return floatingMenu.hasElement
? document.documentElement.clientHeight
: document.body.clientHeight;
}
};
floatingMenu.documentHeight = function()
{
var innerHeight = this.hasInner
? window.innerHeight
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
innerHeight);
};
floatingMenu.documentWidth = function()
{
var innerWidth = this.hasInner
? window.innerWidth
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollWidth,
body.offsetWidth,
html.clientWidth,
html.scrollWidth,
html.offsetWidth,
innerWidth);
};
floatingMenu.calculateCornerX = function(item)
{
var offsetWidth = item.menu.offsetWidth;
var result = this.scrollLeft(item) - item.parentLeft;
if (item.centerX)
{
result += (this.windowWidth() - offsetWidth)/2;
}
else if (item.targetLeft == undefined)
{
result += this.windowWidth() - item.targetRight - offsetWidth;
}
else
{
result += item.targetLeft;
}
if (document.body != item.menu.parentNode
&& result + offsetWidth >= item.confinedWidthReserve)
{
result = item.confinedWidthReserve - offsetWidth;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.calculateCornerY = function(item)
{
var offsetHeight = item.menu.offsetHeight;
var result = this.scrollTop(item) - item.parentTop;
if (item.centerY)
{
result += (this.windowHeight() - offsetHeight)/2;
}
else if (item.targetTop === undefined)
{
result += this.windowHeight() - item.targetBottom - offsetHeight;
}
else
{
result += item.targetTop;
}
if (document.body != item.menu.parentNode
&& result + offsetHeight >= item.confinedHeightReserve)
{
result = item.confinedHeightReserve - offsetHeight;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.isConfinementArea = function(item, area)
{
return item.confinementAreaId != undefined
&& area.id == item.confinementAreaId
|| item.confinementAreaClassRegexp != undefined
&& area.className
&& item.confinementAreaClassRegexp.test(area.className);
};
floatingMenu.computeParent = function(item)
{
if (item.ignoreParentDimensions)
{
item.confinedHeightReserve = this.documentHeight();
item.confinedWidthReserver = this.documentWidth();
item.parentLeft = 0;
item.parentTop = 0;
return;
}
var parentNode = item.menu.parentNode;
var parentOffsets = this.offsets(parentNode, item);
item.parentLeft = parentOffsets.left;
item.parentTop = parentOffsets.top;
item.confinedWidthReserve = parentNode.clientWidth;
// We could have absolutely-positioned DIV wrapped
// inside relatively-positioned. Then parent might not
// have any height. Try to find parent that has
// and try to find whats left of its height for us.
var obj = parentNode;
var objOffsets = this.offsets(obj, item);
if (item.confinementArea == undefined)
{
while (obj.clientHeight + objOffsets.top
< item.menu.scrollHeight + parentOffsets.top
|| item.menu.parentNode == obj
&& item.updateParentHeight
&& obj.clientHeight + objOffsets.top
== item.menu.scrollHeight + parentOffsets.top)
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
else
{
while (obj.parentNode != undefined
&& !this.isConfinementArea(item, obj))
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
item.confinedHeightReserve = obj.clientHeight
- (parentOffsets.top - objOffsets.top);
};
floatingMenu.offsets = function(obj, item)
{
var result =
{
left: 0,
top: 0
};
if (obj === item.scrollContainer)
return;
while (obj.offsetParent && obj.offsetParent != item.scrollContainer)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
if (window == window.top)
return result;
// we're IFRAMEd
var iframes = window.top.document.body.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++)
{
if (iframes[i].contentWindow != window)
continue;
obj = iframes[i];
while (obj.offsetParent)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return result;
};
floatingMenu.doFloatSingle = function(item)
{
this.findSingle(item);
if (item.updateParentHeight)
{
item.menu.parentNode.style.minHeight =
item.menu.scrollHeight + 'px';
}
var stepX, stepY;
this.computeParent(item);
var cornerX = this.calculateCornerX(item);
var stepX = (cornerX - item.nextX) * item.distance;
if (Math.abs(stepX) < .5 && item.snap
|| Math.abs(cornerX - item.nextX) <= 1)
{
stepX = cornerX - item.nextX;
}
var cornerY = this.calculateCornerY(item);
var stepY = (cornerY - item.nextY) * item.distance;
if (Math.abs(stepY) < .5 && item.snap
|| Math.abs(cornerY - item.nextY) <= 1)
{
stepY = cornerY - item.nextY;
}
if (Math.abs(stepX) > 0 ||
Math.abs(stepY) > 0)
{
item.nextX += stepX;
item.nextY += stepY;
this.move(item);
}
};
floatingMenu.fixTargets = function()
{
};
floatingMenu.fixTarget = function(item)
{
};
floatingMenu.doFloat = function()
{
this.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
this.fixTarget(floatingArray[i]);
this.doFloatSingle(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 20);
};
floatingMenu.insertEvent = function(element, event, handler)
{
// W3C
if (element.addEventListener != undefined)
{
element.addEventListener(event, handler, false);
return;
}
var listener = 'on' + event;
// MS
if (element.attachEvent != undefined)
{
element.attachEvent(listener, handler);
return;
}
// Fallback
var oldHandler = element[listener];
element[listener] = function (e)
{
e = (e) ? e : window.event;
var result = handler(e);
return (oldHandler != undefined)
&& (oldHandler(e) == true)
&& (result == true);
};
};
floatingMenu.init = function()
{
floatingMenu.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
floatingMenu.initSingleMenu(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 100);
};
// Some browsers init scrollbars only after
// full document load.
floatingMenu.initSingleMenu = function(item)
{
this.findSingle(item);
this.computeParent(item);
this.fixTarget(item);
item.nextX = this.calculateCornerX(item);
item.nextY = this.calculateCornerY(item);
this.move(item);
};
floatingMenu.insertEvent(window, 'load', floatingMenu.init);
// Register ourselves as jQuery plugin if jQuery is present
if (typeof(jQuery) !== 'undefined')
{
(function ($)
{
$.fn.addFloating = function(options)
{
return this.each(function()
{
floatingMenu.add(this, options);
});
};
}) (jQuery);
}
The script requires the menu to have #floatdiv id. I made my div, #floatdiv, and added the following line of javascript to the head to make the action start working:
<script type="text/javascript">
floatingMenu.add('floatdiv',
{
targetLeft: 250,
targetTop: 290,
snap: true
});
</script>
the #floatdiv css is here,
#floatdiv{
height:45px;
width:830px;
z-index:2;
}
The script is working fine. When I scroll down, the menu float as specified. But I dun wanna the menu to float all the way with scrolling. I need the float of the menu to fire only when I enter specific divs not all the way with scrolling.. Any clues?
is this what look like?
html
<div id="header">HEADER</div>
<div id="content">
<div id="left">LEFT</div>
<div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>
js
$(function() {
var $sidebar = $("#right"),
$window = $(window),
rightOffset = $sidebar.offset(),
rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
topPadding = 15;
$window.scroll(function() {
$sidebar.stop().animate({
marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
});
});
});
working demo
hope this help you
I wrote the script listed in the question.
The script is very versatile and can make div float within a specific area (e.g. another container div). Here are the instructions:
http://www.jtricks.com/javascript/navigation/floating/confined_demo.html

Categories

Resources