javascript videoタグが自動再生になっているかを判定する

javascript videoタグが自動再生になっているかを判定する

javascriptで、videoタグが自動再生になっているかを判定するサンプルコードを記述してます。

環境

  • OS windows11 home
  • ブラウザ chrome 105.0.5195.127

自動再生になっているかを判定

自動再生になっているかを判定するには、「autoplay」プロパティの値を確認します。

<video id="video" autoplay muted style="width:700px;height:400px;">
    <source src="test.mp4">
</video>

<video id="video2" style="width:700px;height:400px;">
    <source src="test.mp4">
</video>

<script>

console.log(
	document.getElementById('video').autoplay // true
)

console.log(
	document.getElementById('video2').autoplay // false
)

</script>

判定されていることが確認できます。

また、javascript部はdocument.getElementByIdを省略して記述することも可能です。関数もアロー関数を使用できます。

console.log(
	video.autoplay
)

console.log(
	video2.autoplay
)

サンプルコード

以下は、ボタンをクリックすると、自動再生になっているかを判定して結果を出力するサンプルコードとなります。

※cssには「Material Design for Bootstrap」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- Font Awesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.1.0/mdb.min.css" rel="stylesheet" />
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 20px;
  }
</style>
<script>

  const hoge = () => {
    
    result.innerHTML = video.autoplay

  }

</script>

<body>
  <div class="main">

    <video id="video" autoplay muted style="width:700px;height:400px;">
      <source src="test.mp4">
    </video>

    <span id="result" class="badge badge-success"></span>

    <button type="button" class="btn btn-raised btn-success mt-3" onclick="hoge();">判定</button>

  </div>
</body>

</html>

判定されていることが確認できます。