user17631451
user17631451

Reputation:

Adjusting a javascript line

I'm trying to get Code 2 to work

This line in that code needs to be adjusted in it, but I don't know how I would fix it.

  const otherVideos = (video) => video !== player.getVideoUrl() !== temp;

After a second video is clicked, the one before it pauses.

This Works: Code 1

https://jsfiddle.net/d72Lp43v/418/

  function onPlayerStateChange(event) {
    if (event.data === YT.PlayerState.PLAYING) {
      const temp = event.target.getVideoUrl();
      const otherVideos = (player) => player.getVideoUrl() !== temp;
      const pauseVideo = (player) => player.pauseVideo();
      players.filter(otherVideos).forEach(pauseVideo);
    }
    const player = event.target;
    const playerVars = player.b.b.playerVars;
    if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
      player.seekTo(playerVars.start);
    }
  }

And this code doesn’t, how come?

Code 2

https://jsfiddle.net/d72Lp43v/421/

function onPlayerStateChange(event) {
    const player = event.target;
    if (event.data === YT.PlayerState.PLAYING) {
      const temp = event.target.getVideoUrl();
      const otherVideos = (video) => video !== player.getVideoUrl() !== temp;
      const pauseVideo = (video) => video.pauseVideo();
      players.filter(otherVideos).forEach(pauseVideo);
    }

    const playerVars = player.b.b.playerVars;
    if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
      player.seekTo(playerVars.start);
    }
  }

Upvotes: 1

Views: 61

Answers (2)

Akrion
Akrion

Reputation: 18525

Just change that line to:

  const otherVideos = video => video.getVideoUrl() != player.getVideoUrl()

This will do what you want. It just makes sure that the filter does not include the current video by comparing the urls strings.

You also this way do not need temp variable.

Here is the working fiddle

Upvotes: 1

fliedonion
fliedonion

Reputation: 952

players.filter(otherVideos)

I think filter always return full list.

Each player is not url, so video !== player.getVideoUrl() is true. And true is not url. true !== temp is also true.

I don't know what you want to improve code 1. However I think you want to write is following:

function onPlayerStateChange(event) {
    const player = event.target;
    if (event.data === YT.PlayerState.PLAYING) {
      const temp = event.target.getVideoUrl();
      // only change this line:
      const otherVideos = (video) => video.getVideoUrl() !== player.getVideoUrl() && video.getVideoUrl() !== temp;
      const pauseVideo = (video) => video.pauseVideo();
      players.filter(otherVideos).forEach(pauseVideo);
    }

    const playerVars = player.b.b.playerVars;
    if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
      player.seekTo(playerVars.start);
    }
}

Upvotes: 0

Related Questions