Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through php variable div class using jquery

Tags:

html

jquery

css

php

I'm having a bit of trouble using variable generated php div classes and jQuery to use the fadeToggle() feature. I've got two elements in question. The first contains a link to click and the second contains a description about the link and I want to add a simple fadeToggle to the first div when clicked to show and hide the description. However, the div classes are dynamically generated using a php for loop. I've got 12 different links and 12 different descriptions that get inserted from outside folders using a php for loop. Here's the code:

<?php for ($i = 1; $i <= 12; $i++): ?> 
<p>
<a href="" onclick="return false" class="<?php echo "project$i-text-link-visible"; ?>">
    <span class="text-expand-symbol"></span>
     View project details:
</a>
</p>

<!-- PROJECT DESCRIPTION -->
<div class="<?php echo "project$i-description-hidden"; ?>">        
    <?php include 'descriptions/project' . $i . '.inc.html.php'; ?>
</div>  
<?php endfor; ?>

So i'm having trouble using jQuery's fadeToggle because I do not know how to iterate through the dynamically generated php div classes. If I change the div class to something static like "project-description", the script I tried causes every description box to open at once when I click on any of the links. Any ideas would be very much appreciated.

You can check out the site and see the problem for yourself, if you like.
Visit http://www.romanleykin.com/projects and scroll down to the "Class Projects" section to get an idea of what I'm trying to accomplish. Currently, the site uses an ugly javascript code that changes the css properties from hidden to visible, but I would like to use jQuery for this. Any ideas would be very much appreciated. Thanks in advance.

like image 298
jacknone Avatar asked Jun 16 '26 19:06

jacknone


1 Answers

Use custom data attributes:

<?php for ($i = 1; $i <= 12; $i++): ?> 

<a href="#" data-target="<?php echo $i ?>"> ... </a>

<div id="target_<?php echo $i ?>"> ... </div>

<?php endfor; ?>

Then the JS code:

$(function(){

    $('a[data-target]').on('click', function(event){

        event.preventDefault();

        $('#target_' + $(this).attr('data-target')).fadeToggle();

    });

});

This way you tie each anchor to its related div without messing with classes.

like image 146
moonwave99 Avatar answered Jun 18 '26 11:06

moonwave99



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!