Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle button to show/hide data from API

Tags:

javascript

php

I have a meetup.com API on my website that pulls in descriptions of events. I would like to have this information hidden by a toggle button so that when you click on 'More Info' the description shows.

Here is my javascript for the toggle button:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle();
    });
});
</script>

And here is the PHP:

$ct = 1;
foreach ($my_array['results'] as $event) {
   echo '<strong> ' . $event['name'] . '</strong>' . '<br />';
   echo '<strong>Event link:  </strong><a href="' . $event['event_url'] .'" target="_blank">' .  $event['event_url']  . '</a><br />';
   echo '<strong>When: </strong>' . date('Y-m-d H:i', $event['time']/1000) . '<br />' ;
  // echo '<strong>More Info: </strong>' . $event['description'] . '<br />';
   echo '<strong><button>More Info</button></strong><infobox>' . $event['description'] . '</infobox><br />';

$ct = $ct+1;

This is what it looks like live: http://maddusability.com/icm505/meetups.php

As you can see, it is only allowing me to show/hide all event descriptions at once, not individually - even though I created a unique id for each event. Any ideas?

like image 347
MadCM Avatar asked Feb 27 '26 08:02

MadCM


1 Answers

You have to use the this keyword and DOM traversal to target the correct elements

$(document).ready(function(){
    $("button").click(function(){
        $(this).closest('strong').next('infobox').find("p").toggle();
    });
});

FYI: <infobox> seems like an invalid tag to me ?

like image 117
adeneo Avatar answered Feb 28 '26 20:02

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!