Reputation: 1039
there. I have a list of items (users) in a popup. This list is in a scrollable div. I want to make a search box that, using jQuery and Javascript, calculates the position of the desired user in this list and then scrolls to it. Basically, this is what I want:
function goToUser(userName) {
var userPosition = getPosition(userName);
$('#myContainer').scrollTop(userPosition);
}
function getPosition(userName){
// ?????
}
Anyone had such a problem before ? Thank you.
This is the partial view I use for the popup:
@using (@Html.BeginForm())
{
<div class="popupTitle">
Choose user(s)
</div>
<div style="height: 400px; overflow: scroll" class="popupNotifications">
@foreach (var user in Model.Users)
{
<div>
<input id="[email protected]" name="targetIds" type="checkbox" value="@user.id" @if(Model.TargetIds != null && Model.TargetIds.Contains(user.id)){<text>checked="checked"</text>} />
<label for="[email protected]" style="cursor: pointer;">@user.name</label>
</div>
}
</div>
<div class="popupButtons">
<input type="button" class="button" value="Save" onclick="GetValues(Notifications_UsersPopupHolder)" />
<input type="button" class="button" value="Cancel" onclick="Cancel(Notifications_UsersPopupHolder)" />
</div>
}
Upvotes: 2
Views: 525
Reputation: 1705
Have you tried $(element).scrollIntoView()
?
I think your code would look like this (no need for a getPosition function):
function goToUser(userName){
$('div.popupNotifications input#' + username).closest('div').scrollIntoView();
}
Upvotes: 1
Reputation: 337560
You can use the offset().top
of the specific element.
function goToUser(userName) {
var userPosition = getPosition(userName);
$('.popupNotifications').scrollTop(userPosition);
}
function getPosition(userName){
return $('.popupNotifications label:contains(' + userName + ')').offset().top;
}
Upvotes: 0
Reputation: 5899
You could assign the element containing your user an ID or some class that identifies it (either id="user1" or class="user1")
Then you can simply use
$('#elementcontainingusers').scrollTop($('#user1').position().top);
Upvotes: 0
Reputation: 293
If all your items in the list is the same height you can calculate by (index + 1) * height of item.
Upvotes: 0