Header scroll issue - javascript

This is a wordpress site wherein i have an issue with header when i scroll down, you can see in the first image the header is transparent, then once i scroll down there is a glicth where the header is blinking while scrolling down with the background, actually the background should appear only when we scroll up,
please check the link, and try scrolling the page fast and you will see the blink in the header :
Code : `
<script type="text/javascript">
var mywindow = $(window);
var mypos = mywindow.scrollTop();
var up = false;
var newscroll;
mywindow.scroll(function () {
newscroll = mywindow.scrollTop();
if (newscroll > mypos && !up) {
$('.header2').stop().slideToggle();
up = !up;
console.log(up);
} else if(newscroll < mypos && up) {
$('.header2').stop().slideToggle();
up = !up;
}
mypos = newscroll;
});
</script>
<script type="text/javascript">
jQuery(window).scroll(function() {
var scroll = jQuery(window).scrollTop();
if (scroll > 300) {
jQuery(".header2").addClass("dark");
} else {
jQuery(".header2").removeClass("dark");
}
});
</script>
.dark {
background: #323232;
position: fixed!important;
border-bottom: none!important;
margin: 0px;
}
.site-logo {
float: left!important;
padding: 20px!important;
margin-top: 0px!important;
z-index: 999!important;
position: relative!important;
width: 200px!important;
}
<div id="contain">
<div class="fixed-header">
<div class="header2">
<?php if(true === get_theme_mod('show_topbar')){ ?>
<div class="fulltop">
<div class="wrap"><div class="pm-left"><?php echo ( get_theme_mod( 'topbar_text' ) ); ?></div><div class="pm-right social"><?php my_social_media_icons(); ?></div></div>
</div>
<?php }?>
<div class="wrap">
<?php if ( get_theme_mod( 'themeslug_logo' ) ) : ?>
.........
</div>
</div>
`
please help

Related

Javascript fade coloured images and backgrounds

