Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

JavaScript How to add data-id to button, allowing me to remove the 2nd container

Can you help me?

The whole goal or overarching objective here is being able to remove the 2nd container from the code.

My HTML is repetitive. Since I only show one player at a time, I should only have a single container.

I’m already using data-container on each button to figure out which video container I want to play.

Instead I want to have a single video player element/container, and just pass the corresponding data-id directly from the button instead. Where I can then instantiate the video player in the same process to load only the video that is clicked.

<div class="video video-frame">

So for example, I’m using play2 to go find a video container named play2 and doing actions to show that specific container. In that container I have an element that has the data-id of my YouTube video -Xgi_way56U

So instead of creating a playX container for every single video, I want to put -Xgi_way56U on the button instead. When the button is clicked, I want to take that ID and pass it into the video player element to load it on demand.

The idea here would be to attach the id data-id="-Xgi_way56U"

to the button:

<button class="playa2 cover" type="button" data-container="play1"></button>

Which would then become this:

<button class="playa2 cover" type="button" data-container="play1" data-id="-Xgi_way56U"></button>

I have been told by multiple people now, I should only be needing 1 container.

They said it is unnecessary duplication where only 1 container is all that should be needed.

The idea here would be to add the data-id="" to the buttons, which should allow me to remove the 2nd container from the code.

I have not been able to figure out how to do this.

How the code works is, after clicking a button a video will appear on the screen, click the X the buttons return to the screen where you can click on the 2nd button and a video will appear on the screen.

Two buttons should be able to run off of one of these, that are inside 1 container, instead of needing multiple containers for each button.

<div class="video video-frame">

Here is the code working with 2 containers: https://jsfiddle.net/7apg90wz/

Code:
<div class="container play1 with-curtain">
  <div class="inner-container curtain ">
    <div class="ratio-keeper">
      <div class="wrap">
        <div class="video video-frame" data-id="-Xgi_way56U"></div>
      </div>
    </div>
    <button class="exit" type="button" title="Exit" aria-label="Close"></button>
  </div>
</div>
<div class="container play2 with-curtain">
  <div class="inner-container curtain">
    <div class="ratio-keeper">
      <div class="wrap">
        <div class="video video-frame" data-id="0dgNc5S8cLI"></div>
      </div>
    </div>
    <button class="exit" type="button" title="Exit" aria-label="Close"></button>
  </div>
</div>

Here is the container with buttons:
Code:
<div class="playButtonContainer with-curtain">
  <button class="playa1 cover" type="button" data-container="play1"></button>
  <button class="playa2 cover" type="button" data-container="play2"></button>
</div>

Removing 1 container I have this now: https://jsfiddle.net/82rxzq7h/

The code is not working now because more stuff is needed to be done.

I don’t know what else is needed to be done, or how to achieve this, of being able to remove the 2nd container from the code.

I have been having a very difficult time trying to figure out how to do this in the code.

Code:
<div class="container play1 with-curtain">
  <div class="inner-container curtain">
    <div class="ratio-keeper">
      <div class="wrap">
        <div class="video video-frame"></div>
      </div>
    </div>
    <button class="exit" type="button" title="Exit" aria-label="Close"></button>
  </div>
</div>

Here is the container with buttons: Where I attached the data-id="" to them.
Code:
<div class="playButtonContainer with-curtain">
  <button class="playa1 cover" type="button" data-container="play1" data-id="-Xgi_way56U"></button>
  <button class="playa2 cover" type="button" data-container="play1" data-id="0dgNc5S8cLI"></button>
</div>

I tried to provide as much detail in here as possible in what I am trying to do in the code.

If you may have any questions, or would like to know more information, please ask.
 
Solution
What can be done to figure out how to fix it?
OK I Got it
1669670649074.png

1669670845919.png

Also, sorry for the late reply, been in and out of meetings all for the most part of today. Not gonna lie, as I was going through your code, I found myself a bit confused at times due to the naming conventions you use. Go ahead and make these changes, and clean up the code a little as far as those console logs and those functions you commented out, and you should be good to go!
NOTE: Please try to use better naming conventions.
An attempt at fixing:

Replacing this line:

