0

I want to pass the myVideo element as a parameter in the play() function, but it does not work? (It is auto-playing the video instead and the eventListener no longer works)

If I use the element directly in the function it work. So I am wondering is it ever possible to pass a DOM element as a parameter and if so is it ever used

Here is the code below:

// Get our elements
const myVideo = document.querySelector(".player__video");
const playButton = document.querySelector(".player__button");
console.log(myVideo);

function play(video) {

    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

playButton.addEventListener('click', play(myVideo))
1
  • Do you get any errors in the console? Commented Apr 19, 2018 at 7:35

2 Answers 2

1
playButton.addEventListener('click', function(){play(myVideo)})

You need to pass a function but instead you are passing the result of a function. JavaScript has first class functions, so get used to this thing.

Sign up to request clarification or add additional context in comments.

Comments

0
const myVideo = document.querySelector(".player__video");
const playButton = document.querySelector(".player__button");
console.log(myVideo);

function play(video) {

    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
}

playButton.addEventListener('click', () => play(myVideo) );

will works. addEventListener requires the second parameter as a Function, but you passed a value as undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.