S. E.
S. E.

Reputation: 415

jQuery "if" to change text

Should this work, or am I doing something completely wrong?

HTML:

<div class="header-title">
<h1 class="h1-title" id='title'>America</h1>
</div>

jQuery:

 $('#title').click(function(){
    var classExist = $(this).hasClass('active-t');
    if(classExist = false) {
        $('.header-title').html("<h1 class='h1-title'>'Murica!</h1>");
    }
    if(classExist = true) {
        $('.header-title').html("<h1 class='h1-title'>America</h1>");
    }
});

JSFIDDLE

Anyways, I cant get it to work

Upvotes: 0

Views: 593

Answers (3)

Tomanow
Tomanow

Reputation: 7367

You are using = instead of === when checking for true or false. Also, why not simplify to just alter the text()?

Added toggleClass because I think that is what you are trying to do.

$('#title').click(function () {
    var classExist = $(this).hasClass('active-t');
    if (!!classExist) {
        $(this).text("'Murica!");
    } else {
        $(this).text('America');
    }
    $(this).toggleClass('active-t');
});

FIDDLE

Upvotes: 0

Alex Char
Alex Char

Reputation: 33218

You can simple:

 $('#title').click(function() {
   $(this).hasClass('active-t') ? $('.header-title').html("<h1 class='h1-title'>America</h1>") : $('.header-title').html("<h1 class='h1-title'>'Murica!</h1>");

 });

Upvotes: 5

Sterling Archer
Sterling Archer

Reputation: 22395

if(classExist = false) {
    $('.header-title').html("<h1 class='h1-title'>'Murica!</h1>");
}
if(classExist = true) {
    $('.header-title').html("<h1 class='h1-title'>America</h1>");
}

These are assignment statements, not comparisons. Use === instead of =

Also, you didn't specify to load jquery in your fiddle.

Upvotes: 4

Related Questions