How to detect scroll position of page using jQuery - javascript

I am having trouble with jQuery functionality on my website. What it does, is that it uses the window.scroll() function to recognize when the windows changes its scroll position and at the change calls a few functions to load data from the server.
The problem is the .scroll() function is called as soon as there is even a little change in the scroll position and loads data at the bottom; however, what I wish to achieve is to load new data when the scroll/page position reaches at the bottom, like it happens for Facebook feed.
But I am not sure how to detect scroll position using jQuery?
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
//Load some data from the server
})
};
$(window).scroll(function () {
getData();
});

You can extract the scroll position using jQuery's .scrollTop() method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});

You are looking for the window.scrollTop() function.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > some_number) {
// do something
}
});

Check here DEMO http://jsfiddle.net/yeyene/Uhm2J/
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
    //Load some data from the server
})
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
// getData();
}
});

$(window).scroll( function() {
var scrolled_val = $(document).scrollTop().valueOf();
alert(scrolled_val+ ' = scroll value');
});
This is another way of getting the value of scroll.

Now that works for me...
$(document).ready(function(){
$(window).resize(function(e){
console.log(e);
});
$(window).scroll(function (event) {
var sc = $(window).scrollTop();
console.log(sc);
});
})
it works well... and then you can use JQuery/TweenMax to track elements and control them.

Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.
//jQuery
jQuery(document).ready(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />

You can add all pages with this code:
JS code:
/* Top btn */
$(window).scroll(function() {
if ($(this).scrollTop()) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
var top_btn_html="<topbtn id='toTop' onclick='gotoTop()'>↑</topbtn>";
$('document').ready(function(){
$("body").append(top_btn_html);
});
function gotoTop(){
$("html, body").animate({scrollTop: 0}, 500);
}
/* Top btn */
CSS CODE
/*Scrool top btn*/
#toTop{
position: fixed;
z-index: 10000;
opacity: 0.5;
right: 5px;
bottom: 10px;
background-color: #ccc;
border: 1px solid black;
width: 40px;
height: 40px;
border-radius: 20px;
color: black;
font-size: 22px;
font-weight: bolder;
text-align: center;
vertical-align: middle;
}

$('.div').scroll(function (event) {
event.preventDefault()
var scroll = $(this).scrollTop();
if(scroll == 0){
alert(123)
}
});
This code for chat_boxes for loading previous messages

GET Scroll Position:
var scrolled_val = window.scrollY;
DETECT Scroll Position:
$(window).scroll
(
function (event)
{
var scrolled_val = window.scrollY;
alert(scrolled_val);
}
);

Related

Back to top button doesn't click - jquery

I am trying to achieve the "back to top" feature on a page through simple jquery. The "BACK TO TOP" button appears/disappears as expected.
When it appears if I click on it, I expect it to go to the top of the page, instead nothing happens. I am not sure what's going wrong.
Here's the code:
css:
#btoTop {
padding: 15px 10px;
background: #1f242a;
color: #fff;
position: fixed;
bottom: 0;
right: 15px;
display: none;
cursor:pointer;
cursor:hand;
width:130px;
height:40px;
}
html:
<div id='btoTop'>BACK TO TOP</div>
js:
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 0){
$("#btoTop").fadeIn("slow");
}
else {
$("#btoTop").fadeOut("slow");
}
});
$("#btoTop").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:0 },"slow");
});
});
Note: If I call the click function inside the $(window).scroll(), I am able to click the button. But it flickers and doesn't work well with window resize.
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 0){
$("#btoTop").fadeIn("slow");
}
else {
$("#btoTop").fadeOut("slow");
}
$("#btoTop").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:0 },"slow");
});
});
});
You're binding click on your button every single time you scroll, which is unnecessary. You should change it:
$(document).ready(function () {
$(window).scroll(function () {
if( $(window).scrollTop() > 0 ) {
$("#btoTop").fadeIn("slow");
} else {
$("#btoTop").fadeOut("slow");
}
});
// Bound a single time
$("#btoTop").click(function ( event ) {
event.preventDefault();
console.log("Clicked the button");
$("html, body").animate({scrollTop:0 },"slow");
});
});
This might not be the problem, but should be changed to avoid strange behaviours in your code.
I figured out the button was not yet available in the DOM when I was trying to click it.
Adding a timer on it worked pretty good. Hope this helps someone out there with similar issue...
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 0){
$("#btoTop").fadeIn("slow");
}
else {
$("#btoTop").fadeOut("slow");
}
});
$timeout( function() {
$("#btoTop").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:0 },"slow");
});
}, 500);
});

