only scroll to bottom if user not scrolling - javascript

I find myself getting frustrated with JS yet again! please help!
below is some code I am using for a simple chat app, that refreshes the content from a text file via an AJAX request. At the same time it scrolls to the bottom of the window. I want it so if the user scrolls up to catch up it doesnt keep interupting this behavour by sending them down to the bottom when it refreshes. How could I do this.
<script>
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,3000);
$.post('pollchat.php', function(data) {
$('#content_div_id').html(data);
var wtf = $('#content_div_id');
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
});
}
</script>
Any help greatly appreciated.

See How I have used current scroll position and counted that whether user has scrolled or not..
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 1000);
var wtf = $('#content_div_id');
var currentScrollPos = wtf.scrollTop();
var elementHeight = wtf[0].scrollHeight;
var scroll = false;
//User has scrolled, don't set scroll
if (wtf.height() + currentScrollPos >= elementHeight) {
scroll = true;
}
var data = $('#content_div_id').html();
data += "Some Text<br/>";
$('#content_div_id').html(data);
if (scroll) {
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
}
}
#content_div_id {
max-height: 100px;
overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content_div_id">
Some Text
<br/>Some Text
<br/>Some Text
<br/>Some Text
<br/>
</div>
UPDATE:
Try this code, you probably need to fix one or two things .. but have a look at the code and get an idea
$(function() {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh,3000);
$.post('pollchat.php', function(data) {
var wtf = $('#content_div_id');
var currentScrollPos = wtf.scrollTop();
var elementHeight = wtf[0].scrollHeight;
var scroll = false;
//User has scrolled, don't set scroll
if (wtf.height() + currentScrollPos >= elementHeight) {
scroll = true;
}
$('#content_div_id').html(data);
if (scroll) {
var height = wtf[0].scrollHeight;
wtf.scrollTop(height);
}
});
}

Related

How can I return false when scrolling down?

I found a lot of examples of console logging scroll direction. But even though I tried modifying almost all of them to return a value instead, I couldn't make them work.
My goal is to check the scrolling direction when entering a specific viewport, and return false if the scrolling direction is down. Then I want to use the false value in a exitviewport function to only then send ONE ReactGA event of scrolling. My attempts have either resulted in 'cannot read property of undefined' error or to a lot of events which I do not want. I think my main problem is combining a return with the fact that there is a reassignment that needs to be reached by the code.
My code so far is:
//this code I found and it seems to work
onEnterViewPort () {
window.onscroll = function (e) {
console.log(this.oldScroll > this.scrollY);
this.oldScroll = this.scrollY;
};
}
//used console logs to check.
onExitViewPort () {
console.log('I have left the viewport.')
// ReactGA.event({
// category: 'Scroll',
// action: 'Scrolled down',
// });
}
which I use in
<ScrollTrigger onEnter={this.onEnterViewPort} onExit={this.onExitViewPort} triggerOnLoad={false}>
<div >
<thingshere>
</div>
</ScrollTrigger>
Please help a noob out!
Example with jQuery.
This will start to display the scrolling direction after u entered the Viewpoint the first time, so you would need to create another funtion for the onExitViewpoint event...
$.fn.onEnterViewport = function (callback) {
var $window = $(window);
return this.each(function () {
var that = this;
var oldHeight = 0;
$(document).on('scroll', function () {
var docHeight = $window.height();
var myTop = $(this).scrollTop();
var myOffset = $(that).offset();
var top = myOffset.top - myTop;
if(top < docHeight){
callback(oldHeight, top);
}
oldHeight = top;
});
});
};
$('.viewpoint-in').onEnterViewport(function(oldHeight, newHeight) {
if (oldHeight > newHeight) {
console.log('Scroll Down')
} else {
console.log('Scroll Top')
}
});
*{
padding: 0;
margin: 0;
}
.viewpoint-out {
background: red;
height: 1000px;
}
.viewpoint-in {
background: white;
height: 600px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="viewpoint-out"></div>
<div class="viewpoint-in"></div>
<div class="viewpoint-out"></div>
</section>

Update div content in real time with jQuery

I'm pretty new to web design, and I wanted to make a rectangle which says "true" if the user has scrolled, and turn to "false" after one second has passed.
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
}, 1000);
});
});
body { height: 800px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle"></div>
However, even though the variable "hasScroll" changes exactly how I want, I can't seem to find a way to make the div show the hasScroll status in real-time.
You'll need to set the #rectangle's text again after the scrolling is done. You'll also probably want to set/clear a setTimeout that only runs once no scroll events have been triggered for 1000ms:
let scrollingTimeout;
const rectangle = document.querySelector('#rectangle');
$(window).scroll(function() {
if (scrollingTimeout) clearTimeout(scrollingTimeout);
else rectangle.textContent = 'true';
scrollingTimeout = setTimeout(function() {
console.log('setting text to false');
rectangle.textContent = 'false';
scrollingTimeout = null;
}, 1000);
});
body {
height: 800px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle">abc</div>
It's very simple, Just put the same line $("#rectangle").html(hasScroll.toString()); after setting hasScroll = false;
For ex.,
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
$("#rectangle").html(hasScroll.toString()); // To show false
}, 1000);
});
});

