kannan D.S
kannan D.S

Reputation: 1101

How to dynamically scroll focus a particular highlighted div

How to dynamically scroll to focus a particular highlighted div? am trying to scroll to focus a specific div has class highlighted.How can i solve this?

<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row highlighted">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>

Upvotes: 6

Views: 17763

Answers (4)

Use jQuery scrollIntoView:

$(".ClssName").scrollIntoView();

Upvotes: -1

Youenn LOIE
Youenn LOIE

Reputation: 11

You can indeed use:

element.scrollIntoView();

Be careful: if you are using VueJs, you may have problems trying to use Refs instead. Even in VueJs, you should use a document.getElementById.

Upvotes: 0

prasanth
prasanth

Reputation: 22490

Try with jquery position().top

$(document).on('click','button',function(){
var s  = $('.highlighted').position().top;
$('body').scrollTop(s)
})
.row{
padding:50px;
border:1px solid red;
}
.highlighted{
border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>scroll highlighted</button>
<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>
<div class="row highlighted">
<p>123</p>
</div>
<div class="row">
<p>123</p>
</div>

Upvotes: 2

m.nachury
m.nachury

Reputation: 982

In simple js:

document.getElementsByClassName("row highlighted")[0].scrollIntoView();

or in jquery:

$( ".row highlighted")[0].scrollIntoView();

Upvotes: 12

Related Questions