js and html are not my strong suit but I'm trying to achieve a two simplish effects on the same page.
The user scrolls down the page and the background image/background colour changes as the divs come into view and then leave the screen.
The colors (.panel class) are working great but the image (.fadeimage) is not working at all.
HTML:
<div class="fadeimage">
<h2>image panel</h2>
</div>
<div class="panel" data-color="green">
<h2>Indigo panel</h2>
</div>
<div class="panel" data-color="blue">
<h2>Blue panel</h2>
</div>
<div class="fadeimage">
<h2>image panel</h2>
</div>
<div class="panel" data-color="yellow">
<h2>Yellow panel</h2>
</div>
CSS:
body {
color: #000;
background-color: #f4f4f4;
transition: background-color 1s ease;
}
.panel {
min-height: 100vh;
}
.fadeimage {
opacity: 0;
transition: 0.3s;
background-image: url("/New Page/images/testtakeall.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
/* colours */
.color-blue {
background-color: #2F8FED;
}
.color-green {
background-color: #4DCF42;
}
.color-yellow {
background-color: #FAEB33;
}
JS: EDITED: This this function breaks while $fadeimage.each(...) is included... it works if I remove it... but obviously this means no image fadein.
$(window).scroll(function() {
// selectors
var $window = $(window),
$body = $('body'),
$panel = $('.panel');
// Change 33% earlier than scroll position so colour is there when you arrive.
var scroll = $window.scrollTop() + ($window.height() / 3);
$fadeimage.each(function () {
var $this = $this;
if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {
$this.css('opacity', 1);
}
else {$this.css('opacity', 0)}
})
$panel.each(function () {
var $this = $(this);
// if position is within range of this panel.
// So position of (position of top of div <= scroll position) && (position of bottom of div > scroll position).
// Remember we set the scroll to 33% earlier in scroll var.
if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {
// Remove all classes on body with color-
$body.removeClass(function (index, css) {
return (css.match (/(^|\s)color-\S+/g) || []).join(' ');
});
// Add class of currently active div
$body.addClass('color-' + $(this).data('color'));
}
}).scroll();
The opacity of the divs with .fadeimage as a class just stays at 0 the whole time...
You can't use two scroll functions for same document. Instead, try to move everything in one scroll function:
$(window).scroll(function () {
// Add $fadeimage to these variables
var $window = $(window),
$body = $("body"),
$panel = $(".panel"),
$fadeimage = $(".fadeimage");
var scroll = $window.scrollTop() + $window.height() / 3;
$panel.each(function () {
var $this = $(this);
if ( $this.position().top <= scroll && $this.position().top + $this.height() > scroll ) {
$body.removeClass(function (index, css) {
return (css.match(/(^|\s)color-\S+/g) || []).join(" ");
});
$body.addClass("color-" + $(this).data("color"));
}
});
$fadeimage.each(function () {
var $this = $this;
if ( $this.position().top <= scroll && $this.position().top + $this.height() > scroll ) {
$this.css("opacity", 1);
} else {
$this.css("opacity", 0);
}
});
}).scroll();

How to Delay a Javascript Function Until it is in the middle of web page?

Hello I have a number animation on my web page and I dont want the animation to start until it is in the middle of the web page. I tried to google onscroll and other options but I could not get this to work properly.
I prefer for the animation not to start until the visitor has scrolled down to 472px. As of right now as soon as the web page loads the number animation starts automatically. Any help I would really appreciate it.
// 472 px - Starts Yellow Counter Section
const counters = document.querySelectorAll('.counter');
const speed = 200; // The lower the slower
counters.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
// Lower inc to slow and higher to slow
const inc = target / speed;
// console.log(inc);
// console.log(count);
// Check if target is reached
if (count < target) {
// Add inc to count and output in counter
counter.innerText = count + inc;
// Call function every ms
setTimeout(updateCount, 1);
} else {
counter.innerText = target;
}
};
updateCount();
});
.bg-yellow-white {
background: #f7c51e;
color: white;
}
.container {
max-width: 1404px;
margin: auto;
padding: 0 2rem;
overflow: hidden;
}
.l-heading {
font-weight: bold;
font-size: 4rem;
margin-bottom: 0.75rem;
line-height: 1.1;
}
/* Padding */
.py-1 {
padding: 1.5rem 0;
}
.py-2 {
padding: 2rem 0;
}
.py-3 {
padding: 3rem 0;
}
/* All Around Padding */
.p-1 {
padding: 1.5rem;
}
.p-2 {
padding: 2rem;
}
.p-3 {
padding: 3rem;
}
/* ======================== Red Block ======================== */
.red-block {
height: 472px;
width: 100%;
background-color: red;
}
/* ======================== PROJECS COMPLETED ======================== */
#projects-completed .container .items {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
#projects-completed .container .items .item .circle {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
<div class="red-block">
<p>red block</p>
</div>
<section id="projects-completed" class="counters bg-yellow-white">
<div class="container">
<div class="items">
<div class="item text-center p-3">
<div class="circle">
<div class="counter l-heading" data-target="1750">500</div>
</div>
<h2 class="py-2">Projects Completed</h2>
</div>
<div class="item text-center p-3">
<div class="circle py-2">
<div class="l-heading counter" data-target="5">500</div>
</div>
<h2 class="py-2">Staff Members</h2>
</div>
<!-- <div class="item text-center p-3">
<div class="circle">
<h3 class="l-heading ">1750</h3>
</div>
<h2 class="py-2">Projects Completed</h2>
</div>
<div class="item text-center p-3">
<div class="circle py-2">
<h3 class="l-heading">5</h3>
</div>
<h2 class="py-2">Staff Members</h2>
</div> -->
</div>
</div>
</section>
wesbos has great video on this https://www.youtube.com/watch?v=uzRsENVD3W8&list=PLu8EoSxDXHP6CGK4YVJhL_VWetA865GOH&index=14&t=0s
Basically what you need to do is listen for scroll and check where user currently is compared to desired place in px
you can check code here and adjust it to your needs https://github.com/wesbos/JavaScript30/blob/master/13%20-%20Slide%20in%20on%20Scroll/index-FINISHED.html
Try getBoundingClientRect(). document.querySelector( 'some element' ).getBoundingClientRect() will give you the properties of the specific element
for Example if you want to start an animation when an element is visible to user on his screen ( in the visible viewport ), you can use this to call the function and start the animation
let calledStatus = 0; // some flag variable to remember if function is called
window.onscroll = function(){
element = document.querySelector( '.some element' );
clientRect = element.getBoundingClientRect();
if( clientRect.top < window.innerHeight && clientRect.top > ( clientRect.height * -1) && calledStatus == 0){
//call your function or do other stuff
console.log('called' )
calledStatus = 1;
}
}
By using jquery , first add this reference script above your js code or referenece script
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></scrip>
....
</head>
if you want the code to launch specifically after 472 px:
js
$(document).ready(function () {
Let initialScroll = true;
//you can decrease or increase 472 depending on where exactly
//you want your function to be called
$(document).scroll(function () {
if (($(document).scrollTop() > 472)&& initialScroll) {
//call your function here
console.log( "reached 472")
InitialScroll=false;
}
});
});
if you want your function to start after reaching the middle
of the document
you place a div where the middle of the html code is :
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
...
<div id="middle"></div>
...
</body>
</html>
js
$(document).ready(function () {
Let initialScroll=true
$(document).scroll(function () {
if (($(document).scrollTop() >=$('#middle').position().top)&&initialScroll) {
//call your function here
console.log( "reached middle")
InitialScroll=false;
}
});
});
There is a native javascript API for "listetning" where the user currently is on the page called Intersection Observer. Basically you set a callback which should execute once the desired content scrolls into view.
It's used for all those fancy page animations where cards appear once you start scrolling to the bottom of the page since it's far more efficient than listening on the scroll event.
Kevin Powell did a great video about this topic.
Hope it helps!
Here's a code copy pasted, but it should give you a clue on how it should work:
document.addEventListener("DOMContentLoaded", function() {
let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
let active = false;
const lazyLoad = function() {
if (active === false) {
active = true;
setTimeout(function() {
lazyImages.forEach(function(lazyImage) {
if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") {
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove("lazy");
lazyImages = lazyImages.filter(function(image) {
return image !== lazyImage;
});
if (lazyImages.length === 0) {
document.removeEventListener("scroll", lazyLoad);
window.removeEventListener("resize", lazyLoad);
window.removeEventListener("orientationchange", lazyLoad);
}
}
});
active = false;
}, 200);
}
};
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
});

