Troy Riemer
Troy Riemer

Reputation: 85

Incremental JQuery Function On Load

I am trying to create a javascript or jQuery function (but open to other ideas) that will echo the number of html values based upon this php function.

<?php if( have_rows('SECTION') ): $i = 0;
    while ( have_rows('SECTION') ) : the_row(); $i++; ?>
        <div id='NAME-<?php echo $i; ?>'><?php the_sub_field('OBJECT'); ?></div>
        <div id='NAME-<?php echo $i; ?>-p'><?php the_sub_field('OBJECT-2'); ?></div>
    <?php endwhile;
    else :
endif; ?>

The basic jQuery function that I'm using is this:

$(function () {
    $('#NAME-1').click(function () {
        $('#NAME-1-p').stop().fadeIn(500);
    });
});

Right now I just repeat that function over and over and replace the number consecutively so there ends up being more functions than actual objects on the page. This is because the info being called by the php function can range from 1 - 20.

Looking for a more elegant solution. Thanks!

Upvotes: 1

Views: 45

Answers (1)

James
James

Reputation: 22247

I would use a class and then locate the second div relative to what was clicked:

<?php if( have_rows('SECTION') ): $i = 0;
    while ( have_rows('SECTION') ) : the_row(); $i++; ?>
        <div class='clickable'><?php the_sub_field('OBJECT'); ?></div>
        <div><?php the_sub_field('OBJECT-2'); ?></div>
    <?php endwhile;
    else :
endif; ?>

$(function () {
    $('.clickable').click(function () {
        $(this).next().stop().fadeIn(500);
    });
});

Upvotes: 1

Related Questions