tags:

views:

351

answers:

5
document.getElementById('logbox').scrollTop = 
document.getElementById('logbox').scrollHeight;

I tried $('#logbox').scrollTop but there is not this attribute.

How to access DOM attribute through jQuery object?

+2  A: 

$("#logbox").attr( "scrollTop", $("#logbox").attr("scrollHeight") );

For more informations: http://docs.jquery.com/Attributes

brainfck
I don't think scrollTop and scrollHeight are element attributes
spender
@spender,it is in fact.
Shore
Hmm. I actually believe it's a scriptable property, but it's not a valid element attribute. http://msdn.microsoft.com/en-us/library/ms534618%28VS.85%29.aspx , http://msdn.microsoft.com/en-us/library/ms534618%28VS.85%29.aspx , https://developer.mozilla.org/En/DOM/Element.scrollTop , https://developer.mozilla.org/En/DOM/Element.scrollHeight etc. *scrollTop is part of the MSIE's DHTML object model and is implemented in the Mozilla Gecko engine powering Firefox. scrollTop is not part of any W3C specification or technical recommendation*Once again, not an element attribute. Definitely
spender
A: 

Try this:

var elem = $('#logbox');
elem.scrollTop(elem.scrollTop());
Gumbo
So DOM attributes become jQuery function calls?
Shore
$("#logbox").scrollHeight is not a function
Shore
No, but `scrollTop` is a getter and setter in jQuery. See http://docs.jquery.com/CSS/scrollTop
Gumbo
A: 

The following should do it:

$('#logbox').scrollTop($('#logbox').attr("scrollHeight"));

There's a scrollTop function in jquery, but no scrollHeight function. If you pass a value into scrollTop, it serves to set the scroll top offset, so you have to read the scrollHeight attribute of the relevant node using the attr function to achieve what you are trying to do.

Pete OHanlon
A: 

A few ways to make it "more jQuery" - all depends on how often you need to set scrollTop to scrollHeight.

// jQuery to get the DOMElement only
var elem = $('#logbox')[0];  // $('#logbox').get(0) works too
elem.scrollTop = elem.scrollHeight;

// a little more jQuery way - allows you to pass more than one matched element,
// $.fn.each() passes each DOMElement in as the context of `this`
$('.scrollers').each(function() {
  $(this).scrollTop(this.scrollHeight);
});

// even more jQuery way - make your own plugin
$.fn.scrollToBottom = function() {
  return this.each(function() {
    $(this).scrollTop(this.scrollHeight);
  });
};
$('#logbox').scrollToBottom();
gnarf
+3  A: 

This is about as jQuery-like as you can get whilst retaining sanity, as there is no direct support for scrollHeight in the library (there is for scrollTop though).

$('#logbox').each(function() {
    this.scrollTop = this.scrollHeight;
});

You should not really be using attr to access scrollHeight as other answers have recommended; attr is for manipulating HTML attributes (href, alt, title, etc.) and scrollHeight is a DOM attribute.

Alex Barrett
+1 for mentioning that attr is for HTML Attributes, not `DOMElement` properties.
gnarf