Weverton Souza Weverton Souza - 1 year ago 67
jQuery Question

click the generated button while loop does not work

I have an unordered list that receives dynamic data mysql database, the list returns me some youtube links with Title thumbnail and full view of each video, I made a simple script that displays and hides a div using css disply none and display block this div that will receive the link and it will display the video, my problem is that only the first play button hides and shows the div, the other buttons dynamically created in while not working.

Here is my HTML and PHP receiving the data bank through while

<div class="divvideos">

<?php while($videolist = $resultvideos->fetch_array()){ ?>

<li class="listdivvideos">

<button class="btplay" id="btplay"></button>
<img src="images/datahoraicon.png" class="imgdatahora">



<img src="http://i1.ytimg.com/vi/<?php echo $videolist['miniatura'] ?>/default.jpg">




<?php } ?>


Here is the simple script to show and hide the div player


$("#btplay").click(function () {

if($("#player").css("display") == "none"){




My code works normally by clicking the button with the ID btplay it hides and shows the div with the id player, my only problem is that this button is created several times because the While it is created in the home line that returns the while but only the primero button hides and shows the div other buttons do not work

Answer Source

First, your Ids should be unique (as mentioned above). Leave them out or add a counter to it (better leave them out).

$(".btplay").click(function () {

should make the trick.

Tipp: You could replace

 <?php while($videolist = $resultvideos->fetch_array()){ ?>
 <?php } ?>


 <?php while($videolist = $resultvideos->fetch_array()): ?>
 <?php endwile; ?>


 <?php echo $videolist['miniatura'] ?>


 <?= $videolist['miniatura']; ?>

I think it makes it more readable, but it is just a tipp.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download