omg
omg

Reputation: 139862

How to translate this pure javascript to jQuery?

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?

Upvotes: 0

Views: 814

Answers (5)

Alex Barrett
Alex Barrett

Reputation: 16455

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.

Upvotes: 3

gnarf
gnarf

Reputation: 106332

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();

Upvotes: 0

Pete OHanlon
Pete OHanlon

Reputation: 9146

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.

Upvotes: 1

Gumbo
Gumbo

Reputation: 655229

Try this:

var elem = $('#logbox');
elem.scrollTop(elem.scrollTop());

Upvotes: 0

brainfck
brainfck

Reputation: 9376

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

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

Upvotes: 2

Related Questions