How to check if user push up (scroll top < 0 ) in iPhone - javascript

Anywhy can i detect when user push up when scroll top less than 0 ? (Like facebook app reload)
This is my code idea so far :
window.onscroll = function (e) {
scrollTop = hasOffset ? window.pageYOffset : docBody.scrollTop;
detect_pushUp(scrollTop);
};
var push_up_check = true;
function detect_pushUp(scrollPosition) {
if(scrollPosition === 0 && !push_up_check) {
push_up_check = true;
} else if(scrollPosition === 0 && push_up_check) {
location.reload(true);
} else {
push_up_check = false;
}
}
This is working ok, But any better idea? to detect something like this?

Related

How can I make the webpage slow down autoscrolling on a button press?

As the title says - I'm looking to add some auto-scrolling on a specific webpage but the script that I have at the moment stops it completely from scrolling, which doesn't look visually appealing during presentations IMHO.
Is there a possibility to slow down instead of harshly stopping the auto-scrolling of the webpage on a specific keystroke?
This is the JS that I tried.
let scrollerID;
let paused = true;
let speed = 2; // 1 - Fast | 2 - Medium | 3 - Slow
let interval = speed * 5;
function startScroll(){
let id = setInterval(function() {
window.scrollBy(0, 2);
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// Reached end of page
stopScroll();
}
}, interval);
return id;
}
function stopScroll() {
clearInterval(scrollerID);
}
document.body.addEventListener('keypress', function (event)
{
if (event.which == 13 || event.keyCode == 13) {
// It's the 'Enter' key
if(paused == true) {
scrollerID = startScroll();
paused = false;
}
else {
stopScroll();
paused = true;
}
}
}, true);
Thanks in advance!

Issue with checking if item is in DOM and the executing the javascript function

I'm making a webpage that has two different navbars... Lets say I named them navbar1 and navbar2.. soo the navbar1 is being used on the home page of the web site and navbar2 on all other sub pages... I have written a pure Javascript function that checks if the navbar1 exists in DOM and if it does then it does something... if navbar1 doesent exist in DOM it should ignore that part of code and move forward with the rest...
so now I have this issue that I spent several hours now trying to resolve... and I just can figure it out... When I go to the home page the code works... everything that should happen to navbar1 happens... but if I go to a subpage that doesn't use navbar1 I get this error in the console: "Cannot read properties of null (reading 'getBoundingClientRect')"
I would apreciate some help... and if it matters I don't have much experience with javascript so :)
So here's my JS code...
function docReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function() {
var className = "scroll";
var scrollTrigger = 60;
var navTogler = document.getElementById('navbar-toggler');
var navbar1 = document.getElementById('navbar1');
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
if (isInViewport(navbar1)) {
navTogler.addEventListener('click', classToggle);
function classToggle() {
navbar1.classList.toggle('has-bg');
if (navbar1.classList.contains('has-bg')) {
document.getElementsByClassName("logo")[0].src="./assets/images/Logo_blue.svg";
document.getElementsByClassName("search")[0].src="./assets/images/search-blue.svg";
}
if (navbar1.classList.contains('scroll') && navbar1.classList.contains('has-bg')) {
document.getElementsByClassName("logo")[0].src="./assets/images/Logo_blue.svg";
document.getElementsByClassName("search")[0].src="./assets/images/search-blue.svg";
}
if (!navbar1.classList.contains('scroll') && !navbar1.classList.contains('has-bg')) {
document.getElementsByClassName("logo")[0].src="./assets/images/Logo_White.svg";
document.getElementsByClassName("search")[0].src="./assets/images/search.svg";
}
else {
// console.log("something");
}
}
window.onscroll = function() {
if (window.scrollY >= scrollTrigger || window.pageYOffset >= scrollTrigger) {
document.getElementById("navbar1").classList.add(className);
document.getElementsByClassName("logo")[0].src="./assets/images/Logo_blue.svg";
document.getElementsByClassName("search")[0].src="./assets/images/search-blue.svg";
}
else {
document.getElementById("navbar1").classList.remove(className);
document.getElementsByClassName("logo")[0].src="./assets/images/Logo_White.svg";
document.getElementsByClassName("search")[0].src="./assets/images/search.svg";
}
};
}
var swiper = new Swiper(".mySwiper", {
slidesPerView: 3,
grid: {
rows: 2,
},
spaceBetween: 30,
pagination: {
el: ".swiper-pagination",
clickable: true,
},
});
console.log("hello swiper");
});
isInViewport() should return false if the element doesn't exist.
var isInViewport = function (elem) {
if (!elem) {
return false;
}
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};