Jquery horizontal image gallery - retain clicked image to the middle

I have a horizontal image gallery, the images for which is populated from a thumbnail folder. I want to create a utility where the clicked image always remain at the middle of the thumbnail image palette. Similar to the question asked here.
A minimal version of the code is as follows:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#loaded_img_panel {
border-top: solid 0.3em #f1ded9;
display:flex;
flex-wrap: nowrap;
overflow-x:auto;
padding: 10px 0 0 0;
}
#loaded_img_panel > ul > li {
list-style: none;
}
#loaded_img_panel ul li img {
display: inline;
width: 210px;
height:175px;
cursor: pointer;
}
#loaded_img_panel img.active{
border: 0.4em solid red;
padding : 5px;
}
#loaded_img_panel > caption {
display:block;
}
#loaded_img_panel img:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="book-list-headbox">
<div class="page-number-box">
<label for="" id="total-page" value="" class="mb-0"></label>
<span class="separator">of</span>
<input type="text" id="current-page" value="1">
</div>
</div>
<div class="loaded_img_panel" id="loaded_img_panel">
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
window.addEventListener('load', function(e) {
var matchLst = "thumb";
var project = "upload";
if (matchLst !== null && matchLst !=="") {
$.post("loadimages.php", { 'project' : project,'matchLst' : matchLst }, function(output){
$("#loaded_img_panel").html(output).show();
});
}
})
$(function(){
$('#gotoframe').change(function() {
var i = $(this).val() -1;
activeBook(i);
localStorage.setItem('clicki', i);
});
$('#loaded_img_panel').on('click', 'img', function() {
activeBook($(this).index());
});
function activeBook(i){
$('#loaded_img_panel img').removeClass('active');
var active = $('#loaded_img_panel img').eq(i).addClass('active');
var left = active.position().left;
console.log("firstleft: " + left);
var currScroll= $(".loaded_img_panel").scrollLeft();
var contWidth = $('.loaded_img_panel').width()/2;
var activeOuterWidth = active.outerWidth()/2;
left= left + currScroll - contWidth + activeOuterWidth;
$('.loaded_img_panel').animate( {
scrollLeft: left
},'slow');
}
});
</script>
loadimages.php
<?php
session_start();
$project = $_POST['project'];
$match = $_POST['matchLst'];
$_SESSION['matchLst'] = $match;
$tardir = "projects/" . $project . "/" . $match . "/thumb/*.jpg" ;
$imgdir = "projects/" . $project . "/" . $match . "/" ;
$files = glob($tardir);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $imgdir . $imgname;
$filnam = substr($filname, -5);
$filnam = rtrim($filnam);
echo '<ul class="item" id="item">';
echo '<li class="book"><img src="'.$img.'" id="thumbNails'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
?>
The php code renders the images from the folder. When I click on the image from the gallery, instead of providing the position of the image, I get static values till I use the scroll bar to select some of the images that were not visible onload. Those clicks returns the position values in negative. What I am trying to do is given as an example here.

