Issue with jQuery scrolling - javascript

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

Related

How do we fixed the button at the top on Window scrolling?

i am trying to fix the button on top when we scroll the window ,as soon as the button reach on the top then to be fixed, please need your help, i am using javascript code for this or if you have suitable code related to javascript or jquery then please suggest me,
i am showing a snapshot that clear you that what i want to do in this images,
image is here please click to see clearly my problem
This is my button code
HELPLINE NUMBER
and
This is javascript code what i have tried:
<script>
window.onscroll= function(){ myfunc(); }
var location_v=document.getElementById("NUMBER");
var pixtop=location_v.offsetTop;
function myfunc()
{
if(window.pageYOffset >= pixtop )
{
//var a=document.getElementById('NUMBER');
location_v.classList.add('stick');
}
else
{
a.classList.remove('stick');
}
}
</script>
and the css code is below:
.stick {
position:fixed;
top: 10px;
width: 100%;
}
and please also don't forget to tell me what i am missing, if you have any conceptual javascript or jquery code...
Here is a script that can do the trick for you:
$(document).ready(function() {
$(window).scroll(function () {
if ($(window).scrollTop() > 90) {
$('#NUMBER').addClass('stick');
}
if ($(window).scrollTop() < 91) {
$('#NUMBER').removeClass('stick');
}
});
});
And what it does is on each scroll event it checks the scrolling position from top of a window and using if check it either adds or removes your pre-made stick class. But of course you have to chose your own numbers in this if check.
I have also played around with a code snippet, so you can see how it works
$(document).ready(function() {
$(window).scroll(function () {
if ($(window).scrollTop() > 10) {
$('#NUMBER').addClass('stick');
}
if ($(window).scrollTop() < 11) {
$('#NUMBER').removeClass('stick');
}
});
});
body {
height: 600px;
}
.stick {
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="NUMBER">Press me</button>

Modify existing jQuery to change URL on Scroll

I have a jQuery code obtained from w3schools.com which ON CLICK (clicking an ) changes URL's #id and also allows smooth scrolling to a particular DIV section. But its not working on scroll. I want the same with an scrolling effect. When I scroll down or up to a particular section the URL's #id should change.
Current jQuery Code:
$(document).ready(function(){
$("#navlist a").on('click', function(event) {
if(this.hash !== ""){
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});
I searched on stackoverflow and I got something like this:
$(document).bind('scroll',function(e){
$('div').each(function(){
if ($(this).offset().top < window.pageYOffset + 10 && $(this).offset().top + $(this).height() > window.pageYOffset + 10){
window.location.hash = $(this).attr('id');
}
});
});
This seems to work but when I place both the code either one of them is stopping the other one from executing. I thought of combining both the codes into one to achieve both onclick and scroll effect but I am not being able to do so (weak hands on jquery yet).
Example URL with ID: http://localhost/sites/fh/index.php#first
Please help me devs.
Instead of setting the location hash, you should change the history state. That way you will avoid forced page scrolling by browser. Check it below:
navlist = [];
$("#navlist a").each(function(i) {
var thisLink = $(this);
var thisId = thisLink.attr('href');
var thisTarget = $(thisId);
navlist.push({
'anchor': thisLink,
'id': thisId,
'target': thisTarget
});
thisLink.on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: thisTarget.offset().top
}, 800);
});
});
$(window).on('scroll resize', function(e) {
$.each(navlist, function(e, elem) {
var placement = elem.target[0].getBoundingClientRect();
if( placement.top<window.innerHeight && placement.bottom>0 ) {
history.pushState({}, '', elem.id);
console.log('Hash: ' + elem.id);
return false; /* Exit $.each loop */
};
});
});
nav a {
display: block;
}
section {
height: 600px;
border-top: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="navlist">
Go to Section 1
Go to Section 2
Go to Section 3
</nav>
<section id="s1">Section 1 Content</section>
<section id="s2">Section 2 Content</section>
<section id="s3">Section 3 Content</section>
Also on JSFiddle.
Please note, if you are using Foundation framework, than you already have Magellan.
For Bootstrap it is called ScrollSpy.

jQuery Overflow: Hidden on Parent, Detect if Child is Actually On Visible

I'm having an issue with this jQuery that is blowing my mind. I've tried three different JS and jQuery functions people suggested online for accomplishing this and can't seem to get anything to work.
I'm trying to hide the class .arrow-up when .first is actually visible on the screen and hide the class .arrow-down when .last is visible on the screen.
Sounds simple enough, right?
Well the parent element has overflow: hidden on it (like most carousels–they really are from hell). Anyone know how to do this? I'd really appreciate any help, JS really isn't my strongest by any means...
Here's my current jQuery–
jQuery(document).ready(function ($) {
$(".arrow-down").bind("click", function (event) {
event.preventDefault();
$(".vid-list-container").stop().animate({
scrollTop: "+=300"
}, 300);
});
$(".arrow-up").bind("click", function (event) {
event.preventDefault();
$(".vid-list-container").stop().animate({
scrollTop: "-=300"
}, 300);
});
});
In this, .vid-list-container is the parent with overflow: hidden on it and .first and .last are both inside the container. The arrow classes are both outside of the container.
Built this pen for anyone who wants to play around with it.
http://codepen.io/seancrater/pen/waPNEW
Thanks!
This should work. Notice however that I used opacity:0, so the arrow can still be clicked. You need to change that!
function checkDownArrow() {
setTimeout(function() {
if($(".vid-list-container").scrollTop() != 0){
$('.arrow-up').css('opacity',1);
}
if(($(".vid-list-container").scrollTop() + $(".vid-item").height()+5) >= $(".vid-item").length * $(".vid-item").height()) {
$('.arrow-down').css('opacity',0);
}
},350);
}
function checkUpArrow() {
setTimeout(function() {
if($(".vid-list-container").scrollTop() == 0){
$('.arrow-up').css('opacity',0);
}
if(($(".vid-list-container").scrollTop() + $(".vid-item").height()+5) < $(".vid-item").length * $(".vid-item").height()) {
$('.arrow-down').css('opacity',1);
}
},350);
}
checkDownArrow();
checkUpArrow();
jQuery(document).ready(function ($) {
$(".arrow-down").bind("click", function (event) {
event.preventDefault();
$(".vid-list-container").stop().animate({
scrollTop: "+=173"
}, 300);
checkDownArrow();
});
$(".arrow-up").bind("click", function (event) {
event.preventDefault();
$(".vid-list-container").stop().animate({
scrollTop: "-=173"
}, 300);
checkUpArrow();
});
});
EDIT
Okay, I see you have a different problem... may I suggest using a different approach? Something like this.
HTML:
<div class="outer-wrapper">
<div class="inner-wrapper">
<div class="vid-item">
...
</div>
<div class="vid-item">
...
</div>
</div>
</div>
CSS:
.outer-wrapper {width:200px; height:150px; overflow:hidden;}
.inner-wrapper {height:auto; margin-top:0;}
.vid-item {width:200px; height:150px;}
JS:
var itemHeight = $('.vid-item').first().height();
var wrapperHeight = $('.inner-container').height();
$(".arrow-down").bind("click", function (event) {
event.preventDefault();
var margin = parseInt($('.inner-container').css('margin-top'));
if(itemHeight - margin > wrapperHeight) {
$('.inner-container').css('margin-top', (itemHeight-wrapperHeight) + 'px');
$('.arrow-down').addClass('hidden');
}
else {
$('.inner-container').css('margin-top', (margin-itemHeight) + 'px');
}
$('.arrow-up').removeClass('hidden');
});
$(".arrow-up").bind("click", function (event) {
event.preventDefault();
var margin = parseInt($('.inner-container').css('margin-top'));
if(margin + itemHeight >= 0) {
$('.inner-container').css('margin-top', '0');
$('.arrow-up').addClass('hidden');
}
else {
$('.inner-container').css('margin-top', (margin+itemHeight) + 'px');
}
$('.arrow-down').removeClass('hidden');
});

How to detect scroll position of page using jQuery

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

Automatically Scroll Page from Top to Bottom, then Back Up (and Repeat)

I'm trying to figure out how to, upon pageload, automatically scroll to the bottom of a page (which has been described sufficiently here) and then scroll back up automatically upon reaching the bottom of the page. I can find the automatic scrolling to the bottom, but I can't figure out how to identify when I'm at the bottom of the page, and how to scroll back up when I am. I'd do this using generic Javascript (or JQuery).
Thanks in advance!
Try this:
http://jsfiddle.net/yjYJ4/
$('html, body').animate({ scrollTop: $(document).height() - $(window).height() }, 1000, function() {
$(this).animate({ scrollTop: 0 }, 1000);
});
You can view the demo in full screen here: http://jsfiddle.net/yjYJ4/embedded/result/
Change the number "1000" if you want to increase or decrease speed.
Works fine in Chrome, Firefox and IE 6-9.
EDIT:
If you need it to repeat forever (not recommended...) you could do like this: http://jsfiddle.net/QUCWe/
here is the example using Pure JavaScript
<script type="application/javascript">
var Height = document.documentElement.scrollHeight;
var currentHeight = 0;
var bool = true;
var step = 5;
var speed = 10;
var interval = setInterval(scrollpage, speed)
function scrollpage() {
if (currentHeight < 0 || currentHeight > Height)
bool = !bool;
if (bool) {
window.scrollTo(0, currentHeight += step);
} else {
// if you don't want to continue scroll
// clearInterval(interval) use clearInterval
window.scrollTo(0, currentHeight -= step);
}
}
</script>
<style type="text/css">
#top {
border: 1px solid black;
height: 10000px;
}
#bottom {
border: 1px solid red;
}
</style>
<div id="top">top</div>
<div id="bottom">bottom</div>
You can pass a function as an argument, which will be called when the end has reached. I've just written a jQuery plugin for this purpose. Fiddle: http://jsfiddle.net/kKaWZ/
(function($){
$.fn.downAndUp = function(time, repeat){
var elem = this;
(function dap(){
elem.animate({scrollTop:elem.outerHeight()}, time, function(){
elem.animate({scrollTop:0}, time, function(){
if(--repeat) dap();
});
});
})();
}
})(jQuery);
$("html").downAndUp(2000, 5)
Be aware that the suggested infinite scroll JSFiddle code will work in firefox however will not work in Chrome/Chromium without a valid
<!DOCTYPE html>
tag at the start of ones page. Per This Answer
$("body").animate({ scrollTop: '1000' }, 500, function(){
$("body").animate({ scrollTop: '0' }, 500, function(){
$("body").animate({ scrollTop: '1000' }, 500);
});
});

Categories