Reputation: 155
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
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
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);
});
});
Upvotes: 1
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