How to control the interval of time between triggering of mousewheel event

I'm currently writing a website for a movie making company, which shows their different movies in full-screen.
I put each video in a list, and wrote a function that takes the user to the next video everytime a mousewheel event is triggered. The problem is that when the user is mousewheeling with a trackpad, it triggers multiple events at once, so I figured, I just had to set an interval between each triggering, depending on a variable "animating" that would be either true or false.
So here's my code :
let animating = false
$(window).bind('mousewheel', function (event) {
if (event.originalEvent.wheelDelta >= 0 && actuallyPlaying === false && animating === false) {
animating = true;
goToPreviousVideo();
setInterval(function () {
animating = false
}, 2000)
}
else {
if (actuallyPlaying === false && animating === false) {
animating = true;
goToNextVideo();
setInterval(function () {
animating = false
}, 2000)
};
}
});
And this piece of code works fine, but only for a few video "swipes". I noticed that after two or three times, this function stops working, and many events get triggered at the same time, which results in skipping all the videos and going from the top of the page straight to the bottom.
Do you guys have any idea why this isn't working ?
I'm also adding the code of goToNextVideo() and goToPreviousVideo() in case the problem is with them :
let i = 1 //
const goToNextVideo = function () {
if (i === 4) { // because I've got 4 videos
return;
} else {
$('html, body').animate({
scrollTop: $(`.video-${i + 1}`).offset().top
}, 500);
$(`.video-${i + 1}`).get(0).play();
i += 1
$(`.video-${i - 1}`).get(0).pause();
}
};
const goToPreviousVideo = function () {
if (i === 1) {
return
} else {
$('html, body').animate({
scrollTop: $(`.video-${i - 1}`).offset().top
}, 500);
$(`.video-${i}`).get(0).pause();
i -= 1
$(`.video-${i}`).get(0).play();
}
};
Thanks for your help !
Wish you all a great day
its seems your error is coming from the fact you dont clear the setInterval,
let animating = -1;
$(window).bind('mousewheel', function (event) {
if (event.originalEvent.wheelDelta >= 0 && actuallyPlaying === false && animating < 0) {
animating = setInterval(function () {
clearInterval(animating);
animating = -1;
}, 2000)
goToPreviousVideo();
}
else {
if (actuallyPlaying === false && animating < 0) {
animating = setInterval(function () {
clearInterval(animating);
animating = -1;
}, 2000)
goToNextVideo();
}
}
});
I am not able to understand where the problem is lying but
I have a cleaner and better approach to doing this Please tell if it works
var lastVideoChangeAnimation = Date.now()-2001;
$(window).bind('mousewheel', function (event) {
if (event.originalEvent.wheelDelta >= 0 && actuallyPlaying === false && Date.now()-lastAlertTime>2000) {
lastVideoChangeAnimation = Date.now();
goToPreviousVideo();
}
else if (actuallyPlaying === false && Date.now()-lastAlertTime>2000) {
lastVideoChangeAnimation = Date.now();
goToNextVideo();
};
});
THERE CAN ALSO BE A PROBLEM THAT THERE OCCURS SOME SORT OF ERROR AND YOUR CODE STOPS EXECUTING.
SO JUST CHECK IF THE CONSOLE IS GIVING SOME ERROR WITH POINTING TOWARDS THE FILE WHERE THESE TWO CODES ARE SAVED.
Also please tell in the comment that did it worked

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

