0

How to call click function inside a while loop in jquery?

$(document).ready(function(){
  var count=2;
  while(count>0){
    $(".box1").click();
    count--;
   }
   $(".box1").click(function(){
     var aud=document.createElement('audio');
     aud.src="tom-1.mp3";
     aud.play();
   });    
});

1 Answer 1

2
  1. You need to specify .box1 as String.
  2. Attach the event handler before calling it.
  3. Add audio to HTML. (Do not use virtually in javascript), Otherwise you get Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. . now I am getting this error. error.

$(document).ready(function() {
  var count = 2;

  $(".box1").click(function() {
    var aud = document.getElementById('audio');
    // replace with your audio
    aud.src = "https://freesound.org/data/previews/515/515391_1453392-lq.mp3";
    aud.play();
  });

  while (count > 0) {
    $(".box1").click();
    count--;
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio id='audio'></audio>
<button class='box1'>Play</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. . now I am getting this error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.