Functions not being triggered on scroll - javascript

I have a code which is supposed to trigger various functions as I scroll down (each function draws a chart below another). The thing is that this code works well on my screen but when I run it on a bigger screen the functions are not triggered.
I haven't harcoded anything, I have debugged, and tested each conditions and all throw true.
This is the troublesome snippet:
$(window).scroll(function() {
if ($('#chartdiv').html().length != 0) {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if (Math.round((scrollHeight - scrollPosition) / scrollHeight) === 0) {
if ($('#chartdiv2').html().length == 0) {
drawChar2();
}
okas.
else if ($('#chartdiv3').html().length == 0) {
drawChar3();
} else if ($('#chartdiv4').html().length == 0) {
drawChar4();
} else if ($('#chartdiv5').html().length == 0) {
drawChar5();
}
}
}
});

If your screen is very big, you have to add if condition.
Because there is no reason to scroll.
$(window).scroll(function() {
if ($('#chartdiv').html().length != 0) {
var $window = $(window);
var windowHeight = $window.height();
var scrollHeight = $(document).height();
var scrollPosition = windowHeight + $window.scrollTop();
if (windowHeight === scrollHeight || // add this condition!!!
Math.round((scrollHeight - scrollPosition) / scrollHeight) === 0) {
if ($('#chartdiv2').html().length == 0) {
drawChar2();
} else if ($('#chartdiv3').html().length == 0) {
drawChar3();
} else if ($('#chartdiv4').html().length == 0) {
drawChar4();
} else if ($('#chartdiv5').html().length == 0) {
drawChar5();
}
}
}
});

Related

How i can reduce block code if else

Have a page with height 4600px and have if else statement in scroll elements
smoothly moving right or left.But this if else block very big.I need to reduce it.Please help anyone
var withAp = document.querySelector('.withAp');
window.onscroll = function() {
var scrolled = window.pageYOffset || document.documentElement.scrollTop;
if (scrolled < 100 ) {
withAp.style.marginRight = '0';
withAp.style.opacity = '0.1';
}
if (scrolled > 100 ) {
withAp.style.marginRight = '30px';
withAp.style.opacity = '0.2';
}
if (scrolled > 200) {
withAp.style.marginRight = '50px';
withAp.style.opacity = '0.2';
}
};
var withAp = document.querySelector('.withAp');
window.onscroll = function() {
var scrolled = window.pageYOffset || document.documentElement.scrollTop;
if (scrolled > 100 ) {
withAp.style.marginRight = '30px';
withAp.style.opacity = '0.2';
} else {
withAp.style.marginRight = '0';
withAp.style.opacity = '0.1';
}
if (scrolled > 200) {
withAp.style.marginRight = '50px';
withAp.style.opacity = '0.2';
}
};
You can do this without checking is scrolled less then 100 because if it's not greater it is less or equal so that can go in else block.

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.

Choppy animation on scroll

I'm attempting to animate a block based on how far scrolled down the page I am, by using jQuery to change the CSS attribute.
when using a mouse wheel, there is a slight flicker of where it was and where it ends up being shown at the same time.
An example of this can be viewed at the following link.
http://fiddle.jshell.net/LPvES/10/show/light/
This behaviour is not smooth and feels 'choppy'.
I have no idea why this is happening. The expected behaviour should be this:
http://jsfiddle.net/LPvES/10/embedded/result/
I understand the irony of linking the exact same example. Only difference I can see between the two is that one is embedded in an iFrame, which is not a solution I want to use.
my JS code:
var icons = {
header: "iconClosed",
activeHeader: "iconOpen"
};
$('.main--content').accordion({
header: ".accordion header",
heightStyle: "content",
collapsible: true,
icons: icons
});
function accordionIcon() {
var icon = $('.ui-accordion-header-icon.iconOpen');
var iconClosed = $('.ui-accordion-header-icon.iconClosed');
if (icon[0]) {
var article = $('.ui-accordion-header-icon.iconOpen').closest('.article')
if (article.offset().top - window.scrollY > 200) {
if (icon.css('top') !== 0) {
icon.css('top', 0)
}
} else if (article.offset().top - window.scrollY < 200) {
// article.outerHeight() - (icon.offset().top - article.offset().top) > 0
if (article.offset().top - (window.scrollY + 200) < article.outerHeight() && window.scrollY + $(window).height() - article.offset().top < article.outerHeight()) {
var position = (window.scrollY + 200) - article.offset().top
// if(icon.css('transform') === none){
icon.css('top', position)
// }
if (icon.hasClass('iconExtend')) {
icon.removeClass('iconExtend')
}
} else if (window.scrollY + $(window).height() - article.offset().top > article.outerHeight()) {
if (icon.css('top') !== article.outerHeight() + 30) {
icon.css('top', article.outerHeight() + 30)
}
if (!icon.hasClass('iconExtend')) {
icon.addClass('iconExtend')
}
} else {
if (icon.css('top') !== article.outerHeight()) {
icon.css('top', article.outerHeight())
}
if (!icon.hasClass('iconExtend')) {
icon.addClass('iconExtend')
}
}
}
}
if (iconClosed[0]) {
if (iconClosed.css('top') !== 0) {
iconClosed.css('top', 0)
}
if (iconClosed.hasClass('iconExtend')) {
iconClosed.removeClass('iconExtend')
}
}
}
function raf() {
window.requestAnimFrame = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
requestAnimFrame(raf);
accordionIcon();
}
raf();
Any help would be appreciated.

javascript to jquery

I am trying to update my javascript to be jquery.
Here is the javascript (this is working correctly)
<script type="text/javascript">
function getWindowHeight() {
var windowHeight = 0;
if (typeof (window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if (document.getElementById) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = document.getElementById('content')
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
contentElement.style.visibility = 'visible';
}
else {
contentElement.style.position = 'static';
contentElement.style.visibility = 'visible';
}
}
}
}
window.onload = function () {
setContent();
}
window.onresize = function () {
setContent();
}
</script>
Here is the jquery (this just returns a blank screen without errors)
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getWindowHeight() {
var windowHeight = 0;
if (typeof (window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if ($.documentElement && $.documentElement.clientHeight) {
windowHeight = $.documentElement.clientHeight;
}
else {
if ($.body && $.body.clientHeight) {
windowHeight = $.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if ($) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = $('content')
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
contentElement.style.visibility = 'visible';
}
else {
contentElement.style.position = 'static';
contentElement.style.visibility = 'visible';
}
}
}
}
$(document).ready= function () {
setContent();
}
$(document).onresize = function () {
setContent();
}
</script>
Your function bindings at the end are a bit off, they should look like this:
$(setContent);
$(window).resize(setContent);
This will lead to other errors though, $ isn't a replacement for document, overall I think this is what you're looking for:
function setContent() {
var windowHeight = $(window).height();
if (windowHeight > 0) {
var contentHeight = $('#content').height();
if (windowHeight - contentHeight > 0) {
$('#content').css({ position: 'relative',
top: ((windowHeight / 2) - (contentHeight / 2)) + 'px',
visibility: 'visible' });
}
else {
$('#content').css({ position: 'static',
visibility: 'visible' });
}
}
}
$(setContent);
$(window).resize(setContent);​
You can give it a try here, a few notes on this compared to the code in the question:
document.getElementById('content') is $('#content'), notice the # for an #ID selector.
$(window).height() uses .height() to take care of the cross browser/various case heights.
You can't replace document with $, they're very different things :)
.css() takes an object, so you can shorten you style setting above.
try this code..
$(function(){
var windowHeight = $(window).height();
var content = $('content');
if (windowHeight > 0) {
if (windowHeight - content.height() > 0) {
content.css({'position':'relative','top':((windowHeight/2) - (content.height()/2) + 'px','visibility':'visible' });
}else{
content.css({'position':'static','visibility':'visible'});
}
}
});

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