ScroolToTop show and hide based on user's scroll - javascript

How can show and hide a dive of scrolltotop.
Condition:
1. when user scrool down to 80 px it will be shown
2.if user clicks on it it it will take user to the top.
3. if a user stay 2 or more seconds in a certain position(it may maby 200px or more or less), the scroolbar also hidden. If he scroll up or down, the scroolbar visible then.
$(document).ready(function () {
$("#scrollup").hide('slow')
$(window).scroll(function (e) {
e.preventDefault();
if ($(window).scrollTop() > 80) {
$("#scrollup").show('slow');
}
if ($(window).scrollTop() < 80) {
$("#scrollup").hide('slow');
}
});
$(".scrollup").click(function () {
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
});
i have done 1 and 2 condition , but how can i implement no 3?

Add setInterval(function(){ $("#scrollup").hide('slow'); }, 2000); and clear it on scroll
var idleInterval=null;
$(document).ready(function () {
$("#scrollup").hide('slow');
$(window).scroll(function (e) {
if(idleInterval != null)
clearTimeout(idleInterval);
idleInterval = setInterval(function(){ $("#scrollup").hide('slow'); }, 2000);
idleTime = 0;
e.preventDefault();
if ($(window).scrollTop() > 80) {
$("#scrollup").show('slow');
}
if ($(window).scrollTop() < 80) {
$("#scrollup").hide('slow');
}
});
$(".scrollup").click(function () {
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
});
Demo:-
var idleInterval=null;
$(document).ready(function () {
$("#scrollup").hide('slow');
$(window).scroll(function (e) {
if(idleInterval != null)
clearTimeout(idleInterval);
idleInterval = setInterval(function(){ $("#scrollup").hide('slow'); }, 2000);
idleTime = 0;
e.preventDefault();
if ($(window).scrollTop() > 80) {
$("#scrollup").show('slow');
}
if ($(window).scrollTop() < 80) {
$("#scrollup").hide('slow');
}
});
$(".scrollup").click(function () {
$("html, body").animate({ scrollTop: 0 }, 500);
return false;
});
});
#pagewrap{
height:1000px;
}
#scrollup {
position: fixed;
color: white;
padding: 10px 30px;
background: red;
bottom: 30px;
right: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pagewrap">
<h1>Demo</h1>
<h2>Animated Scroll to Top</h2>
<div id="scrollup">
scroll to top
</div>
</div>

Related

Create a dropdown using JavaScript

I'm a new developer and still learning and i would appreciate a bit help in here coz I'm already insane.
I have this code, trying to make a dropdown with some options but i can't make it work. In inspector mode it says Uncaught ReferenceError, jQuery not defined it doesn't do the dropdown.
<div class="container">
<nav class="fixed-top nav-menu nav d-lg block justify-content-end">
<!--<div class="right">-->
<ul>
<li>
"Nome Utilizador"
</li>
<li class="drop-down">Action
<ul class="dropdown-menu">
<li class="dropdown-item">
exemplo
</li>
</ul>
</li>
</ul>
<!--</div>-->
</nav>
</div>
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/counterup/counterup.min.js"></script>
<script src="vendor/owl.carousel/owl.carousel.min.js"></script>
<script src="js/main.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="vendor/php-email-form/validate.js"></script>
<script src="vendor/waypoints/jquery.waypoints.min.js"></script>
<script src="vendor/venobox/venobox.min.js"></script>
<script src="vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="vendor/aos/aos.js"></script>
This is the Main.js code
/**
* Template Name: OnePage - v2.2.2
* Template URL: https://bootstrapmade.com/onepage-multipurpose-bootstrap-template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
*/
!(function($) {
"use strict";
// Preloader
$(window).on('load', function() {
if ($('#preloader').length) {
$('#preloader').delay(100).fadeOut('slow', function() {
$(this).remove();
});
}
});
// Smooth scroll for the navigation menu and links with .scrollto classes
var scrolltoOffset = $('#header').outerHeight() - 2;
$(document).on('click', '.nav-menu a, .mobile-nav a, .scrollto', function(e) {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
e.preventDefault();
var scrollto = target.offset().top - scrolltoOffset;
if ($(this).attr("href") == '#header') {
scrollto = 0;
}
$('html, body').animate({
scrollTop: scrollto
}, 1500, 'easeInOutExpo');
if ($(this).parents('.nav-menu, .mobile-nav').length) {
$('.nav-menu .active, .mobile-nav .active').removeClass('active');
$(this).closest('li').addClass('active');
}
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').fadeOut();
}
return false;
}
}
});
// Activate smooth scroll on page load with hash links in the url
$(document).ready(function() {
if (window.location.hash) {
var initial_nav = window.location.hash;
if ($(initial_nav).length) {
var scrollto = $(initial_nav).offset().top - scrolltoOffset;
$('html, body').animate({
scrollTop: scrollto
}, 1500, 'easeInOutExpo');
}
}
});
// Mobile Navigation
if ($('.nav-menu').length) {
var $mobile_nav = $('.nav-menu').clone().prop({
class: 'mobile-nav d-lg-none'
});
$('body').append($mobile_nav);
$('body').prepend('<button type="button" class="mobile-nav-toggle d-lg-none"><i class="icofont-navigation-menu"></i></button>');
$('body').append('<div class="mobile-nav-overly"></div>');
$(document).on('click', '.mobile-nav-toggle', function(e) {
$('body').toggleClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').toggle();
});
$(document).on('click', '.mobile-nav .drop-down > a', function(e) {
e.preventDefault();
$(this).next().slideToggle(300);
$(this).parent().toggleClass('active');
});
$(document).click(function(e) {
var container = $(".mobile-nav, .mobile-nav-toggle");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close');
$('.mobile-nav-overly').fadeOut();
}
}
});
} else if ($(".mobile-nav, .mobile-nav-toggle").length) {
$(".mobile-nav, .mobile-nav-toggle").hide();
}
// Navigation active state on scroll
var nav_sections = $('section');
var main_nav = $('.nav-menu, #mobile-nav');
$(window).on('scroll', function() {
var cur_pos = $(this).scrollTop() + 200;
nav_sections.each(function() {
var top = $(this).offset().top,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
if (cur_pos <= bottom) {
main_nav.find('li').removeClass('active');
}
main_nav.find('a[href="#' + $(this).attr('id') + '"]').parent('li').addClass('active');
}
if (cur_pos < 300) {
$(".nav-menu ul:first li:first").addClass('active');
}
});
});
// Toggle .header-scrolled class to #header when page is scrolled
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#header').addClass('header-scrolled');
} else {
$('#header').removeClass('header-scrolled');
}
});
if ($(window).scrollTop() > 100) {
$('#header').addClass('header-scrolled');
}
// Back to top button
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.back-to-top').fadeIn('slow');
} else {
$('.back-to-top').fadeOut('slow');
}
});
$('.back-to-top').click(function() {
$('html, body').animate({
scrollTop: 0
}, 1500, 'easeInOutExpo');
return false;
});
// jQuery counterUp
$('[data-toggle="counter-up"]').counterUp({
delay: 10,
time: 1000
});
// Testimonials carousel (uses the Owl Carousel library)
$(".testimonials-carousel").owlCarousel({
autoplay: true,
dots: true,
loop: true,
responsive: {
0: {
items: 1
},
768: {
items: 2
},
900: {
items: 3
}
}
});
// Porfolio isotope and filter
$(window).on('load', function() {
var portfolioIsotope = $('.portfolio-container').isotope({
itemSelector: '.portfolio-item'
});
$('#portfolio-flters li').on('click', function() {
$("#portfolio-flters li").removeClass('filter-active');
$(this).addClass('filter-active');
portfolioIsotope.isotope({
filter: $(this).data('filter')
});
aos_init();
});
// Initiate venobox (lightbox feature used in portofilo)
$(document).ready(function() {
$('.venobox').venobox({
'share': false
});
});
});
// Portfolio details carousel
$(".portfolio-details-carousel").owlCarousel({
autoplay: true,
dots: true,
loop: true,
items: 1
});
// Init AOS
function aos_init() {
AOS.init({
duration: 1000,
once: true
});
}
$(window).on('load', function() {
aos_init();
});
})(jQuery);
First of all you need to include your jQuery script before your main.js file.
Also please consider in sharing your code here so we can help you better.

