I am performing the same actions for different elements and I want to know if the code could be shortened and how to do it. This is a page with 3 videos that I want to play or stop playing on hover or exit.
The HTML code for the videos is the following (which I repeat 3 times with different id):
controls = [];
player1 = new Plyr('#player1', {
controls
});
window.player1 = player1;
player2 = new Plyr('#player2', {
controls
});
window.player2 = player2;
player3 = new Plyr('#player3', {
controls
});
window.player3 = player3;
$("#demo1btn").hover(function() {
player1.play();
});
$("#demo1btn").mouseout(function() {
player1.stop();
});
$("#demo2btn").hover(function() {
player2.play();
});
$("#demo2btn").mouseout(function() {
player2.stop();
});
$("#demo3btn").hover(function() {
player3.play();
});
$("#demo3btn").mouseout(function() {
player3.stop();
});
<div class="btn p-0" id="demo1btn">
<video class="video-fluid" id="player1" poster="fotos/demo1.jpg" playsinline loop>
<source src="demo1.mp4" type="video/mp4">
</video>
</div>
I calculate that if I go for the .video-fluid class instead of the IDs, I could start all 3 together with a for... but I'm not sure if there would be any conflict with the window.player or how it would be done, and the same with The hover and mouseout, I know I have to go through the btn class, but inside I got lost with the selector to identify the element with the $(this "#video-fluid") and it didn't work out.
Could someone please help me with this?
I don't know how much you want to shorten it, but you could just do this:
And from there, if you wanted to handle any Plyr, you still have them in the object
window
.The jQuery method
hover()
accepts 2 arguments of type function, one formouseenter
and one formouseleave
.PS: The code is ES6, so you may want to convert it to ES5 or compile it .
To simplify that code a bit, what I did was create an attribute for all the btn divs that you had where I indicate the # of the player and specify that it is the one that I am going to read to assign the hover and mouseout event, then I capture those events for all the div that have that attribute, I create the players and add them to the window object and in each case I play or pause it. Here I leave the code.
This would be an example of your html:
Now your javascript would look something like this:
Try it and tell me luck ;P
EDITED I had forgotten the $(item) of each sorry. If it works for you please mark it as correct
creating a class would be better since in the end if it is a game you will have too many players to be doing methods for everyone and it would not be shortening if not optimizing: