I want to add a class to a div after scrolling 500px down the page using jquery. I found a way of doing it but it's an immediate transition, I want to be able to controll how long it takes to add the class like with the normal Jquery addclass.
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".nav").addClass("navnewclass");
}
});
I tried doing this:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
$(".nav").addClass("navnewclass", 2000);
}
});
but it was the same.
I want to be able to controll how long it takes to add the class like with the normal Jquery addclass.
addClass is always instantaneous, it's not part of the animation suite.
There are plug-ins that will do class-based animations for you (most notably jQuery UI's addClass override), but jQuery itself does not. Simply adding jQuery UI to your page will make your second example work. But there are other options as well.
Your options are to use one of those plug-ins, or animate the properties directly (using animate) rather than using a class. Note that jQuery only animates certain kinds of properties (not, notably, colors — jQuery UI adds support for animating colors as well).
Here's an example animating a class (with colors) using jQuery UI: Live Copy | Live Source
<style>
.testing {
color: white;
background-color: blue;
}
</style>
<!-- ...and later in the body... -->
<p>After half a second, the div below will spend two seconds animating the addition of a class.</p>
<div class="nav">This is a test .nav element</div>
<script>
setTimeout(function() {
$(".nav").addClass("testing", 2000);
}, 500);
</script>
IT WILL WORK FINE FOR ME.
$(document).scroll(function() {
var scroll = $(this).scrollTop();
if (scroll >= 500) {
setTimeout('$(".nav").addClass("navnewclass")',1000);
}
});
instead of 1000 U can just set your time.
you can do that using jQuery or $ sign
example:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("#logo-not-scroll").addClass("blue1");
}
else{
$("#logo-not-scroll").removeClass("blue1");
}
});
or
jQuery(window).scroll(function() {
var scroll = jQuery(window).scrollTop();
if (scroll >= 100) {
jQuery("#logo-not-scroll").addClass("blue1");
}
else{
jQuery("#logo-not-scroll").removeClass("blue1");
}
});
Related
I have a button that scrolls to another element. This works fine on desktop but on mobile if I scroll a little bit and click the button, the function does not scroll precisely to the element I want but is a bit off, even though I didn't specify any offset.
On desktop I have a fixed menu that changes size, so that is why in below code I check for desktop or mobile using the window width:
if(window.outerWidth > 991) {
console.log('desktop');
$("body").on("click","#bestellenbtn",function(){
var scrollmenuheight = $('.scrollmenu').height();
$([document.documentElement, document.body]).animate({
scrollTop: $("#bestellen").offset().top - scrollmenuheight
}, 1000);
});
}else{
console.log('mobile');
$("body").on("click","#bestellenbtn",function(){
$([document.documentElement, document.body]).animate({
scrollTop: $("#bestellen").offset().top
}, 1000);
});
}
This is the button that starts the function:
<button class="btnstyle blue-inverse" type="button" name="button">Bestellen</button>
And the element:
<div class="separator" id="bestellen">
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Bestellen</h2>
</div>
</div>
</div>
</div>
I added a copy of the page in a codepen so you can see it for yourself (click the first of 4 blue buttons on mobile view):
https://codepen.io/twan2020/pen/RwGmaMQ You can resize to get the mobile version.
What can I do?
I've tried changing the offset but that shouldn't be necessary because on mobile there is no fixed menu that changes the height of the document.
I made a short video to show what the problem is:
https://gyazo.com/431163072afb0de9a6488ebfba895ff5
Use the if-statement inside the function that handels #bestellenbtn click.
Use window.innerWidth instead of window.outerWidth. However, For compatibility reason, it is better that you use the following code instead.
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); .
On mobile, use Element.scrollIntoView() with smooth behaviour. Let JS rules.
Element.scrollIntoView()
The Element interface's scrollIntoView() method scrolls the element's
parent container such that the element on which scrollIntoView() is
called is visible to the user. MDN - Element.scrollIntoView()
document.querySelector("#bestellen")
.scrollIntoView({block: "start", behavior: "smooth"})
$("body").on("click","#bestellenbtn",function(){
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(viewportWidth > 991) {
console.log('desktop');
var scrollmenuheight = $('.scrollmenu').height();
$([document.documentElement, document.body]).animate({
scrollTop: $("#bestellen").offset().top - scrollmenuheight
}, 1000);
}else{
console.log('mobiel');
document.querySelector("#bestellen")
.scrollIntoView({block: "start", behavior: "smooth"})
}
});
Update.
Do you have an idea why on desktop when I click, the animation is not
instant but only starts after about 1 second? Maybe the function is
too heavy?
That is probably because of animation duration. Try using 300 or 700 as timeout for the animate function.
If you need a similar behaviour as on mobile, use window.scrollTo with smooth behaviour.
Window.scrollTo() scrolls to a particular set of coordinates in the
document. - MDN - Window.scrollTo()
$("body").on("click","#bestellenbtn",function(){
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if(viewportWidth > 991) {
console.log('desktop');
var scrollmenuheight = $('.scrollmenu').height();
var offsetTop = $("#bestellen").offset().top - scrollmenuheight;
window.scrollTo({
top: offsetTop,
behavior: 'smooth'
});
}else{
console.log('mobiel');
document.querySelector("#bestellen")
.scrollIntoView({block: "start", behavior: "smooth"})
}
});
On mobile, it scroll faster because the distance between #bestellenbtn and #bestellen is more than the distance between those two elements on desktop.
From your question what I have understood is you want to scroll down to a particular section of your page on clicking an item in the menu. This can very easily be done with HTML. In your href of the link element replace javascript:void(0); with the id of the element where you want to scroll to i.e. #bestellen. Check my pen here. Once you click One, Two, Three or Four then you will be scrolled to that particular section.
html {
scroll-behavior: smooth;
}
I'm designing a nav that has the background bar appear after the user has scrolled down the page a bit. When they scroll back to the top, the bar (background color) disappears. I'm doing it using the instructions over at:
Add/remove class with jquery based on vertical scroll?
It works fine but now I would like to add fading in and out of the bar on scroll. I've tried adding the fadeIn() and fadeOut() methods. Problem is when it fades out, it fades out the whole #nav div! Not just the background colour. Here's the query
$(function() {
//caches a jQuery object containing the header element
var header = $('.noBackground');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('noBackground').addClass('blackBackground').fadeIn();
} else {
header.removeClass('blackBackground').fadeOut().addClass('noBackground');
}
});
});
Full, HTML, CSS and jQuery on this fiddle
The problem here is your #nav div is hidden when you scroll back to top. It is because the .fadeOut() method hides the matched elements by fading them to transparent. So you you remove .fadeOut() from else condition and it works fine.
Here is the edited code.
$(function() {
//caches a jQuery object containing the header element
var header = $('.noBackground');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
header.removeClass('noBackground').addClass('blackBackground').fadeIn();
} else {
header.removeClass('blackBackground').addClass('noBackground');
}
});
});
Edit:
A simple twist will show the effect:
$(function() {
//caches a jQuery object containing the header element
var header = $('.noBackground');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 500) {
if(header.hasClass('noBackground')) {
header.hide();
header.removeClass('noBackground')
.addClass('blackBackground').fadeIn(2000);
}
} else {
if(header.hasClass('blackBackground')) {
header.hide();
header.removeClass('blackBackground')
.addClass('noBackground').fadeIn(2000);
}
}
});
});
Demo Fiddle.
fadeOut() method can be implemented on a jquery element,not on a class..your code is working perfectly fine
I have a div that scrolls content when the cursor is either at the top or bottom (scrolling up or down). I have two customized cursor images- one is supposed to show when the div content is scrolling up and the other when the div content is scrolling down. The script below was written by a stackoverflow member and works only when using standard cursor styles such as wait, pointer, etc. I want to use images, but cannot get it to work correctly. I also do not need the timer in the script below.
<script type='text/javascript' >
var top=0, timer;
$('#repertoirescroll').on('scroll', function() {
clearTimeout(timer);
var scrollTop = $(this).scrollTop(),
cursor = scrollTop > top ? 'pointer' : 'wait';
$('body').css('cursor', cursor);
top = scrollTop;
timer = setTimeout(function() {
$('body').css('cursor', 'default');
}, 500);
});
</script>
The image names I am using are
url(../images/arrowup.png)
url(../images/arrowdown.png)
*HTML/CSS**
.cursorup {
cursor: url(../images/arrowup.png), auto;
position:relative;
}
.cursordown {
cursor: url(../images/arrowdown.png), auto;
position:relative;
}
scrolling content
Thanks for any help in advance.
To use custom cursors, you use CSS styling:
.curarrowup {
cursor: url(../images/arrowup.png), auto;
}
Then to apply, use jQuery to apply the style:
$(myElement).addClass("curarrowup");
When you want to go back to a normal cursor:
$(myElement).removeClass("curarrowup");
Using $('body') (myElement === 'body') as in your example is fine.
One caveat: in Firefox, the new cursor often will not appear until you actually move the mouse. This is a known bug and I cannot find any workarounds.
Edit: Modifying your code:
var top=0, timer;
$('#repertoirescroll').on('scroll', function() {
var scrollTop, cursor;
clearTimeout(timer);
scrollTop = $(this).scrollTop();
cursor = scrollTop > top ? 'curarrowup' : 'curarrowdown';
$('body').addClass(cursor);
top = scrollTop;
timer = setTimeout(function() {
$('body').removeclass(cursor);
}, 500);
});
I want to implement something like this page does: link
Look at the Clicker box. The box has two animations going on. One for the easeInQuad, then the other animation is for the easeInOutSine.
How can I implement something like that in my own function?
$(function()
{
var iH = window.innerHeight + 80;
var position = $(window).scrollTop();
$(window).scroll(function()
{
var scroll = $(window).scrollTop();
if(scroll > position)
{
$("body").animate(
{
scrollTop: iH
},1000,
"easeInOutQuart")
.animate(
{
scrollTop: parseInt($(window).scrollTop()) - 80
},1000,
"easeInOutQuart");
}
else if(scroll < position)
{
$("body").get(0).scrollTop = 0;
}
position = $(window).scrollTop();
});
});
The second animate doesn't work quite well. But it does scroll it up. But it scroll it up too much not just 80 pixels. It scroll it up to the top, then the animation gets into an infinite loop. After the second .animate it will continue to animate it again and again and again. Non stop.
I think its better to use a toggle effect
http://www.sohtanaka.com/web-design/examples/toggle/
$("body").stop(true)
This will clear all animation Queues on the object.
http://docs.jquery.com/Effects/stop
I'm curious how I can create a DIV (or anything really) that I can fade (or change opacity of) when a user scrolls down the page. This DIV would sit at the top of the page, but only be clearly visible when at the very top of the page.
Additionally, it would be ideal if I I could have this element fade back in onmouseover, regardless of the current scrolled position on the page.
jQuery would allow for a succinct solution, whilst hiding most browser discrepancies. Here's a quick mock-up to get you started:
<script type="text/javascript">
//when the DOM has loaded
$(document).ready(function() {
//attach some code to the scroll event of the window object
//or whatever element(s) see http://docs.jquery.com/Selectors
$(window).scroll(function () {
var height = $('body').height();
var scrollTop = $('body').scrollTop();
var opacity = 1;
// do some math here, by placing some condition or formula
if(scrollTop > 400) {
opacity = 0.5;
}
//set the opacity of div id="someDivId"
$('#someDivId').css('opacity', opacity);
});
});
</script>
See also:
jQuery
Selectors
CSS
Events/Scroll
CSS/ScrollTop
CSS/ScrollLeft
I thought I would give it a go using the actual value of scrollTop to dictate the opacity level, thus getting a smooth fade. I also added the hover state for the second part. Thanks to David for refining the maths for me.
//reduce the opacity of the banner if the page is scrolled.
$(window).scroll(function () {
var height = $("body").height();
var scrollTop = $("body").scrollTop();
var opacity = 1;
if(scrollTop < 41)
{opacity = 1-Math.floor(scrollTop)/100;}
else
{opacity = 0.6;}
$("#header").css("opacity", opacity);
$("#header").hover(function(){
$(this).css("opacity", 1);
},function(){
$(this).css("opacity", 0.6);
});
});
Use scroll event, and analyse value of document.documentElement.scrollTop to set appropriated opacity.
http://www.quirksmode.org/dom/events/scroll.html