Q . How to scroll to a element using javascript?

Mike Tyson. asked, May 17 ' 2018
I have a html content in table tr using jquery animate function to scroll to the tr but its not working.
Please suggest How to do it?
<html>
	<body>
		<table>
			<tr id="tr_255">
				<td>column 1</td><td>column 2</td><td>column 3</td><td>column 4</td>
			</tr>
			<tr id="tr_256">
				<td>column 1</td><td>column 2</td><td>column 3</td><td>column 4</td>
			</tr>
			<tr id="tr_257">
				<td>column 1</td><td>column 2</td><td>column 3</td><td>column 4</td>
			</tr>
			<tr id="tr_258">
				<td>column 1</td><td>column 2</td><td>column 3</td><td>column 4</td>
			</tr>
			<tr id="tr_259">
				<td>column 1</td><td>column 2</td><td>column 3</td><td>column 4</td>
			</tr>
		</table>
	</body>
</html>
//jquery
if($('#tr_259').length > 0){
	$('html, body').animate({ scrollTop: $('#tr_259').offset().top }, 'slow');
}   

 

  • JavaScript
  • jQuery
  • scroll

3 Answers

Try this (pure js) :

if($('#tr_259').length > 0){
	window.scroll(0,findPos(document.getElementById("tr_259")));
}

function findPos(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	return [curtop - 50];
	}
}

 

var elmnt = document.getElementById("content");

function scrollToTop() {
    elmnt.scrollIntoView(true); // Top
}

function scrollToBottom() {
    elmnt.scrollIntoView(false); // Bottom
}

 

You can use an anchor to "focus" the div. I.e:

<div id="myDiv"></div>
and then use the following javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

 

Leave a Ansewer