Weverton Souza Weverton Souza - 5 months ago 20
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">
<ul>

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

<li class="listdivvideos">

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

<ul>

<li>

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

</li>

</ul>


</li>

<?php } ?>

</ul>
</div>


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

<script>

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

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

$("#player").css("display","block");
}else{
$("#player").css("display","none");
}


});

</script>


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

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 } ?>

with

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

And

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

with

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

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