JavaScript:
players.add(".playSingle" + i, (playerVarsList[i % (Object.keys(playerVarsList).length)] ||

With this line:

JavaScript:
players.add(".playSingle" + i, (playerVarsList[i] || {}));


Did not work.

I just tried.

t breaks button 3 when I do that: https://jsfiddle.net/vpjrsb9z/

No video appears at all when button 3 is clicked.

hghgfhfgh.png

Maybe almost fixed?

The 1st video isn't being selected anymore, that is good.
 
Cannot read properties of undefined (reading 'wrapper')"

The error happens because I added
HTML:
<button class="playInitial cover spinner" type="button" data-container="play1" data-id="EK3h0IADYrQ">
to the source code.

This increases totalPlayButtons

I need to change the way totalPlayButtons is calculated so that only the actual play buttons are counted, not the initial one.

How do I do that in the code? https://jsfiddle.net/ju5Lqbws/

JavaScript:
function findPlayers() {
    const allCovers = document.querySelectorAll(".cover");
    const allWrappers = document.querySelectorAll(".wrap");
    allCovers.forEach(function addToPlayers(cover, index) {
      players.push({
        "cover": cover,
        "wrapper": (index < allWrappers.length) ? allWrappers[index] : allWrappers[allWrappers.length - 1]
      });
    });
  }


  function getWrapper(cover) {
    const index = players.findIndex(
      (player) => player.cover === cover
    );
    return players[index].wrapper;
  }

JavaScript:
//to add the player to all the play buttons
  let totalPlayButtons = document.querySelectorAll('[data-container="play1"]').length;


  //looping over all the play buttons and adding player to that
  for (let i = 0; i < totalPlayButtons; i++) {
    players.add(".playSingle" + i, (playerVarsList[i] || {}));
  }
 
Fixed: https://jsfiddle.net/q6omxswa/

JavaScript:
document.querySelectorAll('button.cover').forEach(function(button) {
  button.addEventListener('click', function(event) {
    const container = event.currentTarget.dataset.container;
    const myVideo = document.querySelector('.' + container + ' .video');
    myVideo.dataset.id = event.currentTarget.dataset.id;
  });
});

JavaScript:
function findPlayers() {
    const allCovers = document.querySelectorAll(".cover");
    const allWrappers = document.querySelectorAll(".wrap");
    allCovers.forEach(function addToPlayers(cover, index) {
      players.push({
        "cover": cover,
        "wrapper": (index < allWrappers.length) ? allWrappers[index] : allWrappers[allWrappers.length - 1]
      });
    });
  }


  function getWrapper(cover) {
    const index = players.findIndex(
      (player) => player.cover === cover
    );
    return players[index].wrapper;
  }

JavaScript:
//to add the player to all the play buttons
  let totalPlayButtons = document.querySelectorAll('[data-container="play1"]').length;


  //looping over all the play buttons and adding player to that
  for (let i = 0; i < totalPlayButtons; i++) {
    players.add(".playSingle" + i, (playerVarsList[i] || {}));
  }
 
...all you need is a bit of null checking and you should be fine.
JavaScript:
if(typeof wrapper !== 'undefined' && wrapper !== null){
    //code goes here
}
How would this be fixed in the code?

JavaScript:
function initPlayer(wrapper, playerOptions) {
        if (typeof wrapper !== "undefined" && wrapper !== null) {
            show(wrapper);
            const player = createPlayer(wrapper, playerOptions);
            wrapper.player = player;
        }
    }

errrrr.png
 
How would this be fixed in the code?

JavaScript:
function initPlayer(wrapper, playerOptions) {
        if (typeof wrapper !== "undefined" && wrapper !== null) {
            show(wrapper);
            const player = createPlayer(wrapper, playerOptions);
            wrapper.player = player;
        }
    }

View attachment 1915

Do this then?

JavaScript:
function initPlayer(wrapper, playerOptions) {
        if (wrapper === "undefined" && wrapper === null) {
            show(wrapper);
            const player = createPlayer(wrapper, playerOptions);
            wrapper.player = player;
        }
    }
 
jslint is saying: 'Unused '_' - How would that be fixed?

https://jsfiddle.net/eptu01xg/

JavaScript:
totalP.forEach(function (_, index) {
        players.add(".playSingle" + index, (playerVarsList[index] || {}));
    });
The issue is with that underscore you have as a parameter inside that function in the forEach function. Remove that and the coma, then you should be ok
 
The issue is with that underscore you have as a parameter inside that function in the forEach function. Remove that and the coma, then you should be ok

Then I receive this error: https://jsfiddle.net/suawgv46/

Did you receive this error when you did what you had me do?

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '.playSingle[object HTMLButtonElement</a>' is not a valid selector."

dffgdfg.png
 
What was the reason you had me do that for if it breaks the code?

Were you mistaken? https://jsfiddle.net/suawgv46/
This is for that original "unused" parameter issue.
1672614870147.png
This here is telling you that whatever you are trying to query is not a valid query
1672614988724.png
The issue now is for you to debug it and find out where that is coming from. As I previously mentioned, and will keep mentioning, as you run into issues, please save all your code into separate files, and
Code:
 RUN THEM LOCALLY, WITHOUT THE USE OF ONLINE EDITORS
This will help you identify where the issues are coming from a lot quicker
 
This is for that original "unused" parameter issue.
View attachment 1929
This here is telling you that whatever you are trying to query is not a valid query
View attachment 1930
The issue now is for you to debug it and find out where that is coming from. As I previously mentioned, and will keep mentioning, as you run into issues, please save all your code into separate files, and
Code:
 RUN THEM LOCALLY, WITHOUT THE USE OF ONLINE EDITORS
This will help you identify where the issues are coming from a lot quicker
Perhaps this is valid then:

JavaScript:
totalP.forEach(function (_,index) {
 
Remove it, and see where the error is coming from. Why have a parameter in a function if you are not doing anything with it?
The issue should be coming from where you are calling that method
I was told this is valid code by multiple people: https://jsfiddle.net/suawgv46/

Either they are all wrong, or you are wrong.

Can you definitely say, 100% they are all wrong?

JavaScript:
totalP.forEach(function (_,index) {
 
Last edited:
I was told this is valid code by multiple people: https://jsfiddle.net/suawgv46/

Either they are all wrong, or you are wrong.

Can you definitely say, 100% they are all wrong?

JavaScript:
totalP.forEach(function (_,index) {
So one thing you have to learn is how to tell the difference between valid and correct. Just because it may be a valid thing, doesn't mean it is correct. IF you are taking it at face value, yes, it is valid syntax. Because it is inside of the parenthesis in the function signature, it is being treated as a parameter. However, coming back to my earlier statement...just because it may not cause any immediate errors, doesn't mean it is correct. Does it make sense to have a function like this

JavaScript:
function (someVar, index) {
    console.log(someArr[index]);
}

Code above:
I have two variables in my function signature, but I am only using one of them...what is the actual point of having that "someVar" variable in there if I'm not using it to begin with? So I will ask again, although it may be valid, do you actually need that there to begin with? If so, what is the intended purpose of it, otherwise, if you are not using it, it is just creating background noise and should be removed, for readability
 
Also, following my own advice, and separating all the code into its respective files, I get this error with I run it locally
1672724181655.png
It seems to be coming from this part of your js code
1672724219292.png

Any idea as to why?
 
Also, following my own advice, and separating all the code into its respective files, I get this error with I run it locally
View attachment 1932
It seems to be coming from this part of your js code
View attachment 1933

Any idea as to why?

I'm confused now.

Which code are you referring to?

This code gives me No Error.

https://jsfiddle.net/3hutLq0s/

JavaScript:
totalP.forEach(function (_,index) {
        players.add(".playSingle" + index, (playerVarsList[index] || {}));
    });

This code Gives Me An Error.
https://jsfiddle.net/3hutLq0s/1/

JavaScript:
totalP.forEach(function (index) {
        players.add(".playSingle" + index, (playerVarsList[index] || {}));
    });

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '.playSingle[object HTMLButtonElement'>1469:32] Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '.playSingle[object HTMLButtonElement</a>' is not a valid selector.
 
Last edited:

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom