-1

So I am an absolute beginner to this and was wondering on how can I add sound (in this case Bell Sound) to an HTML page. The sound needs to play when I scroll down to the section of the page and reach the bell image.

My HTML:

<div class="container">
<img style="max-width: 100%" alt="" src="<?= 
enter code herebase_url('assets/bootstrap/')? 
>image/ringabox.png">
<audio autoplay="true" >
<source src="<?= base_url('assets/bootstrap/')?>image/ht1.wav" type="wav">
</audio>
</div>

My JS:

var audio = document.getElementsByTagName("audio")[0];
audio.play();

// or with an ID

var audio = document.getElementById("mySoundClip");
audio.play();

Any Help would be appreciated

Thanks

Abhisar2006
  • 17
  • 1
  • 6
  • after a quick search I found this [click](https://stackoverflow.com/questions/22604532/how-to-add-audio-to-a-html-image) – John Oct 03 '18 at 07:17

2 Answers2

0
var audio = $("#mySoundClip");
var bellTop = $('#bell').offset().top;
$(window).on("scroll", function(){
    var scrollTop = $(window).scrollTop();
    if(scrollTop >= bellTop){
        audio.play();
    }
});

The variable scrollTop has the amount of pixels scrolled.
You can also calculate the percentage scrolled by calculating document and window height. eg.

var wHeight = $(window).height();  // window Height
var dHeight = $(document).height();  // document Height
var scrollTop = $(window).scrollTop();  // pixels scrolled
var scrollable_area = dHeight - wHeight  // scrollable area
var pScrolled = Math.floor(scrollTop/trackLength * 100);  // percent scrolled
Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
0

Using Javascript you can do it like this :

$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
       console.log('H1 on the view!');
   }
});

See source on this thread : Trigger event when user scroll to specific element - with jQuery