How to make this scroll to div script "smooth"

So I found this script by a user of this site however I can't remember the author. The script is working, however I want it to scroll more "smoothly" than just instantly appear at my desired information. And if possible, have the destination appear 300pixels above the div.
How do I do that?
#general{
margin-top:900px;
height: 100px;
weight: 100px;
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var hashTagActive = "";
$(".scroll").click(function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().center > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().center;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
</script>
<div>
<a class="scroll" href="#general">Hello</a>
</div>
<div id="general">
</div
For a smoother scroll you can use:
$(document).ready(function() {
$("ANCHOR LINK").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
});
});
And you see the last number? 1000, make it bigger to make it slower.
The second thing I'm afraid I can't help you with.
How to animate to #id links:
jsfiddle
HTML
Click me!<br>
Google.com
<div id="content"></div>
CSS
#content {
margin-top: 900px;
height: 100px; width: 100px;
background-color: lightgreen;
}
jQuery
$('a').on('click', function (event) {
var target = $(this.hash),
top;
if (target) {
top = target.offset().top;
event.preventDefault();
$('html, body').animate({
scrollTop: top
}, 600, 'swing');
}
});
For smooth scroll to 300px above top of the element, your JavaScript function should look like this :
$(".scroll").click(function (event) {
$('html,body').animate({
scrollTop: ($(this.hash).offset().top - 300)
}, 2000);
event.preventDefault();
});

Issue with jQuery scrolling

So I'm building a website for a friend and I want it to scroll on href clicks, that is easy, I managed to do it with smooth animation. But the problem is, when I load the page and click on the FIRST link, scrolling is not precise, and after I click on anything after Test1 is pressed, its not precise again.
Since it's hard for me to explain, ill post jsfiddle link so you can test it.
$(document).ready(function() {
$('.click').click(function(e){
// prevent default action
e.preventDefault();
scrollToElement( $(this).attr('href'), 1000 );
});
var scrollToElement = function(el, ms){
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top-102
}, speed);
}
});
Full code here: http://jsfiddle.net/pxmfs78k/
How to test my problem:
Press any link first time, and then you will see that the div is not positioned where I wanted it to be, and if you press the same link again, it will position itself correctly, and after that there are no problems in clicking until you reload or press test1 link, the first one.
So any idea what might cause the problem?
And I read this https://stackoverflow.com/questions/19750702/jquery-scrolling-issues-with-scrolltop thread and I couldn't fix my problem with the explanation given there.
It's because you're setting the nav to sticky, thus, removing it from the flow, and the whole content jumps up by 102px, to fix this, give the sticky class to the body instead of the nav and use padding to fight against it. http://jsfiddle.net/pxmfs78k/1/
CSS
body.sticky {
padding-top: 102px;
}
body.sticky .nav {
position: fixed;
width: 100%;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
}
JS
$(document).ready(function () {
var stickyNavTop = $('.nav').offset().top;
var stickyNav = function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('body').addClass('sticky');
} else {
$('body').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function () {
stickyNav();
});
});
$(document).ready(function () {
$('.click').click(function (e) {
// prevent default action
e.preventDefault();
scrollToElement($(this).attr('href'), 1000);
});
var scrollToElement = function (el, ms) {
var speed = (ms) ? ms : 600;
$('html,body').animate({
scrollTop: $(el).offset().top - 102
}, speed);
}
});

Navigation menu fade in on scroll

