Кнопка Play и Pause для тега video

Сделал кейс с кучей видео, смотрю его и думаю: «ну как же хреново, что кнопки управления видео внизу».

Пользователю из-за отсутствия других визуальных элементов нужно будет целиться в самый угол.

Нам нужно, чтобы кнопка плей была по центру, вот так.

Сходил в нейронку, попросил написать скрипт, чуть подправил и готово. Теперь есть удобная кнопка воспроизведения.

Код

Можете вставить в основной файл скрипта или подключить отдельно файлом video-play-button.js

/**
 * Video Play Button
 * Добавляет кнопку play/pause ко всем видео на странице
 * Работает только на десктопе (на мобильных используются нативные контролы)
 *
 * Использование: просто подключите скрипт на страницу
 * <script src="video-play-button.js"></script>
 */
(function () {
  // Проверка на мобильное устройство
  var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    || window.innerWidth <= 768;

  if (isMobile) return; // Выход, если мобильное устройство

  // ===== стили =====
  var css = `
  .video-play-wrap {
    position: relative;
    display: inline-block;
    max-width: 100%;
  }
  .video-play-wrap video {
    display: block;
    width: 100%;
    height: auto;
  }
  .video-play-overlay {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
  }
  .video-play-btn {
    width: 74px;
    height: 74px;
    border-radius: 9999px;
    background: rgba(0,0,0,0.55);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    pointer-events: auto;
    transition: transform .2s ease, opacity .2s ease;
  }
  /* PLAY */
  .video-play-btn[data-state="play"]::before {
    content: '';
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 14px 0 14px 20px;
    border-color: transparent transparent transparent #fff;
    margin-left: 4px;
  }
  /* PAUSE */
  .video-play-btn[data-state="pause"]::before {
    content: '';
    display: block;
    width: 10px;
    height: 20px;
    border-left: 4px solid #fff;
    border-right: 4px solid #fff;
  }
  .video-play-btn.is-hidden {
    opacity: 0;
    pointer-events: none;
    transform: scale(.8);
  }
  `;
  var style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);

  // ===== логика =====
  var videos = document.querySelectorAll('video');

  videos.forEach(function (video) {
    // Пропускаем, если уже обработано
    if (video.closest('.video-play-wrap')) return;

    // Создаём обёртку
    var wrap = document.createElement('div');
    wrap.className = 'video-play-wrap';
    video.parentNode.insertBefore(wrap, video);
    wrap.appendChild(video);

    // Создаём оверлей с кнопкой
    var overlay = document.createElement('div');
    overlay.className = 'video-play-overlay';

    var btn = document.createElement('div');
    btn.className = 'video-play-btn';
    btn.setAttribute('data-state', 'play');
    overlay.appendChild(btn);
    wrap.appendChild(overlay);

    var hideTimer = null;
    var ignoreNextBtnClick = false;

    function showBtn(state) {
      if (state) btn.setAttribute('data-state', state);
      btn.classList.remove('is-hidden');
    }

    function hideBtn() {
      btn.classList.add('is-hidden');
    }

    function enableControlsIfNeeded() {
      if (!video.hasAttribute('controls')) {
        video.setAttribute('controls', '');
      }
    }

    // Клик по кнопке
    btn.addEventListener('click', function (e) {
      e.stopPropagation();
      // Игнорируем клик, если кнопка только что появилась под курсором
      if (ignoreNextBtnClick) {
        ignoreNextBtnClick = false;
        return;
      }
      var state = btn.getAttribute('data-state');
      if (state === 'play') {
        enableControlsIfNeeded();
        video.play();
      } else {
        video.pause();
      }
    });

    // Клик по видео (только до добавления controls)
    video.addEventListener('click', function (e) {
      // Если controls уже активны, браузер сам управляет — не вмешиваемся
      if (video.hasAttribute('controls')) {
        return;
      }
      if (video.paused) {
        enableControlsIfNeeded();
        video.play();
      } else {
        video.pause();
      }
    });

    // События видео
    video.addEventListener('play', function () {
      hideBtn();
    });

    video.addEventListener('pause', function () {
      clearTimeout(hideTimer);
      showBtn('play');
    });

    video.addEventListener('ended', function () {
      clearTimeout(hideTimer);
      showBtn('play');
    });

    // Показ паузы при движении мыши
    function userMoved() {
      if (!video.paused) {
        showBtn('pause');
        clearTimeout(hideTimer);
        hideTimer = setTimeout(function () {
          if (!video.paused) {
            hideBtn();
          }
        }, 2000);
      }
    }

    // Тач для мобильных
    wrap.addEventListener('touchstart', userMoved, {passive: true});

    // Старт — показываем кнопку play
    showBtn('play');
  });
})();