Event on scrolling up or down - javascript

I wanna detect when the user scrolls. I saw there are some questions about this but those answers didn't help me.
Here is my code:
var up = document.getElementById('up');
var down = document.getElementById('down');
function onScroll() {
if (view.scrollTop > 0) {
console.log("up");
}
if (view.scrollTop < 0) {
console.log("down");
}
}
var view = document.getElementById('container');
view.addEventListener("wheel", onScroll);
EDIT: "scroll" instead "wheel" isn't working for me... I must have the "wheel". When I make:
if (view.scrolltop <=0) {
console.log("down");
}
that I get in my console "down" but it appears when I scrolling up too! I have my page in 100% of screen and I have no scrollbars (and I don't want to have).
EDIT2: Here is the code that solved my problem!
window.addEventListener('wheel', function (e) {
if (e.deltaY < 0) {
console.log("scrolling up");
}
if (e.deltaY > 0) {
console.log("scrolling down");
}
});

you can use the
window.onscroll
to get the scrolling event, then just use
.scrollTop
to determine your offset from the top of page or an element.
window.onscroll = function() { scrollFunction() };
scrollFunction() {
//code to check if it is scrolling up or down
}
Hopefully this was a helpful start.

I did this with the jquery method
var last = 0;
$(window).scroll(function(event){
var Pos = $(this).scrollTop();
if (Pos > last ){
// down
} else {
// up
}
last = Pos;
});

Supporting #Belmin Bedak's comment.
Use .scroll instead of .wheel:
var up = document.getElementById('up');
var down = document.getElementById('down');
function onScroll() {
if (view.scrollTop > 0) {
alert("up");
}
if (view.scrollTop <= 0) {
alert("down");
}
}
var view = document.getElementById('container');
view.addEventListener("scroll", onScroll);
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
<div id='container'>a<br>
b<br>
c<br>
d<br>
e<br>
f<br>
g<br>
h<br>
i<br>
k<br>
l<br>
</div>

Related

How to change when Jquery edits my CSS upon reaching an anchor point?

I've found this piece of Jquery to change CSS when it reaches an anchor point.
$(window).on("scroll", function() {
var scrollPosition = scrollY || pageYOffset;
if (scrollPosition > $("#someAnchor").position().top - $(window).height()) {
alert("run code here");
}
});
The problem is it does so when the bottom of the screen reaches the anchor point, but it needs to run the code when the top touches the anchor point. How do I do this?
Hoping this works well for you:
var ranOffsetCode = false
$(window).on("scroll", function() {
var docScrollTop = $(document).scrollTop(); // Figure out how far we scrolled.
var someAnchorTop = $('#someAnchor').offset().top - $('#someAnchor').height(); // Figure out how far down the element is on the page
if (docScrollTop >= someAnchorTop) { // If we scrolled up to or past the element, fire this
if (ranOffsetCode === false) { // This makes sure we only run the function once and not every scroll
ranOffsetCode = true;
console.log('run code here'); // Functional code to execute after we scrolled down this far.
}
}
else {
ranOffsetCode = false;
}
});
Demo
Simply remove - $(window).height()
$(window).on("scroll", function() { var scrollPosition = scrollY || pageYOffset;
if (scrollPosition > $("#someAnchor").position().top) { alert("run code here"); } });
Not really meant to be an answer, but it might help:
var spam = false;
$(window).on("scroll", function() {
var scrollPosition = scrollY || pageYOffset;
$('#pos').html( 'y: '+scrollY+', a: '+$("#someAnchor").position().top + ', p: '+scrollPosition );
if (!spam && (scrollPosition > $("#someAnchor").position().top)) {
alert('hit it!');
spam = true;
}
});
Some html:
<div style="position:fixed; top:0; left:85%; width:15%; height:20px">
<span id="pos" style="font-family:Courier; font-size:0.5em; white-space:pre"></span>
</div>

Add and remove class to jquery onscroll

I need to add a 'fixed' class for the header on scroll and remove it when it's scrolled back up in the following script, but not sure how best to do it:
<script>
$(document).ready(function () {
var div = $('.header');
var div2 = $('.headerPlaceholder');
var start = $(div).offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
$(div).css('position', ((p) > start) ? 'fixed' : 'static');
$(div).css('top', ((p) > start) ? '0px' : '');
$(div2).css('display', ((p) > start) ? 'block' : 'none');
});
});
</script>
This stop it triggering the event after each scroll down which is what happens now with the CSS specified in the script, hence I need to add a class.
CSS:
.fixed {
position: fixed;
}
Ideas appreciated.
I have translated your js to use css with the application of 1 class to the body
$(document).ready(function () {
var start = $('.header').offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
if( p > start ) {
$('body').addClass('fixed');
} else {
$('body').removeClass('fixed');
}
});
});
CSS
body.fixed .header {
position: fixed;
top: 0;
}
body.fixed .headerPlaceholder {
display: block;
}
The add/remove class method works great.
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.header').addClass("fixed");
} else {
$('.header').removeClass("fixed");
}
});
});
Here's a fiddle showing how it works: http://jsfiddle.net/gisheri/RpPEe/413/