Javascript to have a fixed navbar is not working

http://www.new.techmoney360.com/ is the website and it's being developed with wordpress.
That navigarion bar is part of the <header> that also encompass my logo section up top so I'm not sure if that causing issues.
This is the entire html the encompasses the navigation bar that I want to stick to the top when I scroll past it.
<div id="navmenu" class="mkd-menu-area">
<div class="mkd-grid">
<div class="mkd-vertical-align-containers">
<div class="mkd-position-left">
<div class="mkd-position-left-inner">
<?php if(is_active_sidebar('mkd-left-from-main-menu')) : ?>
<?php dynamic_sidebar('mkd-left-from-main-menu'); ?>
<?php endif; ?>
<?php discussion_get_main_menu(); ?>
</div>
</div>
<div class="mkd-position-right">
<div class="mkd-position-right-inner">
<?php if(is_active_sidebar('mkd-right-from-main-menu')) : ?>
<?php dynamic_sidebar('mkd-right-from-main-menu'); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
This is the javascript I'm using to target the navigation bar (thanks to akinuri for the script)
window.onscroll = changePos;
function changePos() {
var header = document.getElementById("navmenu");
if (window.pageYOffset > 182) {
header.style.position = "absolute";
header.style.top = pageYOffset + "px";
} else {
header.style.position = "";
header.style.top = "";
}
}
Place .mkd-top-bar outside of all wrappers and whatnot, place it below the <body> and in it's css apply position: fixed;
.mkd-top-bar {
background-color: #303030;
position: fixed;
}
Is this what you're looking for?
#Jacob is partially correct, you don't need (as much) JavaScript here. Here's how you can resolve the issue. Replace the current functionality with this:
window.onscroll = stickyNav;
function stickyNav() {
var header = document.getElementById("navmenu");
if (window.pageYOffset > 70) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
Then, create a new class called .sticky with the following styling adjustments:
.sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
Edit: update stickNav to stickyNav.

Show/hide a div 500 px from top and 500 px before bottom

I have a page where I want an image to appear after scrolling say 500px and I used the "If you want to show a div after scrolling a number of pixels, WITHOUT jquery" code snippet from apaul34208 (show div after 800px scroll). My adapted code is like this:
<!DOCTYPE html>
<html>
<body>
<div id="myID" class="pointer hide">
<img src="image.png">
</div>
<script>
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400) {
myID.className = "pointer show"
} else {
myID.className = "pointer hide"
}
};
window.addEventListener("scroll", myScrollFunc);
</script>
</body>
</html>
and CSS:
.hide {
display: none;
}
.show {
display: block;
margin-top: -80px;
}
Only problem is that I would also like it to DISAPPEAR again lets say 400 px from the bottom of the page. the page-height differs from page to page so I cant just set a range like underneath from say 400-1000 px.
<script>
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400 & y <= 1000 ) {
myID.className = "pointer show"
} else {
myID.className = "pointer hide"
}
};
window.addEventListener("scroll", myScrollFunc);
</script>
</body>
</html>
Anyone have any idea how I can make this happen?
Thanks guys!
$(document).ready(function() {
$(window).scroll(function() {
console.log('scrolling ', $(window).scrollTop(), $(document).height());
if ($(window).scrollTop() >= 400 && $(window).scrollTop() <= ($(document).height() - 600)) {
$('#myID').removeClass('hide');
}
else {
$('#myID').addClass('hide');
}
});
});
.hide {
display: none;
}
.body {
height: 2000px;
}
#myID {
background-color: lightgray;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
<div id="myID" class="pointer hide">
STUFF HERE
</div>
</div>
use document.height to get the height of the document and rest the desired value:
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400 & y <= document.height - 400) {
myID.className = "pointer show";
} else {
myID.className = "pointer hide";
}
};
window.addEventListener("scroll", myScrollFunc);

Categories