Timeline change css on enter view port

Am trying to change the background color of the timeline on scroll like on this site.My replication of the sample is development site. Take a look at the codepen I tried using. The closest I have come to replicating it is with the code below which makes the change in color on each timeline circle flicker on/off on scroll.
jQuery(document).ready(function($) {
function onScroll() {
$('.cd-timeline-block').each( function() {
if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.05 && $(this).find('.cd-timeline-img').hasClass('cd-inactive') ) {
$(this).find('.cd-timeline-img').removeClass('cd-inactive').addClass('cd-active');
$(this).find('.cd-date').addClass('cd-ssf-color');
} else {
$(this).find('.cd-timeline-img').addClass('cd-inactive').removeClass('cd-active');
$(this).find('.cd-date').removeClass('cd-ssf-color');
}
});
};
$(window).scroll(onScroll);
});
I have made some modification to the above code.
CodePen link:
http://codepen.io/anon/pen/KzqWVm
Javascript:
jQuery(document).ready(function($) {
var $timeline_block = $('.cd-timeline-block');
var firstelm = $timeline_block.first();
//on scolling, show/animate timeline blocks when enter the viewport
$(window).on('scroll', function() {
var _win = $(window), iselm = null;
$timeline_block.each(function(index) {
var _this = $(this);
if (((_this.offset().top - _win.height())) <= (_win.scrollTop())) {
iselm = _this;
}
});
if (_win.scrollTop() < $(firstelm).offset().top) {
iselm = $(firstelm);
}
if (iselm) {
$('.cd-active').removeClass('cd-active').addClass('cd-inactive');
iselm.find('.cd-timeline-img').removeClass('cd-inactive').addClass('cd-active');
if ((iselm.offset().top - _win.height()) > (_win.scrollTop() * 0.75)) {
$('.cd-date').removeClass('cd-ssf-color');
}
iselm.find('.cd-date').addClass('cd-ssf-color');
}
});
});
Continuing each loop on scroll might not work properly.

Cannot stop javascript function with conditional statement?

I have a fixed top navigation bar that uses a javascript function to shrink in size along with changing a couple other styles when the user scrolls past a certain anchor point. I also have a mobile hamburger icon that expands the navigation into a fullscreen menu for mobile. I would like the javascript function for shrinking the top nav to stop working whenever I click on the hamburger (opening the menu) and to resume when clicked again (closing the menu), however I am not able to get the scroll function to start or stop.
This is the code I've written so far:
<script>
var win = $(window),
nw = $('.navBgWrapper'),
sw = $('.scrollWaypoint'),
pos = sw.offset().top;
var sticky = function(){
if (win.scrollTop() > pos) {
nw.addClass('navBgWrapperChange');
$('.vjLogoWhite').removeClass('logoGo');
$('.vjLogoGreen').addClass('logoGo');
$('.navLink').removeClass('linkTop');
$('.navLink').addClass('linkScroll');
$('.navContent').on('hover', '.navLink', function () {
$('.navLink').removeClass('hoverTop');
$('.navLink').addClass('hoverScroll');
});
}
else {
nw.removeClass('navBgWrapperChange')
$('.vjLogoGreen').removeClass('logoGo');
$('.vjLogoWhite').addClass('logoGo');
$('.navLink').removeClass('linkScroll');
$('.navLink').addClass('linkTop');
$('.navContent').on('hover', '.navLink', function () {
$('.navLink').removeClass('hoverScroll');
$('.navLink').addClass('hoverTop');
});
}
}
//burger script
var sc = true;
$('.menu').click(function(){
$(this).toggleClass('open');
if (!sc) {
sc = true;
} else {
sc = false;
}
$('.menu-item').toggleClass('menuItemToggle');
$('.navMenuBg').toggleClass('navMenuBgGo');
$('.vjLogoWhite').toggleClass('logoGo');
$('.vjLogoGreen').toggleClass('logoGo');
$('.navLinks').toggleClass('navLinksShow');
});
</script>
<script>
if (sc) {
win.scroll(sticky);
}
</script>
Any help would be appreciated, thanks!
See comments of question for details, thanks Pointy.
var sticky = function(){ if (!sc) { return; } else {...}

jQuery trigger action when a user scrolls past a certain part of the page

Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page. Is this even possible with jQuery? I have looked at .scroll in the jQuery API and I don't think this is what I need. It fires every time the user scrolls, but I need it to fire just when a user passes a certain area.
Use the jquery event .scroll()
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
http://jsfiddle.net/babumxx/hpXL4/
Waypoints in jQuery should do it:
http://imakewebthings.github.com/jquery-waypoints/
$('#my-el').waypoint(function(direction) {
console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});
jQuery waypoints plugin documentation: http://imakewebthings.com/waypoints/guides/jquery-zepto/
To fire any action only once on a single page I have modified jondavid's snippet as following.
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
//do your stuff over here
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
Scroll down to Run code snippet
Here you can check example of working code snippet;
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
alert('This alert is triggered after you have scroll down to 150px')
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
p {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>scroll down this block to get an alert</p>
</body>

Categories

Resources