Amit1992 Amit1992 - 1 month ago 13
jQuery Question

Ul list Item scroll to view with matching option selected in HTML Select.

I have done this code but its behavior is undefined.Its working good for some list item. Thanks in advance.
you can check jsfiddle link http://jsfiddle.net/amitv1093/5uwfky4n/

-----html-----

<select id="sel">
<option value="Volvo">Volvo</option>
<option value="Saab">Saab</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
<option value="Maruti">Maruti</option>
<option value="Tata">Tata</option>
<option value="Ferrari">Ferrari</option>
</select>

<div>
<ul>
<li data-val="Volvo" > Volvo </li>
<li data-val="Audi"> Audi</li>
<li data-val="Saab" > Saab </li>
<li data-val="Mercedes"> Mercedes </li>
<li data-val="Maruti"> Maruti </li>
<li data-val="Tata"> Tata </li>
<li data-val="Ferrari"> Ferrari</li>
</ul>
</div>


---css---

div
{
height:50px;
overflow-y: scroll;
overflow-x: hidden;
}
.red
{
color:red;
}


---js---

$(document).ready(function()
{
//var ulList ;


$('#sel').change(function() {

var selList = $(this).val();

$("ul li").each(function()
{
console.log($(this).data("val"));
console.log($(this).offset().top);
if( selList == $(this).data("val"))
{
$(this).addClass("red");



$("div").animate({
scrollTop: $(this).position().top
}, 600);
}
else
{

$(this).removeClass("red");
}




});

});


});

Answer

Do it this way bro. and check this http://jsfiddle.net/5uwfky4n/2/

$(document).ready(function()
{
//var ulList ;


$('#sel').change(function() {

      var selListIndex = $(this)[0].selectedIndex;
      var myCar = $(this).val();
      console.log(selListIndex)
      $('li').removeClass('red');
      $('#'+myCar).addClass('red');
      var scrollTome =selListIndex *  parseInt($('li').height());
      $("div").animate({ 
        scrollTop: scrollTome
      }, 600);

});


});
Comments