I currently have a button with a span that displays an icon with an arrow, like so:
<button id="btnCollapse" type="button" onClick="hey()" class="btn btn-default btn-sm">
<span id="iconCollapse" class="glyphicon glyphicon-collapse-down"></span>
Collapse Views
</button>
I would want onClick function to instead now say Expand Views, and have the glyphicon-collapse icon to be up
rather than down
Here’s what I have come up with:
function hey() {
var btn = $("#btnCollapse");
var span = btn.children("#iconCollapse");
span.addClass("glyphicon glyphicon-collapse-up");
btn.html = "Expand Views"
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btnCollapse" type="button" onClick="hey()" class="btn btn-default btn-sm">
<span id="iconCollapse" class="glyphicon glyphicon-collapse-down"></span>
Collapse Views
</button>
What I am actually trying to achieve is this:
If user clicks on Collapse View – I want to perform some functionality, something along the lines of
if (btn.html.contains('Collapase'))
Then
//do something
Else
//do something else
2
Answers
First: ID should be unique .. That means if you will use multiple
collapse/expand
elements you need to change theid
to classSecond: if you change the HTML you’ll remove the icon so it will be better to wrap the text inside
<span>Collapse</span>
or change all the html like the example belowFor me this isn’t the good way to do that .. But you can use this code temporarily untill you get a best code of it
And the good way to do this is:
JS ES6/css3 make it easier:
also :