Get scrollTop to run more than once

How is it possible to get the smooth scroll working more than once (with JQuery:s scrollTop)?
var projectContainer = document.getElementsByClassName('projectContainer')[0];
var position = $(window).scrollTop();
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > position) {
$([document.documentElement, document.body]).animate({
scrollTop: $(".projectContainer").offset().top
}, 2000);
projectContainer.style.background = "orange";
$(window).bind("mousewheel", function() {
$("html, body").stop();
});
} else {
projectContainer.style.background = "white";
}
position = scroll;
});
.top {
height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="top">Scroll</div>
<div class="projectContainer">hello</div>
I've tried this but it only works for the first time after running the script.
Thanks in advance!

jQuery scrollTop only working while scrolling with mouse

I have a navigationbar that decreases in size when I scroll down on the page and then it takes its normal size when scroll is at the top. It all works fine when scrolling with the mousescrollwheel, but when I manually click and drag the scrollbar on the page its as if it doesnt recognise the scrollTop value. It takes approx 5 seconds or so for it to realise that its on the top and then applies the style, whereas with the mousescrollwheel it works flawlessly.
$(window).scroll(function () {
var scrollPosition = $(document).scrollTop();
if (scrollPosition > "1") {
$("#topNav").animate({
height: "30px"
}, 90, function () {
});
$("#topNav li").animate({
padding: "5px 0 0 0"
}, 90, function () {
});
} else if (scrollPosition <= "1") {
$("#topNav").animate({
height: "50px"
}, 90, function () {
});
$("#topNav li").animate({
padding: "15px 0 0 0"
}, 90, function () {
});
}
});
What am I missing?
Please try this code:
$(window).on('scroll mousedown mouseup mousemove',function(){
var scrollPosition = $(document).scrollTop();
if (scrollPosition > "1") {
$("#topNav").animate({
height: "30px"
}, 90, function () {
});
$("#topNav li").animate({
padding: "5px 0 0 0"
}, 90, function () {
});
} else if (scrollPosition <= "1") {
$("#topNav").animate({
height: "50px"
}, 90, function () {
});
$("#topNav li").animate({
padding: "15px 0 0 0"
}, 90, function () {
});
}
})
From what i can see, scroll function is called whenever your mouse is over the scroll bar, even without click/drag event. It might be this is causing you the trouble.
Fiddle here
$(window).scroll(function () {
var scrollPosition = $(document).scrollTop();
if (scrollPosition > "1") {
alert('a');
} else if (scrollPosition <= "1") {
alert('a');
}
});
I gave up and decided to go with CSS classes instead, using transitions and it worked wonders. Now what the scroll does is just add and remove class to the li elements and nav. Thansk for all the answers!

Javascript: scroll from one div to the other when scrolling?

I want to be able, when scrolling down, to go directly to the next div, and when scrolling up, to go directly to the previous div.
Here are my files with an example with two divs:
$(document).ready(function() {
var lastScrollTop = 0;
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
$('html, body').animate({
scrollTop: $("#space_od").offset().top
}, 500);
} else {
$('html, body').animate({
scrollTop: $("#black_hole").offset().top
}, 500);
}
lastScrollTop = st;
});
});
body {
padding: 0;
margin: 0;
}
#black_hole {
background-image: url("black_hole.jpg");
background-position: center;
display: block;
height: 100vh;
width: 100%;
}
#space_od {
background-image: url("2001.png");
background-position: center;
display: block;
height: 100vh;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="black_hole">
</div>
<div id="space_od">
</div>
It seems to work fine when scrolling down the first time, but not when scrolling up, it seems to move a few pixels and then stop. Any ideas?
scrollTo is a class to add to the divs you need to scroll to:
<div id="black_hole" class="scrollTo">
</div>
<div id="space_od" class="scrollTo">
</div>
Js
var scrolling = false;
var currentPos = 0;
function scrollUp(){
if(!scrolling && currentPos > 0 ){
scrolling=true;
currentPos --;
var scrollToElement = $('.scrollTo')[currentPos];
$('html, body').animate({
scrollTop: $(scrollToElement).offset().top
}, 500, function(){
scrolling = false;
});
}
}
function scrollDown(){
if(!scrolling && currentPos < $('.scrollTo').length-1 ){
scrolling=true;
currentPos ++;
var scrollToElement = $('.scrollTo')[currentPos];
$('html, body').animate({
scrollTop: $(scrollToElement).offset().top
}, 500,function(){
scrolling = false;
});
}
}
$(document).ready(function() {
// Get the current position on load
for( var i = 0; i < $('.scrollTo').length; i++){
var elm = $('.scrollTo')[i];
if( $(document).scrollTop() >= $(elm).offset().top ){
currentPos = i;
}
}
$(document).bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
scrollDown();
}else {
scrollUp();
}
return false;
});
$(document).bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
scrollDown();
}else {
scrollUp();
}
return false;
});
});