Prevent scrolling jquery script from running twice

I'm new to jquery and have put together the following code to make a DIV appear after a set scroll-down amount. If scrolling back up, the DIV disappears. Optionally, once the DIV has appeared, there is a link to close it. This all works as intended, apart from that I only want the script to run once. At the moment if I scroll back up, the yellow box appears again. How can I ensure the box stays closed? As another option, could I integrate cookies or localStorage?
Many thanks! Russ.
Javascript:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
return false;
});
});
Here is the jsfiddle link to my code: jsfiddle link
You can remove the class to ensure the box stays enclosed with removeClass(). Or directly $(".box").remove() after your animation.
You can store this choice with cookie but if the client deletes his cookies, it's lost.
You can remove event scroll from window and for localStorage do something like that:
$(function () {
var target = $(".box");
if ($(window).scrollTop() > 30) {
target.hide();
}
$(window).scroll(function () {
var pos = $(window).scrollTop();
if (pos > 30) {
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
}
if(localStorage['noNotification'] == 'true'){
$(window).off('scroll');
}
});
$('a.close').click(function () {
$($(this).attr('href')).slideUp();
$(window).off('scroll');
localStorage['noNotification'] = 'true';
return false;
});
});
try this http://jsfiddle.net/AbwXu/4/
var notdisplayed=true;
$(function(){
var target = $(".box");
if($(window).scrollTop() > 30){
target.hide();
}
$(window).scroll(function(){
var pos = $(window).scrollTop();
if(pos > 30 && notdisplayed){
target.stop(true, true).fadeIn('slow');
} else {
target.stop(true, true).fadeOut('slow');
notdisplayed=false;
}
});
$('a.close').click(function() {
$($(this).attr('href')).slideUp();
notdisplayed=false;
return false;
});

Style element with javascript

I am trying to make a gototop button with javascript (not jQuery).
I want this button to have a delay effect which I achieve by:
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
The html is a simple:
<div id="gototop">Back to top</div>
I am not able to make to button show/hide depending on scroll height. As far as I have been able to find out, the following should hide the button from view until the page has been scrolled down 600px, but this does not work:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
Why does this styling not take effect?
The complete code I am using is:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
Thanks for your attention, greetings.
Try putting it into the onscroll event handler, like:
Add style to your gototop element, for example:
<div id="gototop" onclick="scrollToTop()" style="display:none;"> </div>
window.onscroll = function(){
if (window.scrollY < 900) {
document.getElementById("gototop").style.display = 'none';
else
document.getElementById("gototop").style.display = 'block';
}
This is the complete working code for a Back-to-top button.
<style type="text/css">
#gototop{display:none;position:fixed;right:28px;bottom:10px;z-index:100;}
#gototop a{font-size:14px;font-weight:bold;display:block;padding:5px;text-decoration:none;color:#fff;background:#000;opacity:0.5;border:1px solid #aaa;}
#gototop a:hover{color: #000;text-decoration:underline;background-color:#fff;border: 2px solid #aaa;opacity:0.5;}
</style>
<script type="text/javascript" language="javascript">
// document.documentElement.scrollTop makes it work in Chrome and IE
// 400 is the point from which the button starts showing, you can change it to your needs
gototop = document.getElementById("gototop");
window.onscroll = function(){
if (window.scrollY < 400 || document.documentElement.scrollTop < 400) {
gototop.style.display = 'none';
}
if (window.scrollY > 400 || document.documentElement.scrollTop > 400)
gototop.style.display = 'block';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
</script>
<div id="gototop">Back to Top</div>

Javascript parameter help needed

I've this function:
$(function() {
$(window).scroll(function(e) {
var sl = $(this).scrollLeft();
var lbl = $("#waypoints");
if (sl > 0) {
lbl.show('');
}
else {
lbl.hide();
}
if (sl > 750) {
lbl.html("<p>now passed 750</p>");
}
if (sl > 1000) {
lbl.html("<p>now passed 1000</p>");
}
});
});
Which work when i scroll the browser window. But I need to adjust it, so that it is set for a div (#main) which scrolls inside another div (.content) which has a fixed width and css overflow enabled.
I've tried $(#main).scroll(function(e) { no joy ...
thanks for reading, any help would be awesome.
Try to change to class:
$(function() {
$('.content').scroll(function(e) {
var sl = $(this).scrollLeft();
var lbl = $("#waypoints");
if (sl > 0) {
lbl.show();
}
else {
lbl.hide();
}
if (sl > 750) {
lbl.html("<p>now passed 750</p>");
}
if (sl > 1000) {
lbl.html("<p>now passed 1000</p>");
}
});
});​
Here's a JSFiddle
I don't see what's the problem here - it's working (I mean the scroll events are fired, as you can see by scrollLeft value that is changing) http://jsfiddle.net/DTKeX/2/

Categories