Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add autoplay attribute in html5 video player

Tags:

html

jquery

I want to add an attribute autoplay to a <video></video> element, when a specific target button is clicked.

HTML

<video controls>
  <source src="video.mp4" type="video/mp4">
</video>

I tried with jQuery:

$('.targetButton').on('click', function(){
  $('video').attr("autoplay"," ");
});

... but the video does not play. What am I doing wrong?

like image 324
Daniel Avatar asked Sep 17 '25 10:09

Daniel


1 Answers

Setting the autoplay flag is not enough to make the video play, you should call the load() method right after setting autoplay to true so that the video will reload and then play, since the flag is true.

$('video').autoplay = true;
$('video').load();

But why do this when you can actualy play the video with JS? Here's how to do it with jQuery:

$('video').play();
like image 50
user6549300 Avatar answered Sep 19 '25 03:09

user6549300