make message always on the top

i want to make a message which will be always on the top however scrolling the page using java script.
i tried the below code, but when i scroll it still on its static place
var message = '<b><font color=000000 size=5>mona link to us! </font></b>'
//enter a color name or hex to be used as the background color of the message
var backgroundcolor = "#FFFF8A"
//enter 1 for always display, 2 for ONCE per browser session
var displaymode = 1
//Set duration message should appear on screen, in seconds (10000=10 sec, 0=perpetual)
var displayduration = 0
//enter 0 for non-flashing message, 1 for flashing
var flashmode = 1
//if above is set to flashing, enter the flash-to color below
var flashtocolor = "lightyellow"
var ie = document.all
var ieNOTopera = document.all && navigator.userAgent.indexOf("Opera") == -1
function regenerate() {
window.location.reload()
}
function regenerate2() {
if (document.layers)
setTimeout("window.onresize=regenerate", 400)
}
var which = 0
function flash() {
if (which == 0) {
if (document.layers)
topmsg_obj.bgColor = flashtocolor
else
topmsg_obj.style.backgroundColor = flashtocolor
which = 1
}
else {
if (document.layers)
topmsg_obj.bgColor = backgroundcolor
else
topmsg_obj.style.backgroundColor = backgroundcolor
which = 0
}
}
if (ie || document.getElementById)
document.write('<div id="topmsg" style="position:absolute;visibility:hidden">' + message + '</div>')
var topmsg_obj = ie ? document.all.topmsg : document.getElementById ? document.getElementById("topmsg") : document.topmsg
function positionit() {
var dsocleft = ie ? document.body.scrollLeft : pageXOffset
var dsoctop = ie ? document.body.scrollTop : pageYOffset
var window_width = ieNOTopera ? document.body.clientWidth : window.innerWidth - 20
var window_height = ieNOTopera ? document.body.clientHeight : window.innerHeight
if (ie || document.getElementById) {
topmsg_obj.style.left = parseInt(dsocleft) + window_width / 2 - topmsg_obj.offsetWidth / 2
topmsg_obj.style.top = parseInt(dsoctop) + parseInt(window_height) - topmsg_obj.offsetHeight - 4
}
else if (document.layers) {
topmsg_obj.left = dsocleft + window_width / 2 - topmsg_obj.document.width / 2
topmsg_obj.top = dsoctop + window_height - topmsg_obj.document.height - 5
}
}
function setmessage() {
if (displaymode == 2 && (!display_msg_or_not()))
return
if (document.layers) {
topmsg_obj = new Layer(window.innerWidth)
topmsg_obj.bgColor = backgroundcolor
regenerate2()
topmsg_obj.document.write(message)
topmsg_obj.document.close()
positionit()
topmsg_obj.visibility = "show"
if (displayduration != 0)
setTimeout("topmsg_obj.visibility='hide'", displayduration)
}
else {
positionit()
topmsg_obj.style.backgroundColor = backgroundcolor
topmsg_obj.style.visibility = "visible"
if (displayduration != 0)
setTimeout("topmsg_obj.style.visibility='hidden'", displayduration)
}
setInterval("positionit()", 100)
if (flashmode == 1)
setInterval("flash()", 1000)
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = ""
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset)
if (end == -1)
end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function display_msg_or_not() {
if (get_cookie("displaymsg") == "") {
document.cookie = "displaymsg=yes"
return true
}
else
return false
}
if (document.layers || ie || document.getElementById)
window.onload = setmessage
any help. or any new code please
If I'm understanding what you want, I think you're totally over thinking it. You can use CSS to keep your message fixed at the top of the page. just add position: fixed. It's how I make my header stay at the top of the page on this site: http://www.recipegraze.com
So use javascript to make the message appear/disappear, but use some simple CSS to make it stick to the top of the page.
edit: you'll also want to up the z-index of the message to make sure it appears on top of your other content, not under it.

Categories

Resources