fanni-portier
fanni-portier

Reputation: 31

Use data-attribute for toggle link

I'm very new to jquery. How can I use a data attribute for toggling?

I want to select the element with the class="filter-group" and the same data-toggle attribute like the button has:

$('button').click(function() {
  var toggleID = $(this).data('toggle');
  $('.filter-group[data-toggle= toggleID ]').toggle();
});

https://codepen.io/elkeschiffer/pen/PWZKmE

Upvotes: 1

Views: 1951

Answers (2)

Amir Hossain
Amir Hossain

Reputation: 693

You can also do this way.Define class name as per button attr

<button type="button" data-toggle="toggle1">Button 1</button>
<button type="button" data-toggle="toggle2">Button 2</button>

<div class="filter-group toggle1" data-toggle="toggle1">
  Filter Group 1
</div>

<div class="filter-group toggle2" data-toggle="toggle2">
 Filter Group 2
</div>

Change your js this way.

$(".filter-group").hide();
$('button').click(function() {
var toggleID = $(this).attr('data-toggle');
 $("."+toggleID).toggle();
});

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42054

Your issue is in this line:

$('.filter-group[data-toggle= toggleID ]').toggle();

Change it to:

$('.filter-group[data-toggle=' + toggleID + ']').toggle();

$(".filter-group").hide();

$('button').click(function() {

    var toggleID = $(this).data('toggle');
    $('.filter-group[data-toggle=' + toggleID + ']').toggle();

});
* {
    margin:0;
    padding:0;
    box-sizing:border-box;
    font-size:1.3rem;
}

button {
    padding:1rem;
    background-color:salmon;
    border:none;
}

.filter-group {
    background-color:silver;
    padding:1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button type="button" data-toggle="toggle1">Button 1</button>
<button type="button" data-toggle="toggle2">Button 2</button>


<div class="filter-group" data-toggle="toggle1">
    Filter Group 1
</div>

<div class="filter-group" data-toggle="toggle2">
    Filter Group 2
</div>

Upvotes: 1

Related Questions