0

I have page where i have to play certain audio files which are related to the text and when related audio file is played then related text should be highlight. Issue i am facing is that i need to keep the highlighted div visible to the reason. I am not sure how i can automatically scroll down the page to keep the highlighted div visible so that he can read it.

JSBin Example

HTML

<audio id="myAudio">
    <source src="" type="audio/mpeg">
</audio>
<button>Play Audio</button>
<div class="wrapper">
    <span>Rooster</span>
    <span>Cat</span>
    <span>Horse</span>
    <span>Elephant</span>
    <span>Vulture</span>
    <span>Duck</span>
    <span>Rooster</span>
    <span>Cat</span>
    <span>Horse</span>
    <span>Elephant</span>
    <span>Vulture</span>
    <span>Duck</span>
    <span>Rooster</span>
    <span>Cat</span>
    <span>Horse</span>
    <span>Elephant</span>
    <span>Vulture</span>
    <span>Duck</span>
    <span>Rooster</span>
    <span>Cat</span>
    <span>Horse</span>
    <span>Elephant</span>
    <span>Vulture</span>
    <span>Duck</span>
</div>

I tried following code but this not working

$aud.onplay = function() {
    $btn.text("Pause Audio");
    playing = true;
    $("div > span:nth-child(" + (audioIndex + 1) + ")").addClass("playing");
    var wHeight = $( window ).height();
    var wHalfHeight = wHeight;
    var x = $(".playing").position();
    var curentSpanPosition = x.top();
    wHalfHeight = wHalfHeight/2;

    //if  ( curentSpanPosition > wHalfHeight )
    //{
    $(".playing").animate({
        scrollTop:  curentSpanPosition
    });
    //}
  };
Learning
  • 17,618
  • 35
  • 153
  • 314
  • I have started to explore option of using `var x = $(".playing").position();` `x.top` i will compare `x.top` position with window that height and scroll down. I think this should work – Learning Jun 13 '16 at 05:30
  • This might help you: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element – Alok Patel Jun 13 '16 at 05:31

1 Answers1

1

Add the following after var x = $(".playing").position(); :

$('html, body').animate({
        scrollTop: x.top
}, 400);

Here is your updated code

Ahs N
  • 7,860
  • 1
  • 23
  • 31
  • I used following code var wHeight = $( window ).height(); `var wHalfHeight = wHeight; var x = $(".playing").position(); var curentSpanPosition = x.top; wHalfHeight = wHalfHeight/2; if ( curentSpanPosition > wHalfHeight ) { $('html, body').animate({ scrollTop: curentSpanPosition }, 1000); }` – Learning Jun 13 '16 at 06:06