0

So for my website, I read data from a database, each video game has a description, once I receive the description from the database using PHP, I split the description into 2 parts one part that is visible and another that is hidden until the user clicks "Read More". I have multiple games on a page which means I have multiple "Read Me" buttons. In my javascript, I have the code so when the user clicks any of the "read me" buttons that the selected button disappears.

This is the part that I have my issue, how do I get it so when the user clicks one of the "Read me" buttons that the hidden text that corresponds with that button is displayed?

Here is the code I have right now.

var readMoresList = document.getElementsByClassName("readMore");
for (var i = 0; i < readMoresList.length; i++) {
  readMoresList[i].addEventListener('click', function (e) {
  var selected = e.target;
  selected.style.visibility = 'hidden';

  //here i am selecting the second description that is hidden
  var reveals = document.getElementsByClassName("readMore");
  reveals[i].style.visibility = 'visible';

}); }

so The readMoreList variable is the array of readMore buttons, I get them and add an eventListener to them and wait till they are clicked. The reveals variable is the array of hidden descriptions.

What I am looking for is how to set things up so when I click on a readMe button the hidden text that is adjacent to that read me will be visible.

Thank you

1 Answers1

0
  //here i am selecting the second description that is hidden
  var reveals = document.getElementsByClassName("readMore");

No, you're selecting the buttons again. Use a different class for the hidden text.

  reveals[i].style.visibility = 'visible';

By the time this runs, i will always be equal to readMoresList.length. Closures inside loops can be counter-intuitive.

AuxTaco
  • 4,883
  • 1
  • 12
  • 27
  • yes, my apologies I was playing around with my code before I posted it. Even with the change I still have the same problem. I need to find a way to reveal the text that corresponds to the "read me" button that is selected. So ill basically have 2 arrays 1 filled with the buttons with the "click" eventListner and an array filled with hidden texts for each game. I need to find a way to say when "readMe" is clicked, hide the "read me" button and make the text for that game visible –  Jan 25 '19 at 00:20
  • @CodingJedi Did you read the linked question? That's the crux of the problem. Applying one of the solutions there to your code will fix it. – AuxTaco Jan 25 '19 at 01:12
  • Thank you, my apologies again, on my screen it looked like normal text. Thanks for the help that solved the problem –  Jan 25 '19 at 01:45