Reputation: 255
I have created a navigational menu
with some of them having submenus. I want the menuitem with fa-chevron-down
(down arrow icon) to change to change to fa-chevron-up
(up arrow icon) when user clicks on that menu item and changes back when user clicks anywhere else. Plus i also have two request,
1) Since i am very new to jquery, the jquery code that i wrote seems to do the trick but is there a better way? (notice when one menu item is clicked twice the sliding takes place twice. ITS ANNOYING)
2) When user resizes the window the html elements doesnot stays in place and scatters.
Thanks in advance.
UPDATE : Thanks for solving my problem. I refined my problem further and it is working perfectly. Here is the final** JSFIDDLE**
Upvotes: 15
Views: 38690
Reputation: 3281
Font Awesome v5 has changed things quite a bit.
This is the code I used to get a plus/minus collapse button working with Bootstrap, JQuery and FontAwesome.
HTML:
<a class="btn btn-collapse" id="btn-collapse" data-toggle="collapse" data-target="#collapse-section"><i class="fas fa-minus"></i></a>
JQuery script:
$("#btn-collapse").click(function() {
if ($(this).hasClass('collapsed')) {
$(this).find('svg').attr('data-icon', 'minus');
} else {
$(this).find('svg').attr('data-icon', 'plus');
}
});
You should be able to substitute plus/minus for chevron up and down.
Upvotes: 6
Reputation: 1093
For changing the icon you can easily do something like this in your click event:
$(this).find($(".fa")).removeClass('fa-chevron-down').addClass('fa-chevron-up');
for More take a look at jsfiddle example:
Upvotes: 27
Reputation: 18109
I think there is no need for changing the class.
If you only want to change the fa-chevron-down
to fa-chevron-up
icon, instead of switching the classes, just use toggleClass
for fa-rotate-180
. fa-rotate-180
will rotate your icon and it might solve your purpose. No need for adding/removing individual classes.
Let's say:
$('selector').click(function(){
$('menu-selector').toggleClass('fa-rotate-180');
});
It's just a sample. You can work around it.
Upvotes: 12