Mouswheel with one page navi - scroll only at the end of section - javascript

I had onepageNav script to scrollTo pages. Pages it's not full height of window than i had problem with addition mousewhell.
I had code:
$('body').mousewheel(function(event, delta) {
if (flag) { return false; }
$current = $('section.current');
if (delta > 0) {
$prev = $current.prev();
if ($prev.length) {
flag = true;
$('body').scrollTo($prev, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$prev.addClass('current');
}
} else {
$next = $current.next();
if ($next.length) {
flag = true;
$('body').scrollTo($next, 1000, {
onAfter : function(){
flag = false;
}
});
$current.removeClass('current');
$next.addClass('current');
}
}
event.preventDefault();
});
It's script for mousewheel. It's work but not exacly what i want.
If i had section #2 bigger than window than it's go automaticaly after scroll to next section.
I i had section #3 last, bigget than windows and i scroll down than scrolling stop working.
Someone had idea how to resolve that?

If I understand you correctly you can use the following code:
HTML:
<section id='s1'></section>
<section id='s2'></section>
<section id='s3'></section>
<section id='s4'></section>
JS:
function elementInViewport2(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
};
var current = $('section').first();
current.addClass('current');
var flag;
$(window).scroll(function(event, delta) {
if (flag) { return false; }
var $body = $('body'),
$window = $(window),
newScroll = $body.scrollTop();
if (!elementInViewport2(current[0])) {
current.removeClass('current');
current[0] = null;
}
var newSection = $('section:not(.current)').filter(function(i, el) {
return elementInViewport2(el);
}).first();
if (newSection[0] && current[0] != newSection[0]) {
current.removeClass('current');
current = newSection;
newSection.addClass('current');
flag = true;
$body.animate({scrollTop: newSection.offset().top}, function() {
flag = false;
});
event.preventDefault();
}
});
Demo

Related

How when I scroll highest and then remove class

I have a question about when I scroll highest I want to remove the class that have position fixed because the position fixed will hide my div right, so I need remove it and dont hide my div when I scroll highest.
May I know can only edit the javascript code to solved it? ty
Here is my codepen link
https://codepen.io/WeiKang-Ng/pen/bGxGQwx
Here is js code
(function(){
var doc = document.documentElement;
var w = window;
/*
define four variables: curScroll, prevScroll, curDirection, prevDirection
*/
var curScroll;
var prevScroll = w.scrollY || doc.scrollTop;
var curDirection = 0;
var prevDirection = 0;
var header = document.getElementById('site-header');
var toggled;
var threshold = 100;
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();
}
prevScroll = curScroll;
if(toggled) {
prevDirection = curDirection;
}
};
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
} else {
toggled = false;
}
return toggled
};
window.addEventListener('scroll', checkScroll);
})();
you need to add 2 lines to remove class from the header.
1st line removes the class if the user is scrolling up and has not yet reached the threshold.
2nd line removes the class if the user is not scrolling or has scrolled past the threshold.
modify the toggleHeader function as follow
var toggleHeader = function() {
toggled = true;
if (curDirection === 2 && curScroll > threshold) {
header.classList.add("nav-on-scroll");
header.classList.remove("show-nav-on-scroll");
} else if (curDirection === 1 && curScroll > threshold) {
header.classList.add("show-nav-on-scroll");
header.classList.remove("nav-on-scroll");
} else {
toggled = false;
header.classList.remove("nav-on-scroll");
}
return toggled;
};

Making animations in react without using Jquery

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

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.

Touch event handle with mousedown, mousemove and mouseup in standard javascript not jquery

Any body please tell me how can I create a touch event handle with 3 event available in javascript are mousedown, mousemove and mouseup?
Any idea is appreciated!
I have an idea for my own question and I'm using this to moving my slideshow like this:
function Dragging() {
var isDragging = false;
var isStartDragging = false;
var isEndDragging = true;
var startPoint = 0;
$('.Content-Page-List').mousedown(function (e) {
e = e || event;
if (!isStartDragging && !isDragging && isEndDragging) { isStartDragging = true; isEndDragging = false; startPoint = e.pageX; }
else { isStartDragging = isDragging = false; }
});
$('.Content-Page-List').mousemove(function () {
if (isStartDragging && !isEndDragging) { isDragging = true;}
else { return; }
});
$('.Content-Page-List').mouseup(function (e) {
e = e || event;
var leftVal = $(this).position().left;
if (isDragging && !isSlideMoving) {
var oldSlide = slide;
/* Slide move from left to right */
if (startPoint < e.pageX) {
if (leftVal == 0) return;
isSlideMoving = true;
$('.Content-Page-List').animate({ left: (leftVal + 1200) + 'px' }, 'slow', function () {
slide = parseInt(slide - 1);
contentHeight = $('.Content-Page-List').children('ul').children('li').eq(slide).height();
$('#page' + slide).parent().parent().css('background', 'rgba(243, 0, 0, 0.6)');
$('#Content-Page-List-Wrapper').css('height', contentHeight + 'px');
isStartDragging = isDragging = false;
isEndDragging = true;
isSlideMoving = false;
});
}
/*Slide move from right to left */
else {
if (leftVal == -((numOfLi * 1200) - 1200) || numOfLi == 1) return;
isSlideMoving = true;
$('.Content-Page-List').animate({ left: (leftVal - 1200) + 'px' }, 'slow', function () {
slide = parseInt(slide + 1);
contentHeight = $('.Content-Page-List').children('ul').children('li').eq(slide).height();
$('#page' + slide).parent().parent().css('background', 'rgba(243, 0, 0, 0.6)');
$('#Content-Page-List-Wrapper').css('height', contentHeight + 'px');
isStartDragging = isDragging = false;
isEndDragging = true;
isSlideMoving = false;
});
}
$('#page' + oldSlide).parent().parent().css('background', '#f4f4f4');
}
else { isStartDragging = false; isEndDragging = true; }
});

Execute & Stop JavaScript when page reach a certain position

I have a script that I want to execute only when a user reaches a position X (under my Nav bar) and to stop only when the user reaches this position X again (under my Nav bar).
How to achieve this effect?
EDIT:
How can I implement this code:
var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
//After scrolling 100px from the top...
if ($(window).scrollTop() > 100 ) {
if (!reachedFromTop) something();
reachedFromTop = true;
} else if (reachedFromTop && otherCondition) {
if (!reachedFromBottom) somethingElse();
reachedFromBottom = true;
}
});
in my existing script:
var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('.main-navigation').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
if(Math.abs(lastScrollTop - st) <= delta)
return;
if (st > lastScrollTop && st > navbarHeight){
$('.main-navigation').removeClass('nav-down').addClass('nav-up');
} else {
if(st + $(window).height() < $(document).height()) {
$('.main-navigation').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}
you should be able to do something like this.
var reachedFromTop = false;
var reachedFromBottom = false;
$(window).scroll(function() {
//After scrolling 100px from the top...
if ($(window).scrollTop() > 100 ) {
if (!reachedFromTop) something();
reachedFromTop = true;
} else if (reachedFromTop && otherCondition) {
if (!reachedFromBottom) somethingElse();
reachedFromBottom = true;
}
});
and you need to include jquery as your dependency

Categories

Resources