I'm designing a website and I'd like the navigation menu to fade in once I scroll down >50px. I'm using the following JavaScript with JQuery library:
(function ($) {
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 50) {
$('.menu').fadeIn(500);
} else {
$('.menu').fadeOut(500);
}
});
});
})(jQuery);
The class .menu is set on {display: none;}.
This should work
$(document).ready(function(){
$(window).bind('scroll', function() {
var distance = 50;
if ($(window).scrollTop() > distance) {
$('nav').fadeIn(500);
}
else {
$('nav').fadeOut(500);
}
});
});
Codepen Demo
It's working for me.
Your .menu is probably at the top of a page and when you scroll you can't see it.
Add to test:
.menu {
position: fixed;
z-index: 10000; //just to check if it is behind the content
}
DEMO
Try this:
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 50) {
$('.menu').fadeIn(1000);
} else {
$('.menu').fadeOut(1000);
}
});
});
Just corrected your code! It works fine!

jQuery scrolling text on hover

I have a "a" element that I want to scroll left on hover. To do this I remove the first character and append it to the end of the string.
How can I continuously fire up the scroll function?
Mouse enters element -> scroll() is fired until mouse leaves the element or user clicks on it.
html:
this text scrolls on hover
jQuery:
$(".scrollthis").hover(function(){
scroll($(this));
});
function scroll(ele){
var s = $(ele).text().substr(1)+$(ele).text().substr(0,1);
$(ele).text(s);
}
Use setInterval() to call it repeatedly from mouseenter, then clearInterval() to stop it on mouseleave:
var intervalID;
$(".scrollthis").hover(function(){
var $this = $(this);
intervalID = setInterval(function() {
scroll($this);
}, 100);
}, function() {
clearInterval(intervalID);
});
Note that you don't need to use $(ele) in your scroll() function because ele is already a jQuery object:
function scroll(ele){
var s = ele.text().substr(1)+ele.text().substr(0,1);
ele.text(s);
}
Demo: http://jsfiddle.net/hTBZn/
You can make your scroll() function a bit neater if you use the callback syntax of the .text() method (or even move that one line directly into the .hover code):
function scroll(ele){
ele.text(function(i,val) { return val.substr(1) + val.substr(0,1); });
}​
Demo: http://jsfiddle.net/hTBZn/1/
Here's the full code, you can try it out as a jsfiddle
function scroll(ele){
var s = $(ele).text().substr(1)+$(ele).text().substr(0,1);
$(ele).text(s);
}
scrollInterval = null;
function startScrolling(e) {
if (!scrollInterval) {
scrollInterval = setInterval(function(){
scroll(e)
},100);
}
}
function stopScrolling(e) {
clearInterval(scrollInterval);
scrollInterval = null;
}
$(".scrollthis").hover(function(){
startScrolling($(this));
});
$(".scrollthis").mouseout(function(){
stopScrolling($(this));
});
$(".scrollthis").mousedown(function(){
stopScrolling($(this));
});
​
css
div.container{
width: 130px;
}
div.title-holder {
width: 130px;
height:20px;
text-align:center;
background: silver;
overflow:hidden;
position: relative;
}
div.title-holder a {
position: relative;
white-space:nowrap;
left: 0px;
}
div.image{
background: brown;
width: 100%;
height: 100px;
}​
html
<div class="container">
<div class="title-holder">
long text that needs to scroll, long text that needs to scroll, long text that needs to scroll
</div>
</div>​
js
$(function(){
var scroll_text;
$('div.container').hover(
function () {
var $elmt = $(this);
scroll_text = setInterval(function(){scrollText($elmt);}, 5);
},
function () {
clearInterval(scroll_text);
$(this).find('div.title-holder a').css({
left: 0
});
}
);
var scrollText = function($elmt){
var left = $elmt.find('div.title-holder a').position().left - 1;
left = -left > $elmt.find('div.title-holder a').width() ? $elmt.find('div.title-holder').width() : left;
$elmt.find('div.title-holder a').css({
left: left
});
};
});​

Categories