-1

I'm not sure how to describe this. I need tabs with video player embed codes. For example, I have two tabs: tab1 and tab2. Both tabs show video player when user click on tab1 and play video, and without stopping this user clicks on tab2 and play video which is in tab2 but tab1 one video is also playing. Need help to stop tab1 player automatically when user switches tab.

freginold
  • 3,946
  • 3
  • 13
  • 28

1 Answers1

0

If your tabs are buttons, you can use

$('.tab1 + button').on('click', function() { //Selects button immediately after `<div class="tab1">`
    var video = $('.tab2 video')[0]; //Get first <video> in selection as DOM Element so that we can use the `pause` function on it
    video.pause()
    //Play the video from tab 1
    $('.tab1 video')[0].play();
});

This selects elements with a class of tab1 and pauses the <video> from tab2

$('.tab2 + button').on('click', function() { //Selects button immediately after `<div class="tab2">`
    var video = $('.tab1 video')[0];
    video.pause()
    //Play the video from tab 2
    $('.tab2 video')[0].play();
});

This selects elements with a class of tab2 and pauses the <video> from tab1

The reason that I use $('.tab1 video')[0] instead of just $('.tab1 video') is because including the [x] (where x = 0 or any index) converts the jQuery object into a normal JavaScript DOM Element so that you can call .play() and .pause() on it. You can use the above javascript if your markup is somewhat similar to

<div class="tab1">
    <video src="myvideo.mp4"></video>
</div>
<button>Open tab 1</button>

<div class="tab2">
    <video src="myvideo.mp4"></video>
</div>
<button>Open tab 2</button>

Where the tabs are <div> elements, and your buttons are immediately after the tab that the button should open (because of the + selector that I used) Please include your HTML so that I can answer this better.

FluxCapacitor
  • 56
  • 1
  • 5