Find div with attribute value equal to that selected with jquery

1

I have several buttons with data-numBtn numeric and with value equal to the div (with data-slide attribute) that it controls. In short, I liked that when I clicked for ex: .btn with data-numBtn="3" something happens (eg fadeIn) to .img with data-slide="3" as well. PS: Elements will be dynamically loaded, no matter how many they will be, elements data-numBtn and data-slide will always match.

HTML:

<div class="btn" data-numBtn="1">...</div>
<div class="btn" data-numBtn="2">...</div>
<div class="btn" data-numBtn="3">...</div>
<div class="btn" data-numBtn="4">...</div>

<div class="img" data-slide="1">...</div>
<div class="img" data-slide="2">...</div>
<div class="img" data-slide="3">...</div>
<div class="img" data-slide="4">...</div>
    
asked by anonymous 21.11.2014 / 12:46

2 answers

2

If your elements are loaded dynamically you will need to delegate this event. So I suggest using $(document).on('click', '.btn', function(){ that will look for the element with class btn only when the click appears and not when it loads the code in case it is not already there.

To read this attribute data you can use .data() of jQuery. One possible code for this problem would be:

$(document).on('click', '.btn', function(){
    var numBtn = $(this).data('numBtn');
    $('.img[data-slide="' + numBtn + '"]').fadeIn();
});

In case there are numbers that clash with each other you will have to use .index() to know the position of this .btn relative to others, ignoring the data attribute. If this is the case, you can use it like this:

$(document).on('click', '.btn', function(){
    var numBtn = $(this).index();
    $('.img[data-slide]').eq(numBtn);
});
    
21.11.2014 / 13:23
1

You can select the image using the .img class and the data-slide attribute itself. To select the image 3:

$('.img[data-slide="3"]');

To select the image corresponding to the button, simply:

$('.btn').on('click',function(){
   var btnId = $(this).attr('data-numBtn'); // pega o id do botão clicado
   var $img = $('.img[data-slide="'+btnId+'"]'); // seleciona a imagem correspondente ao id do botão clicado

   $img.fadeIn(); 
});
    
21.11.2014 / 12:58