Reputation: 1094
I am trying to do the typical Show/Hide menu with javascript or Jquery. The issue I'm having is that font awesome icons or bootstrap seem to be messing up the .text() function so that there is extra spacing and my if statements won't work as expected. Hoping to get this to work cross-browser too.
$('#list-btn').click(function() {
var el = $('#list-btn')
console.log(el.text())
if (el.text() == el.text("Hide Instructions")) {
el.text("Show Instructions");
} else {
el.text("Hide Instructions");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/>
<li>
<a href="#" class="hidden-sm hidden-xs" data-toggle="tab" id="list-btn">
<i class="fa fa-fw fa-list white"></i> Hide Instructions</a>
</li>
Upvotes: 0
Views: 59
Reputation: 133453
You need to correct the comparison.
if (el.text().trim() === "Hide Instructions"){
However, I would recommend you to wrap the text in a span
. It will prevent the <i>
element from being removed when the text()
operation is performed.
$('#list-btn').click(function() {
var el = $('span', this)
console.log(el.text())
if (el.text().trim() == "Hide Instructions") {
el.text("Show Instructions");
} else {
el.text("Hide Instructions");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" />
<li>
<a href="#" class="hidden-sm hidden-xs" data-toggle="tab" id="list-btn">
<i class="fa fa-fw fa-list white"></i> <span>Hide Instructions</span></a>
</li>
Upvotes: 1
Reputation: 121
Jquery Code
<script>
$(document).ready(function(){
$('#list-btn').off().on('click',function() {
var el = $('#list-btn')
console.log(el)
if (el.text() == "Hide Instructions") {
el.text("Show Instructions");
} else {
el.text("Hide Instructions");
}
});
});
</script>
Upvotes: 0