hyprstack
hyprstack

Reputation: 4228

jQuery add class to button

I am trying to simply add a class to a button using jQuery. But nothing happens. Why?

http://jsbin.com/makoxibogeje/2/edit

This is my code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    <p>Press me!</p>
    <button>Test</button>
    <button>Fiddle</button>
</body>
</html>

CSS:

.spinner { color:red;}

Javascript

var B = {

    btn: $("button"),

    addSpinner: function() {
        B.btn.click(function() {
            this.addClass('spinner');
        });
    },
}

Upvotes: 0

Views: 1898

Answers (3)

The Alpha
The Alpha

Reputation: 146191

While the right answer is already given by Troy Gizzy but still you can improve a little by replaceing the B in B.btn.click with this, just like this

var B = {
    btn: $("button"),
    addSpinner: function() {
        this.btn.click(function() { // <-- You've used B.btn.click
            $(this).addClass('spinner'); //<-- You had to use $(this) instead of this
        });
    },
}.addSpinner();
.spinner { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Press me!</p>
    <button>Test</button>
    <button>Fiddle</button>

Upvotes: 1

Troy Gizzi
Troy Gizzi

Reputation: 2520

Inside that click callback function, this is a DOM element, not a jQuery object. Wrapping it as $(this) should make the addClass work.

var B = {

    btn: $("button"),

    addSpinner: function() {
        B.btn.click(function() {
            $(this).addClass('spinner');
        });
    },
}

P.S. Here's a JSFiddle to demonstrate it working. Note that you also have to call B.addSpinner(); from somewhere in order to wire up the click event handlers.

Upvotes: 5

Jerodev
Jerodev

Reputation: 33186

You have to wrap the this variable with jQuery before calling the addClass function

var B = {

    btn: $("button"),

    addSpinner: function() {
        B.btn.click(function() {
            $(this).addClass('spinner'); // <----
        });
    },
}

Upvotes: 0

Related Questions