Hide Nav When Video is playing with js

I have a client who built their site with wpbakery and on their posts are using video player. They want to have it so when the video plays the nav bar disappears. In the inspector I can see that the player has a class of ‘video-container’ and when the video is playing there is an addition class of ‘playing’. I am hoping to check for if video-container has playing then add a class to my nav.

var hideNav = document.getElementsByClassName('video-container playing');
if (hideNav) {
    document.getElementByClassName("nav").className = "hidden";
}

I am guessing I need to add an event listener and I am not sure if my hideNav variable is working how I want it to.

2 thoughts on “Hide Nav When Video is playing with js”

  1. You can watch for changes in dom for that element :

    $('.video-container').on('DOMSubtreeModified', function(e) {
      if $(this).hasClass( "fooplaying"){$(".nav").addClass("hidden")}
    });
    
    $('.video-container').on('DOMSubtreeModified', function(e) {
      if ($(this).hasClass("playing")) {
        console.log(true)
        $(".nav").addClass("hidden")
      }
    });
    
    $('button').on('click', function(e) {
      $('.video-container').addClass("playing")
    });
    .hidden {
      color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="video-container">VIDEO</div>
    <button>press</button>
    <div class="nav">nav</div>
    Reply
  2. Here’s an answer that doesn’t use jQuery:

    const videoEl = document.getElementById('video')
    const navbarEl = document.getElementById('navbar')
    
    videoEl.addEventListener('play', () => {
      navbarEl.classList.add('hidden')
    })
    
    videoEl.addEventListener('pause', () => {
      navbarEl.classList.remove('hidden')
    })
    .hidden {
      display: none;
    }
    <div style="padding: 30px 10px; width: 100%; background: gray; margin-bottom: 20px;" id="navbar">
    Navbar
    </div>
    
    <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" id="video" controls width="400" /> 
    Reply

Leave a Comment