calling functions and click animations

I have one rectangle, 2 functions that animates different this rectangle at different window widths, and im calling the functions with a click. it Must work when screen resizes as well.
Problems:
1- it seems like when I load one function then the other cant work, only the first.
2- It doesn't work on the first click.
3- I have to write the same code for when the document is ready and when the document resize.
How can I fix this 3 points. thx. code below.
$(document).ready(function () {
function lateralMove() {
$(".rectangle-1").off("click").click(function () {
$(this).animate({
left: "+=50"
}, 500);
})
}
function horizontalMove() {
$(".rectangle-1").off("click").click(function () {
$(this).animate({
top: "+=50"
}, 500);
})
}
$(window).resize(function () {
screenWidth = $(this).width()
})
$(".rectangle-1").click(function () {
if (screenWidth > 300) {
lateralMove()
} else if (screenWidth <= 300) {
horizontalMove()
}
})
screenWidth = $(window).width()
if (screenWidth > 300) {
blackMove()
} else if (screenWidth <= 300) {
horizontalMove()
}
})
.rectangle-1 {
position: relative;
background-color: #000;
height: 100px;
width: 100px;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!doctype html>
<html>
<head></head>
<body>
<div>
<div class="rectangle-1"></div>
</div>
</body>
</html>
just cal a different function depending n a screen width:
function do_mobile(){
//do
}
function do_desktop(){
//do
}
$(".rectangle-1").on("click", function(){
if( $(window).width() > 300 ){
do_desktop();
}
else{
do_mobile();
}
})
This was just a matter of cleaning up your code (you had a function call to a function called blackMove() that was undefined) and you also needed to wrap the "assign movement" portion of your code in a function and call it on document ready and on window resize.
Here's the code pen:
http://codepen.io/nhmaggiej/full/azXgqw/
$(document).ready(function () {
function verticalMove() {
$(".rectangle-1").off("click").click(function () {
$(this).animate({
left: "+=50"
}, 500);
})
}
function horizontalMove() {
$(".rectangle-1").off("click").click(function () {
$(this).animate({
top: "+=50"
}, 500);
})
}
function assignMovement() {
screenWidth = $(this).width()
if (screenWidth > 600) {
verticalMove()
} else if (screenWidth <= 600) {
horizontalMove()
}
};
$(window).resize(function () {
assignMovement();
})
assignMovement();
});
This will move the square onload, onresize and when the square is clicked.
jsFiddle
function lateralMove(elementX) {
elementX.animate({
left: "+=50"
}, 500);
}
function horizontalMove(elementX) {
elementX.animate({
top: "+=50"
}, 500);
}
function elementMove() {
screenWidth = $(window).width();
elementX = $(".rectangle-1");
if (screenWidth > 300) {
lateralMove(elementX);
} else if (screenWidth <= 300) {
horizontalMove(elementX);
}
}
//move on resize
//Use a Timeout to ensure that the resize event is only fired once per change.
$(window).resize(function () {
clearTimeout(this.id);
this.id = setTimeout(elementMove, 500);
});
//move on click
$(".rectangle-1").click(function () {
elementMove();
})
//move on load
elementMove();

Categories

Resources