user3143218
user3143218

Reputation: 1816

How to add class with data-attribute?

I am working on some data buttons but can't figure out how to get the function working. I'm trying to add a class to an element via a data-attribute and a corresponding ID. I then want to stop the event propagation with the button inside the subject.

So far this is what I have:

HTML:

<div class ="subject" id="subject1">
    <button class="remove">Remove</button>
    The Subject
</div>
<div class ="subject"  id="subject2">
    <button class="remove">Remove</button>
    The Subject 2
</div>
<div class ="subject" id="subject3">
    <button class="remove">Remove</button>
    The Subject
</div>

<button class="trigger" data-subject="subject1">Trigger</button>
<button class="trigger" data-subject="subject2">Trigger</button>
<button class="trigger" data-subject="subject3">Trigger</button>

CSS:

.active {
    color:red
}

JS:

var subject = document.querySelector('.subject');
var trigger = document.querySelector('.trigger');
var remove = subject.querySelector('.close');
var data = trigger.getAttribute("data-subject");

var datajs = (function () {

    function init() {

    [].forEach.call(trigger),function(btn) {
    btn.onclick = function() {this.classList.add("active");}

    });

     remove.addEventListener('click', function (ev) {
     ev.stopPropagation();
     removeModalHandler();
    });
 });
     }

    init();

})();

and here's a fiddle: http://jsfiddle.net/tNS62/1/

My JS isn't that great as you can probably see.

Upvotes: 0

Views: 1536

Answers (1)

Serge K.
Serge K.

Reputation: 5323

Try this. First we select all the buttons :

var triggers = document.querySelectorAll('.trigger');
var removes = document.querySelectorAll('.remove');

Then we apply the behavior on each button :

for (var i =0; i < triggers.length; i++) {
    var btn = triggers[i];
    btn.addEventListener('click', function () {
        var id = this.dataset.subject;
        document.querySelector('#' + id).classList.toggle('active');    
    }, false);
}

Use dataset to get the id attached to, then search the corresponding element in order to toogle the active class.

I made the same thing for the remove buttons.

Upvotes: 1

Related Questions