turpentyne
turpentyne

Reputation: 155

jquery - text not switching on first click, then works fine

I have a quick little toggle that changes the text of a button when somebody clicks on it. It's working, but not on the first click, for some reason? Second click onward, it works fine. Any thoughts?

$( document ).ready(function() {
  $(".btn-archive-header").click(function(){
        var text = $(this).text() == 'VIEW ARCHIVE' ? 'CLOSE ARCHIVE' : 'VIEW ARCHIVE';
        $(this).text(text);
    });
});
<div class="btn-archive-header">
    VIEW ARCHIVE
</div>

Upvotes: 1

Views: 49

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Use the .trim() JavaScript method on the text obtained from the element:

$( document ).ready(function() {
  $(".btn-archive-header").click(function(){
        var text = $(this).text().trim() == 'VIEW ARCHIVE' ? 'CLOSE ARCHIVE' : 'VIEW ARCHIVE';
        $(this).text(text);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="btn-archive-header">
    VIEW ARCHIVE
</div>

Upvotes: 0

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you need to use $.trim()

$.trim($(this).text());

so your code will be

$( document ).ready(function() {
  $(".btn-archive-header").click(function(){
        var text = ($.trim($(this).text()) == 'VIEW ARCHIVE') ? 'CLOSE ARCHIVE' : 'VIEW ARCHIVE';
        $(this).text(text);
    });
});

DEMO

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25351

You have spaces in the value. Remove them and it works.

Change this:

<div class="btn-archive-header">
    VIEW ARCHIVE
</div>

to this:

<div class="btn-archive-header">VIEW ARCHIVE</div>

Here is how your code should be:

$( document ).ready(function() {
  $(".btn-archive-header").click(function(){
        var text = $(this).text() == 'VIEW ARCHIVE' ? 'CLOSE ARCHIVE' : 'VIEW ARCHIVE';
        $(this).text(text);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-archive-header">VIEW ARCHIVE</div>

Upvotes: 0

Related Questions