1

I have a div .move that starts to move from left to right when the button "go div" is clicked.

Then I have two div .sound in the center of content div with an audio element.

I want that when the div .move arrives to .sound div, the audio inside .sound div starts to play.

But how to say whenever .move div arrives at .sound element, every audio elements in .sound div starts to play?

https://jsfiddle.net/dda5z70r/

jQuery:

$( "#div" ).click(function() {
  • Do users know you are going to play audio? I would re think from a UX perspective if the end result is "surprise!" – Phix Dec 14 '15 at 01:55
  • Will this always be while using `.animate()`? Because it's the difference between using jQuery's Animate Step callback and a setInterval. – Popnoodles Dec 14 '15 at 02:11
  • I think you'll find this question's answers helpful. It is basically the same issue you are having, except you want to play a sound when it happens: http://stackoverflow.com/questions/4230029/jquery-javascript-collision-detection. Also, just a heads up that the jsfiddle will not play the sounds being loaded as they are served over http and jsfiddle is https. – Fraser Crosbie Dec 14 '15 at 02:25
  • Thanks for your help! I just know the animate method to do this... – user5674491 Dec 14 '15 at 02:26

1 Answers1

0

https://jsfiddle.net/popnoodles/dda5z70r/5/

Check for collision each animate step.

Add your code to play the sound where I have added a class to show this visually.

NB I added the ID bar to the bar that moves because it's faster to search the DOM for an ID than a class. If you have more than one moving bar I can alter this.

$( "#go" ).click(function() {
  var stop = $(".stop").offset().left;
  var obj = document.getElementById("audio"); 

  // how to say whenever .move div arrives at .sound element, the sound associated to that .sound div starts to play?
  //obj.play(); 
  $( "#bar" ).animate({
    opacity: 0.25,
    left: stop-($(".stop").width()+$(this).width()),
  }, {
    duration: 5000, 
    step: function(){
        $('.sound').each(function(){
            if (collision($(this), $('#bar'))){
            $(this).addClass('playme');
        } else{
            $(this).removeClass('playme');
        }
            });

  }, complete: function() {
    $(this).css('left',0);
    $(this).css('height','100%');

  }});


});

function collision($div1, $div2) {
      var x1 = $div1.offset().left;
      var r1 = x1 + $div1.width();
      var x2 = $div2.offset().left;
      var r2 = x2 + $div2.width();
      if (r1 < x2 || x1 > r2) return false;
      return true;
 }
Popnoodles
  • 28,090
  • 2
  • 45
  • 53