javascript – Delete or change src parameter on click

Question:

Hello.

Tell me how to change or remove the src parameter on click? When you open a hidden block, the video turns on, but when you close it, it continues to play.

With this code, I start the video. Tell me how to stop it when the window is closed.

$(document).on('click', '.open-video', function() {
  var $video = $('#video'),
  src = $video.attr('src');
  $video.attr('src', src + '?autoplay=1');
});

Tried adding on button click

$(document).on('click', '.open-video', function() {
  var $video = $('#video'),
  src = $video.attr('src');
  $video.attr('src', src + '?pause=1');
});

But when reopening the video does not start, both parameters remain in the link, how to remove ?autoplay=1 ?

Answer:

You can pre-clear the link from variables

$(document).on('click', '.open-video', function() {
  var $video = $('#video'),
      src = $video.attr('src').replace(/^(.+)\?.+$/, '$1');
      
  $video.attr('src', src + '?pause=1');
  
  console.log( $video.attr('src') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video src="video.mp4" id="video"></video>

<button class="open-video">Изменить</button>
Scroll to Top