Lucien Dubois
Lucien Dubois

Reputation: 1674

How to get data attribute with jQuery .each()

I work on a portfolio where there a few people. Each person has a demo and a click on the person should lead to the video.

My problem is that it returns the same videoid for everyone.

Here is what looks like a person container (I got 8 of them). I removed some code to keep the essential.

<div class="personnecontainer">
  <h2 class="nompersonne">Nom</h2>
  <div class="demo<?php echo $i; ?> democontainer" role="button" data-videoid="<?php the_sub_field('demo'); ?>">
    <p class="vert titrelh60v2">Mon démo</p>
  </div>
</div>

I managed to create javascript code that almost work.

<script>
jQuery( document ).ready(function() {
    jQuery('.democontainer').each(function(){
        jQuery(this).click(function() {

            jQuery('.socialcontainer').fadeOut('300');

            jQuery('.page-content').fadeOut(300, function() {
                var videoid = jQuery('.democontainer').data('videoid');

                var contenup1 = "<div class='js-video vimeo widescreen'><iframe id='video1' src='//player.vimeo.com/video/";
                var contenup2 = videoid;
                var contenup3 = "?color=009999&amp;title=0&amp;byline=0&amp;portrait=0&amp;api=1&amp;player_id=video1' width='580' height='326' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>";
                jQuery('.page-content').html(contenup1+contenup2+contenup3).fadeIn(300);

            });
        });
    })
}); // Fin document ready
</script>

What should I modify, where is my error?

Upvotes: 0

Views: 137

Answers (1)

Wilmer
Wilmer

Reputation: 2511

jQuery is always getting the first item in the collection of .democontainer, you should use jQuery(this) to get the clicked element:

<script>
jQuery( document ).ready(function() {
    jQuery('.democontainer').each(function(){
        jQuery(this).click(function() {
            var videoid = jQuery(this).data('videoid');
            jQuery('.socialcontainer').fadeOut('300');
            jQuery('.page-content').fadeOut(300, function() {
                var contenup1 = "<div class='js-video vimeo widescreen'><iframe id='video1' src='//player.vimeo.com/video/";
                var contenup2 = videoid;
                var contenup3 = "?color=009999&amp;title=0&amp;byline=0&amp;portrait=0&amp;api=1&amp;player_id=video1' width='580' height='326' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>";
                jQuery('.page-content').html(contenup1+contenup2+contenup3).fadeIn(300);

            });
        });
    })
}); // Fin document ready
</script>

Upvotes: 1

Related Questions