Walker Farrow Walker Farrow - 3 months ago 8
CSS Question

Set a CSS Class jquery

I have a page that can set email preferences.

Next to each email there is a "Yes/No" button (meaning is this person subscribed to this type of email).

If it is "Yes", the css class is set to bootstraps

success
class.

If it is "No", the css class is set to Boostrap's
danger
class.

I am trying to set it up so that when the user clicks this, it toggles the class and changes the
html
property of the button from "Yes" to "No" or vice-verse.

I use
$(this).html("Yes");
and this works just fine.

However when changing the classes, I have a script that runs as:

$(this).removeClass("success");
$(this).addClass("danger");


The problem is that when I use
$(this).removeClass()
and also
$(this).addClass()
, it doesn't change the element style. However, when I query the element it DOES remove the class and does add the class I want - the only problem is that the styling does not change.

The style DOES exist in the browser. If I load an element with
class="danger"
or an element with a
class="success"
it renders exactly how it should.

So something with this
removeClass
and
addClass
is not somehow triggering the STYLE to update.

What am I doing wrong?

Answer

The below works just fine for me,

however, without your exact HTML and Javascript, this is simply a guess

Let me know how it goes for you.

$(document).ready(function(){
  $('.email-button').on('click',function(){
      $(this).toggleClass('btn-danger btn-success');
      $(this).html($(this).hasClass('btn-success') ? 'Yes' : 'No');
    })
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn btn-danger email-button">No</button>

Comments