0

Hello everyone ! I am coding a board based on bootstrap3. There's a database filled with the sound infos and I'm creating divs from it. I'd like to add a search bar which find the element in the page and scroll to it. I've already looked on jquery.scrollTo or javascript but I can't find how to do it !

Here's the search form I'd like to use :

<form class="navbar-form navbar-left" role="search">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>

And here's what the body looks like :

  echo "<div id='EPsound".$j."' name='".$name[$j]."' class='col-md-6'></br>"; //créer une div pchq son
            echo "<div class='sound center-block'>";
                echo "<img src=".$artwork[$j]." class='img-thumbnail center-block' />";
                echo "<span>$name[$j]</span>";
                echo "<i class='fa fa-play fa-3x play' onclick='$onclickplay'></i>";
                echo "<i class='fa fa-plus fa-3x plus' onclick='$onclickqueue'></i>";
            echo "</div>";
  echo "</div>";

Thank you so much for your help !

gmolveau
  • 95
  • 12

2 Answers2

0
// Grab all the result containing the name
var list = $('.sound span'); // you should add a better scope

// Whenever user type in the input field...
$('.navbar-form input').on('keyup', function (e) {
   var regex = new RegExp(e.currentTarget.value, 'ig');

   // ...try to find if any element is matching typed text
   for (var i = 0, len = list.length; i < len; i += 1) {
     list[i].name.toLowerCase().match(regex) && list[i].scrollIntoView();
     break; // stop when found
   }
});
avetisk
  • 9,795
  • 4
  • 23
  • 36
0

JavaScript:

If you are looking for a pure JavaScript solution, you could make use of the

scrollIntoView()

method.

To use it, you would need the 'element' on which you want to apply it. Hence, you would apply it as such:

document.getElementById("elementID").scrollIntoView();

You can take a look here: http://jsfiddle.net/yYq39/1/

These method just brings the said element into focus immediately. So the overall effect from a user's perspective is not all that nice!!!

JQuery:

If you are looking for a smooth scroll to the said element, you could make use of Jquery's ScrollTop function:

You would use it this way:

$("#btnScroll").click(function() {
    $("html, body").animate({ scrollTop: $("#block2").offset().top }, 500);    
});

You can have a look here: http://jsfiddle.net/3ak6L/

Hope this helps!!!

Satwik Nadkarny
  • 4,770
  • 2
  • 20
  • 39