Scroll to bottom on page load - javascript

I have the following code, it's a chat display that I got using the Firebase API.
The problem is that, when the page loads, I want it to directly have the scrollbar set at the bottom. At the moment it is sort of sliding slowly to the bottom (because of the .animate).
How can I have the scrollbar always stay at the bottom when I reload the page, even if new content is added to the chat?
$(document).ready(function () {
var myDataRef = new Firebase('https://ot7fwnsj7h7.firebaseio-demo.com/');
myDataRef.on('child_added', function (snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name + ': ')).appendTo($('#displayChat'));
// make text scroll everytime someone posts
$('#displayChat').animate({
scrollTop: $("#displayChat")[0].scrollHeight
}, 'slow');
};
});
And here's my fiddle:
http://jsfiddle.net/qxkr35pj/
I hope I've been clear! Thanks.

This line of code scrolls the element to its bottom.
Call it every time you update the view.
JSFiddle
$("#displayChat")[0].scrollTop = $("#displayChat")[0].scrollHeight

I think what you want is this instead of your animate code:
$('#displayChat').scrollTop($("#displayChat").height());
You'd also want to use that every time a message gets added - it'll take the scrollbar to the bottom of the div.

Related

Scroll down to specific position after page refresh issue

I have the following code which works exactly as I need for refreshing a page using a submit button.
However I have added code in it to make it scroll down to a specific location after updating, the problem is, it scrolls down to the location, then springs back to the top of the page
any ideas why anybody please?
$(".visitpage").on('click', function() {
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
$('html, body').animate({
scrollTop: $("#search-results").offset().top
}, 2000);
});
function removeLoader() {
$("#loadingDiv").fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$("#loadingDiv").remove(); //makes page more lightweight
});
}
You will surely need the scrollTo method of the window object in javascript. Then I would figure out how far down your element is by getting a reference for that object in pixels on the page. See Retrieve the position (X,Y) of an HTML element for how to do that, since part of your answer would be a duplicate question I will let you read it. And this article is helpful http://javascript.info/coordinates
window.scrollTo(500, 0);
https://www.w3schools.com/jsref/met_win_scrollto.asp
Maybe I'm wrong here; but if you created a div where you want the page to scroll, or if you have on there make sure it's named, then right after the refresh command add
window.location.href = "#YOURDIVTAGHERE"; so
So if this is the part of the page you want it to go down to:
<div id="search-results">
CONTENT
</div>
so then your JS code, maybe try:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(".visitpage").on('click', function(){
$('body').append('<div style="" id="loadingDiv"><div class="loader"></div><center><span style="font-size:22px;color:#000000;z-index:99999;"><b>Updating your results...</b></span></center></div>');
setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
$( "#loadingDiv" ).fadeOut(500, function() {
// fadeOut complete. Remove the loading div
$( "#loadingDiv" ).remove(); //makes page more lightweight
});
window.location.href = "#search-results";
}

scrollTop duplicating values each time function is called

I have 2 divs that each time one of them is clicked it scrolls down to a common content div called .nbm_specs. The first time you click it scrolls correctly, however any subsequent clicks make the scrolling go crazy and it keeps scrolling up by a small amount each time.
It is acting like it is stacking the offset top each time you click on it.
I have established the scroll in a function that I then call in each .on CLICK function.
//hidel all at start
$(".prostar,.X10,.x20,.x23,.x30,.x46,.xstar").fadeOut(0);
//Scrol when clicekd
function SpecScrol(){
$('html, body').animate({
scrollTop: $(".nbm_specs").offset().top -80}, 1500);
}
//NAVIGATION SECTION FOR MODELS
$("#prostar").on('click', function() {
$(".prostar").fadeIn(0);
$(".X10").fadeOut(0);
SpecScrol();
});
$("#X10").on('click', function() {
$(".X10").fadeIn(0);
$(".prostar").fadeOut(0);
SpecScrol();
});
Thanks in advance
SOLVED.
The issue was that there are multiple .nbm_specs div and the code wasn't sure which to go to and getting all confused. Fixed this by creating a blank div just above the .nbm_specs div with a unique id.

scrollTop not working automatically

I know there are a couple of questions to scrollTop already out there but I haven't really seen anything resembling my problem.
Using jquery 1.7.2 on an IE9 we have a page with three Tabs (JqueryUI).
The Data is connected and that resulted in us only having the current tab on the page. Changing tabs will remove the unseen one and reload the one we jump into.
The Scroll-Positions are stored correctly in variables on the base page but trying to set that position in the document-ready-function does not work.
An alert shows the correct number, so the function is actually called but the scrollbar does not move.
Calling the same function with a button on the page afterwards however works perfectly.
The document-ready-function on the tab's jsp is quite simple:
<script type="text/javascript">
jQuery(document).ready(function(){
setAhaScrollbar();
});
</script>
and the called function is quite simple as well:
function setAhaScrollbar() {
var scrollWert = $('#scrollbarAnhaengeartikel').val();
alert(scrollWert);
$('#anhaengeGridScrollable').scrollTop(scrollWert);
}
Called from document-ready it does nothing. Called from a button later on it works fine.
The div where the scroll position is supposed to be set is defined with overflow: auto and a fixed height
crollTop( value )
Description: Set the current vertical position of the scroll bar for each of the set of matched elements.
.scrollTop( value )
value
Type: Number
An integer indicating the new position to set the scroll bar to.
More Information
As the documentationsaid value should be number.
Try
var scrollWert = Number($('#scrollbarAnhaengeartikel').val());
or
var scrollWert = parseInt($('#scrollbarAnhaengeartikel').val());
Apparently it was primarily a timing problem. Maybe there were still things going on when document ready fired.
Changing that function to
jQuery(document).ready(function(){
setTimeout("setAhaScrollbar()", 500);
});
did the trick so my problem is solved.

jquery, time out another jquery function if a user clicks a div?

I have the following script which fades in multiple divs called 'noti_box'. If a user closes these divs then another div 'advert' fades in in its place.
<script>
$(document).ready(function(){
var animations = [];
$('.noti_box').each(function(i) {
animations.push(
$(this).hide().delay(i * 1000).fadeIn(1500).promise()
);
});
$.when.apply($, animations).done(function () {
time=setInterval(function(){
if ( $('.noti_box:visible').length === 0 ) {
$(".advert").fadeIn("slow");
} },200);
});
});
</script>
this works fine, basically what happens here is my last function is stuck on a loop, where the 'advert' div fades in when 'noti_box' is not visible on the page.
However, now I want a user to click a div called 'icons' and if they do, then this should re-fade in the 'noti_box' divs and fade out the 'advert' div using this code:
<script>
$('.icons').click(function(){
$('.advert').fadeOut('fast');
$('.noti_box).fadeIn('fast');
});
</script>
The problem I have here is the 'advert' div fades in and out again in the blink of an eye, without fading in my 'noti_box' div. This is because my first javascript function is still on a loop and preventing my second script from executing.
So what I need to do, I think is set a time out interval for my first script when a user clicks my div 'icon' and then clear the time out interval once the script has executed and the 'noti_box' divs are once again showing.
Can someone please show me how I would be able to do this as I am brand new to jquery. Thanks
function notiBox(ele){
this.ele=ele;
this.ele.hide().fadeIn('slow');
console.log("I have been born! "+ele);
}
notiBox.prototype={
constructor:notiBox,
advert:function(){
var ele=this.ele;
this.ele.fadeOut('fast',function(){ele.next('.advert').fadeIn('slow');});
},
fadeBack:function(){
var ele=this.ele;
this.ele.next('.advert').fadeOut('slow',function(){ele.fadeIn('slow');});
},
}
$(document).ready(function(){
var timeIn=1;
$('.noti-box').each(function(){
var self=this;
this.timer=setInterval(function(){self.notiBox=new notiBox($(self));clearInterval(self.timer);},1000*timeIn);
timeIn++;
});
$('.icon').click(function(){
$('.noti-box').notiBox.fadeBack();
});
});
Right the above is a 'OOP' based approach to your problem. The only problem you might have with this is that your advert divs are not next to the box div. Sorry I guess your DOM elements and layout. Also my methods my not be correct because it's been so long since I've written something like that. I'll do some tests. In the mean time, could you put up some HTML? So that I can adjust my code :d

Clicking on anchor takes me to the bottom instead of restoring the previous position

I am kind of really stuck with this problem. Any help will great.
I am clicking on a link which expand the content and when i am cliking on a hide button, instead of taking me to the Expand link, it takes me to the bottom.I have already tried such options like onclick="fun() return false" and href=javascrpit:void(0), but not could help.
PLease refer http://jsfiddle.net/BdsyJ/ this link and click on "How do I maximize battery life" and at the bottom you will get a hide button which should take the control back to the Click it rather than placing the page at the bottom.
Thank you guys.
I changed your ReverseDisplay() method to this and it works nicely:
function ReverseDisplay(d) {
$("#" + d).toggle();
$('html, body').animate({
scrollTop: $("#" + d).prev().offset().top
}, 100);
}
here's a working example:
http://jsfiddle.net/hunter/BdsyJ/5/
In case you were wondering; YES your HTML is invalid. <li> elements should not have <div> siblings.
You're at the bottom of the page because you have hidden so much content. Two things I would update in your code:
cache the element look up so you only do it once and and
scroll the page to the top after you close it using scrollTo(0,0) or
something more complex if you need to scroll back to the exact
element you toggled.
Code:
function ReverseDisplay(d) {
var el = document.getElementById(d);
el.style.display = (el.style.display == "none")?"block":"none";
}

Categories