Hi I am trying to implement a simple chatbox in django and was wondering how to scroll to the bottom of a div class using javascript? Basically when the page loads I would like so that users can see the most recent message sent to them instead of the least recent.
I had to do this recently for a similar thing. I found a basic jquery plug-in that will smoothly scroll an element onto the screen.
(function($) {
$.fn.scrollMinimal = function() {
var cTop = this.offset().top;
var cHeight = this.outerHeight(true);
var windowTop = $(window).scrollTop();
var visibleHeight = $(window).height();
if (cTop < windowTop) {
$('body').animate({'scrollTop': cTop}, 'slow', 'swing');
} else if (cTop + cHeight > windowTop + visibleHeight) {
$(jQuery.browser.webkit ? "body": "html")
.animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
}
};
}(jQuery));
which is used like this:
$('#chat').scrollMinimal();
Well, the basic script is set the scrollTop equal to scrollHeight, so you need a script like this:
var DIV = document.getElementById('theDIVElement');
DIV.scrollTop = DIV.scrollHeight;
You only need to change theDIVElement to your DIV id.
This is the script I used in my chat:
<SCRIPT LANGUAGE="JavaScript">
<!--
function myScroll() {
window.scrollBy(0,01)
setTimeout('myScroll()',100); }
if (document.layers || document.all)
myScroll()
//--></SCRIPT>
This is also nice for when new messages are added, if you scroll to the bottom too fast, it's hard on your eyes while you're trying to read.
Related
I am making a website but I don't know much about javascript or jquery. I have a down arrow on my homepage showing that there is more information but I want it to go away when the user scrolls to the bottom of the page because it is then not needed because they can't scroll down anymore. I know I will need javascript or jquery to do this but I don't even know where to start with it. Help!
Try something like this :
document.onscroll = function() {
if (window.innerHeight + window.scrollY > document.body.clientHeight) {
document.getElementById('arrow').style.display='none';
}
}
Where 'arrow' is the id of the image.
Using jquery:
$(window).scroll(function(){
var numPix = 200; // number of pixels before bottom of page that you want to start fading
var op = (($(document).height() - $(window).height()) - $(window).scrollTop()) / numPix;
if( op <= 0 ){
$("#thing-to-hide").hide();
} else {
$("#thing-to-hide").show();
}
$("#thing-to-hide").css("opacity", op );
});
I am rather new to jquery and i'm trying to find the right offset for a div element inside the body. I want to make this div element sticky whenever I scroll down and pass the top offset of this element.
I followed this tutorial: https://www.youtube.com/watch?v=utonytGKodc and it works but I have a metaslider in my header and the width/height of this element is left out of the calculations to find the right offset....
the result is that my element becomes a sticky element way to soon, is there a way I can manualy add the sliders coordinates (offset) to the offset calculation of the element i want to make sticky?
var offerteOffset = jQuery(".agendawrap").offset().top //+ metaslider coordinates??;
alert(offerteOffset);
jQuery(window).scroll(function() {
var scrollPos = jQuery(window).scrollTop();
if (scrollPos >= offerteOffset) {
jQuery(".agendawrap").addClass("fixed");
} else {
jQuery(".agendawrap").removeClass("fixed");
}
});
I cant believe people make such bad tutorials.
First of all: dont write jQuery all the time. Have a look at this thread.
Basically it says: use an invoking function with an own scope:
(function($) { /* all your jQuery goes here */ })(jQuery);
So you can just type $ instead of jQuery.
To your original question:
(function($) {
$(function() { // document ready...
var scrollTolerance = 50,
agendawrap = $(".agendawrap"),
offerteOffset = agendawrap.offset().top;
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
// OR: if (scrollPos - scrollTolerance >= offerteOffset) {
if (scrollPos + scrollTolerance >= offerteOffset) {
agendawrap.addClass("fixed");
}
else {
agendawrap.removeClass("fixed");
}
});
});
})(jQuery);
I have a function that scrolls to make an object visible on screen. However, it is slow. Is there any way to jump to without scrolling the entire page ?
If there is a reasonably portable method that does not use jquery, I would prefer a native one. My definition of reasonably portable is that it works on fairly recent chrome and firefox.
function scrollToId(id) { //TODO: Fix Jquery madness below
var element = $('#' + id); //document.getElementById(id);
var offset = element.offset().top;
if (offset > window.innerHeight) {
// Not in view so scroll to it
$('html,body').animate({
scrollTop: offset
}, 10);
return false;
}
return true;
}
Your best bet for jumping to an area quickly on the page is to use the window.scroll(x, y) method. This does not animate the page, however, it will get your user to that area on the page very quickly.
function scrollToId(id) { //TODO: Fix Jquery madness below
var element = $('#' + id); //document.getElementById(id);
var yPos = element.offset().top;
var xPos = 0; //This could be the left position of an element like element.offset().left
if (offset > window.innerHeight) {
// Not in view so scroll to it
window.scroll(xPos, yPos);
return false;
}
return true;
}
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_scrollto2
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
Is there any way to jump to without scrolling the entire page ?
Try utilizing <a> element with #id set at href attribute , where #id is id of DOM element
#abc {
position:relative;
top:350px;
color:green;
}
#def {
position:relative;
top:650px;
color:orange;
}
abc def
<div id="abc">abc</div>
<div id="def">def</div>
I am not sure how much of a difference this would make, but try snippet below. Instead of scrolling it, just go to it.
function scrollToId(id)
{
var element = $('#' + id);
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
simple question, easy points, cannot find the answer in SO. The javascript function below alerts when a user scrolls to the bottom of a div. I have many divs, but I only want the alert to run when a div id=imageloc is scrolled.
$(window).scroll( function() {
if ( document.documentElement.clientHeight + $( document ).scrollTop() >= document.body.offsetHeight ) {
if (this.id == "imageloc" ) {
alert("bottom of the page.");
}
}
});
The javascript function below alerts when a user scrolls to the
bottom of a div. I have many divs, but I only want the alert to run
when a div id=imageloc is scrolled.
Maybe I have misunderstood, but it's phrased like you have many scrollable divs and want to do something if one of them is scrolled to the bottom. Then you should listen to scroll event on this particular div:
$("#imageloc").scroll( function(e) {
if ( this.scrollTop >= this.scrollHeight - this.offsetHeight ) {
console.log( 'bottom' )
}
});
http://jsfiddle.net/aheh5/
If you want to do something when the document has been scrolled past the bottom of a particular div try this: http://jsfiddle.net/aheh5/1/ (it will, however, trigger every time the user scrolls the window and #imageloc is above the viewport).
Use like this
$(window).scroll(function() {
var winTop = $(this).scrollTop();
var $divs = $('div');
var top = $.grep($divs, function(item) {
return $(item).position().top <= winTop;
});
alert($(top).attr('id'));
});
You can try something like this,
var imgLocTop = $('#imageloc').offset().top ;
var $window = $(window);
var limit = Math.abs($window.height() - imgLocTop);
$window.scroll( function() {
if($window.scrollTop() >= limit) {
alert('Reached the required div');
}
});
Demo
I am trying to set up infinite-scroll on a site I am developing with Coldfusion, I am new to javascript and jquery so I am having some issues wrapping my head around all of this. Do I need to have pagination on my site in order to use the infinite-scroll plugin, or is there a way to do it with out it?
You do not need infinite scroll plug-in for this. To detect when scroll reaches end of page, with jQuery you can do
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
//Add something at the end of the page
}
});
Demo on JsFiddle
I'm using Hussein's answer with AJAX requests. I modified the code to trigger at 300px instead of 10px, but it started causing my appends to multiply before the AJAX request was finished since the scroll call triggers much more frequently in a 300px range than a 10px range.
To fix this, I added a trigger that would be flipped on successful AJAX load. My code looks more like this:
var scrollLoad = true;
$(window).scroll(function () {
if (scrollLoad && $(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
scrollLoad = false;
//Add something at the end of the page
}
});
then in my AJAX response, I set scrollLoad to true.
I built on top of Hussein's little example here to make a jQuery widget. It supports localStorage to temporarily save appended results and it has pause functionality to stop the appending every so often, requiring a click to continue.
Give it a try:
http://www.hawkee.com/snippet/9445/
$(function(){
$(window).scroll(function(){
if($(document).height()<=$(window).scrollTop()+$(window).height()+100){
alert('end of page');
}
});
});
Some one asked for explanation so here is the explanation
here $(document).height()-->is the height of the entire document.In most cases, this is equal to the element of the current document.
$(window).height()-->is the height of the window (browser) means height of whatever you are seeing on browser.
$(window).scrollTop()-->The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward. An element's scrollTop is a measurement of the distance of an element's top to its topmost visible content. When an element content does not generate a vertical scrollbar, then its scrollTop value defaults to 0.
$(document).height()<=$(window).scrollTop()+$(window).height()+100
add $(window).scrollTop() with $(window).height() now check whether the result is equal to your documnet height or not. if it is equal means you reached at the end.we are adding 100 too because i want to check before the 100 pixels from the bottom of document(note <= in condition)
please correct me if i am wrong
I had same problem but didn't find suitable plugin for my need. so I wrote following code. this code appends template to element by getting data with ajax and pagination.
for detecting when user scrolls to bottom of div I used this condition:
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
//now you are at bottom of #infiniteContent element
}
$(document).ready(function(){
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: 1, _limit:3 }, function (jsonre) {
appendTemplate(jsonre,1);
});
});
function appendTemplate(jsonre, pageNumber){
//instead of this code you can use a templating plugin like "Mustache"
for(var i =0; i<jsonre.length; i++){
$("#infiniteContent").append("<div class='item'><h2>"+jsonre[i].name+"</h2><p>"+jsonre[i].body+"</p></div>");
}
if (jsonre.length) {
$("#infiniteContent").attr("data-page", parseInt(pageNumber)+1);
$(window).on("scroll", initScroll);
//scroll event will not trigger if window size is greater than or equal to document size
var dh = $(document).height() , wh = $(window).height();
if(wh>=dh){
initScroll();
}
}
else {
$("#infiniteContent").attr("data-page", "");
}
}
function initScroll() {
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
$(window).off('scroll');
var p = $("#infiniteContent").attr("data-page");
if (p) {
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: p, _limit:3 }, function (jsonre) {
appendTemplate(jsonre, p);
});
}
}
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="infiniteContent"></div>
If you have a scrollable element, like a div with scroll overflow, but no scrollable document/page, you can take this way.
$(function () {
var s = $(".your-scrollable-element");
var list = $("#your-table-list");
/* On element scroll */
s.scroll(function () {
/* The scroll top plus element height equals to table height */
if ((s.scrollTop() + s.height()) == list.height()) {
/* you code */
}
});
});
I wrote this function using Hussein and Nick's ideas, but I wanted it to use promises for the callback. I also wanted the infinite scrolling area to be on a fixed div and not just the window if the div is sent into the options object. There is an example of that in my second link below. I suggest using a promise library like Q if you want to support older browsers. The cb method may or may not be a promise and it will work regardless.
It is used like so:
html
<div id="feed"></div>
js
var infScroll = infiniteScroll({
cb: function () {
return doSomethingPossiblyAnAJAXPromise();
}
});
If you want the feed to temporarily stop you can return false in the cb method. Useful if you have hit the end of the feed. It can be be started again by calling the infiniteScroll's returned object method 'setShouldLoad' and passing in true and example to go along with the above code.
infScroll.setShouldLoad(true);
The function for infinite scrolling is this
function infiniteScroll (options) {
// these options can be overwritten by the sent in options
var defaultOptions = {
binder: $(window), // parent scrollable element
loadSpot: 300, //
feedContainer: $("#feed"), // container
cb: function () { },
}
options = $.extend(defaultOptions, options);
options.shouldLoad = true;
var returnedOptions = {
setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } },
};
function scrollHandler () {
var scrollTop = options.binder.scrollTop();
var height = options.binder[0].innerHeight || options.binder.height();
if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) {
options.shouldLoad = false;
if(typeof options.cb === "function") {
new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) {
if(typeof isNotFinished === "boolean") {
options.shouldLoad = isNotFinished;
}
});
}
}
}
options.binder.scroll(scrollHandler);
scrollHandler();
return returnedOptions;
}
1 feed example with window as scroller
2 feed example with feed as scroller