How i can reduce block code if else - javascript

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.

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);
})();

Functions not being triggered on scroll

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();
}
}
}
});

How can I write this code more elegantly?

I'm writing the same code three times for the different pages of my WordPress site. I feel that it could be written more elegantly but unfortunately I'm not at the skill level yet to achieve this. Is there any way to combine all of this into something more concise? It would also probably help me learn more about what can and can't be done with JavaScript.
if (jQuery(document.body).hasClass("home")) {
jQuery(window).scroll(function () {
var threshold = 654;
if (jQuery(window).scrollTop() >= 654)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) {
jQuery(window).scroll(function () {
var threshold = 20;
if (jQuery(window).scrollTop() >= 20)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
} else {
jQuery(window).scroll(function () {
var threshold = 236;
if (jQuery(window).scrollTop() >= 236)
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
}
var threshold = 236;
if (jQuery(document.body).hasClass("home")) {
threshold = 654;
} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) {
threshold = 20;
}
var scrolled = false;
jQuery(window).scroll(function () {
if (!scrolled && jQuery(window).scrollTop() >= threshold){
jQuery('#sidebar').addClass('fixed');
scrolled = true;
} else if (scrolled && jQuery(window).scrollTop() < threshold) {
jQuery('#sidebar').removeClass('fixed');
scrolled = false;
}
});
UPDATE: I was created a simple demo to show how to implement sidebar scrolls within his parent.
Demo on CodePen
Damn.. I got beat. Well, I'm still posting this anyway.
var scrollTopFn = function(amount){
$(window).scroll(function(){
// this is a ternary statement, basically a shorthand for writing if else statements
$(window).scrollTop() >= amount
? $('#sidebar').addClass('fixed')
: $('#sidebar').removeClass('fixed');
});
}
if ($(document.body).hasClass('home')) {
scrollTopFn(654);
} else if ($(document.body).hasClass('single')){
scrollTopFn(20);
} else {
scrollTopFn(236);
}
Could be:
var threshold = 236;
switch (jQuery(document.body).attr("class")) {
case "home":
threshold = 654
break;
case "single":
case "page":
threshold = 20
break;
}
$(window).scroll(function () {
if (jQuery(window).scrollTop() >= threshold )
jQuery('#sidebar').addClass('fixed');
else
jQuery('#sidebar').removeClass('fixed');
});
Your code could be simplified to:
var $body = jQuery(document.body),
threshold = $body.hasClass("home") ? 654
: $body.hasClass("single") || $body.hasClass("page") ? 20
: 236;
jQuery(window).on('scroll', function() {
jQuery('#sidebar').toggleClass('fixed', state);
});
But this one should have better performance:
var $body = jQuery(document.body),
state = false,
threshold = $body.hasClass("home") ? 654
: $body.hasClass("single") || $body.hasClass("page") ? 20
: 236;
jQuery(window).on('scroll', function() {
if(state != (state = jQuery(window).scrollTop() >= threshold))
jQuery('#sidebar').toggleClass('fixed', state);
});

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

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

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'});
}
}
});

Categories

Resources