How to scroll div to bottom? - javascript

Now I have div with following properties:
.chat-history {
height: 70%;
overflow: auto;
}
How to scroll it to bottom using js?

window.scrollTo(0, document.getElementsByClassName('chat-history')[0].scrollHeight);
I think this will work as you needed. you have to write the class name of the div where you are showing the messages.

You can use the scrollTop function in Javascript
Example:
var obj = document.getElementById("Name of your div");
obj.scrollTop = obj.scrollHeight;
Working fiddle: https://jsfiddle.net/js1vyrxr/3/
If you want to use it with jQuery you can use something like this
$("#ScrollToThisDivID").scrollTop($("#ScrollToThisDivID")[0].scrollHeight);

You can use the javascript scrollTo function
window.scrollTo(0, document.body.scrollHeight);
Where 0 is the horizontal scoll and the second parameter is the vertical scroll.
For your example you should get the element and use that element instead of window, like this:
getElementsByClassName('chat-history')

Related

Scroll an object to the right

I have a div with an overflow: scroll. How can I make it scroll 20px to the right in javascript?
I tried the following but it doesn't seem work:
document.querySelector('div').scrollTo(20, 0);
It returns that scrollTo isn't a function.
scrollTo is not a function. What you want to use is scrollLeft. This will scroll your div to the right.
document.querySelector('div').scrollLeft = 20;
If you want to scroll 20 pixels to the right every time, use +=
document.querySelector('div').scrollLeft += 20;
If you want to scroll vertically, use the scrollTop property.
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft

Set the position of div according to scroll

I want a div to be scroll upto some height with scrolling.
I am using this code bt its not working for me,please help me out to solve this problem using javascript or css i can't use jquery in my programm
thanks in advance
element.style.position='fixed';
element.style.scrollTop ='800px';
element.style.overflow='scroll';
function Scroll()
{
var intY = document.getElementById("impulseadcontainer").scrollTop ;
console.log("pos"+intY);
}
You have to assign something to the scrollTop attribute in order for it to work.
function scroll() {
document.getElementById("impulseadcontainer").scrollTop = 0; // scrolls to top (set here whatever value you want)
}
You can do this with the following javascript code.
document.scrollTo(0,document.getElementById('id-of-element').offsetTop);

Jquery slide to visibility hidden?

I want to achieve something like :
$("#left").hide('slide', {direction: 'right'}, 1000)
However I do not want the div to be hidden I want it to keep up space so I want have the visibility hidden like:
$("#left").css('visibility','hidden')
Yet still achieve the same effect as above.
This is what I'd do
$parent = $('#left').parent(); //store the parent of the element in a variable
$('#left').clone() //clone the existing element
.appendTo($parent) // insert it into the current position
.css('visibility','hidden') //set it's visibility to hidden
.end().end() //target the initial element
.slideUp() //do any slide/hide/animation that you want here, the clone will always be there, just invisible
This could be horrible, but it's the only way I could think of solving the problem :)
EXAMPLE: http://jsfiddle.net/skyrim/j2RWt/4
Try this:
var $content = $("#left");
var offset = $content.offset();
$("<div></div>").css({
width: 0,
position: "absolute",
left: offset.left,
top: offset.top,
height: $content.outerHeight(),
backgroundColor: "White"
}).appendTo("body")
.animate({
width: $content.outerWidth()
}, 1000, function () {
$content.css('visibility', 'hidden');
$(this).remove();
});
EDIT
So, after learning what the actual need was (:p), this method basically place another div over the original element. I've tested it on IE...and I'll edit this with an update after I do further testing on other browsers!
EDIT
Only Chrome seems to be having an issue with getting the correct height.
Added a callback which removes the makes visibility hidden (as LEOPiC suggested) and removes the slideout div
You can do it in very simple way. There is really a nice tutorial here to animate in different direction. It will surely help you. try this
$('#left').animate({width: 'toggle'});
EXAMPLE : http://jsfiddle.net/2p3FK/2/
EDIT: One more solution, this is very simple to move the div out of window with left margin
$("#left").animate({marginLeft:'1000px'},'slow');
EXAMPLE : http://jsfiddle.net/2p3FK/1/

iScroll doesn't show the scrollbar but lets me drag the content

This is how I call it
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
/**/
$(document).ready(function() {
//Created an array for adding n iScroll objects
var myScroll = new Array();
$('.content').each(function(){
if($(this).attr('id')==null){
$(this).attr('id') = $(this).attr('class');
}
id = $(this).attr('id');
console.log(id);
$(this).html('<div class="scroller">'+$(this).html()+'</div>');
myScroll.push(new iScroll(id));
});
});
I modified it a little bit so you can use it with a class and not only id.
It seems to work (to be enabled) because I can drag the container and its content (but it wont keep position, it will restore on mouse release)
If you want to see it happening please visit http://toniweb.us/grano and click on any item in the menu, the new shown has the effect.
Any idea why it is working but not as expected?
The reason I want to do this is because the container has several subcontainers that will be hidden or shown depending on the content selection.
CSS:
#nvl1{
padding:0px 25px;
z-index:10;
position:absolute;
left:0px;
background:url("../img/fondoNivel2.jpg") no-repeat scroll right 0 #79797B ;
height:100%;
}
#nvl1 .content{
width:650px;
z-index:11;
display:none;
color:#6666b6b;
position:relative;
line-height:30px;
}
I had a look at your code on: http://toniweb.us/grano
I think what you would like to do is use iScroll on your class with "scrolling". That is not what you are doing in the following code but instead you are actually setting iScroll to use the parent of your scroller DIV:
id = $(this).attr('id');
$(this).html('<div class="scroller">'+$(this).html()+'</div>');
myScroll.push(new iScroll(id));
For reference: iScroll uses an ID rather than a class
The effect this is having is that it is causing the "snap" effect on the immediately following block level element - your scroller DIV.
Consider this example where there is a DIV (id="scroller") containing an OL which contains a number of (block level) LIs:
http://cubiq.org/dropbox/iscroll4/examples/simple/
Long story short, give your DIV with the scroller class an id and create your iScroll from that instead.
if you set the style on the div tag you put the scroller on to (example)
style="position:relative;overflow: hidden;height:350px;
i think it's setting the height explicitly that should solve the dragging problem
Don't you just want:
.content {overflow-y:scroll;}
Is that not what you're saying mate?
The elements within the scroll div can't be floating. If they are floating and not cleared the flow of the page will mean your scrolling div is not the correct height. Try avoiding any floats within your scrolling and div and see how that goes. This was the problem for me.
I also found Matthews answer to be helpful as I was also calling iscroll on the wrong div. I think the confusing thing about the iScroll example is that it's easy to assume iScroll is called on the div with the ID scroller, but it's called on the wrapper div. The div with the ID scroller doesn't actually need an ID and I think for the examples sake this would be clearer without that. e.g.
<div id="wrapper">
<div>
<p>Whatever you want here</p>
<ul>
<li>1</li>
</ul>
</div>
</div>
...
myScroll = new iScroll('wrapper');

Find the "potential" width of a hidden element

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com

Categories

Resources