0

On a page, I have multiple button but with same class, and I want to add class loading on each button click.

$(".btn").click(function() {
    $(".btn").addClass('loading');
    alert("button 1 clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div>
  <a href="#" cass="btn btn-test">Button 1</a>
  <a href="#" class="btn btn-test">Button 2</a>
  <a href="#" class="btn btn-test2">Button 3</a>
  <a href="#" class="btn btn-test2">Button 1</a>
</div>

How to handle for different button clicked so each time button is clicked the same alert will appear?

2
  • Use $(this).addClass('loading'); Commented Aug 2, 2018 at 12:36
  • Do you want to add loading on each button when any of the buttons is clicked? Commented Aug 2, 2018 at 12:38

4 Answers 4

3

You can make use of this operator. Within the below example, this refers to the current object being handled.

See Mozilla Docs

<div>
  <a href="#" cass="btn btn-test">Button 1</a>
  <a href="#" class="btn btn-test">Button 2</a>
  <a href="#" class="btn btn-test2">Button 3</a>
  <a href="#" class="btn btn-test2">Button 1</a>
</div>

$(".btn").click(function() {
    $(this).addClass('loading');
    alert("button 1 clicked");
});
Sign up to request clarification or add additional context in comments.

Comments

1

You want the this keyword it refers to the object its within in this case the element clicked

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

$(".btn").click(function() {
    this.classList.add('loading')
});
.loading {background: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div>
  <a href="#" class="btn btn-test">Button 1</a>
  <a href="#" class="btn btn-test">Button 2</a>
  <a href="#" class="btn btn-test2">Button 3</a>
  <a href="#" class="btn btn-test2">Button 1</a>
</div>

Comments

0

use this keywoard this

$(".btn").click(function() {
    $(this).addClass('loading');
});

Comments

0
$(".btn").on('click', function() {
    $(this).addClass('loading');
    alert("button clicked");
});

Give them the same class and it should work.

1 Comment

Yea, my bad. Works either way

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.