-1

I am trying to toggle the opacity of a DOM element on an event which is attached to a javascript method. A click on checkbox is what triggers the completed method.

The below method is triggered on a click:

 completed: function(){
                var task = this.$('.actions');

                console.log(task);

                if(!task.hasClass('toggle')){

                    task.addClass('toggle');
                } else {
                    task.removeClass('toggle');
                }

               }
            }

The CSS .toggle{ opacity: 0.4; }

and the HTML (underscore template, in this case) is

        <div class="table table-bordered">
            <div class="actions">
                <input type="checkbox" class='completed'>
                <button type='button' class='delete btn btn-danger btn-xs'> x </button>
                <button type='button' class='edit btn btn-primary btn-xs' id='actions'> edit </button>
                <span style='font-weight:bold' class="word" spellcheck='false'> <%= task %>-</span>
                <span class="definition" spellcheck='false'> <%= description %> </span>
            </div>
        </div>  

But nothing happens. How can I addClass to a DOM element via javascript?

redress
  • 1,399
  • 4
  • 20
  • 34
  • `this.$('.actions');` is not correct. if you want `.actions` _inside_ the current element, use `$('.actions', this);` – Rhumborl Jan 14 '15 at 20:27
  • possible duplicate of [How do I add a class to a given element?](http://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element) – Ryan Jan 14 '15 at 20:32

1 Answers1

2

When you add a class using jQuery, you don't need a prefix .:

task.addClass('toggle');

Furthermore, your function seems slightly off:

You either want to use this, when you want to select .action globally

var task = $('.actions');

or this, if it shall be a childnode of the current this object:

var task = $( this ).find('.actions');
Sirko
  • 72,589
  • 19
  • 149
  • 183