Toggle icon with Jquery

Asked

Viewed 79 times

2

<span class="col-sm-1 text-center">
    <i class="taskIcon glyphicon glyphicon-chevron-down" data-toggle="collapse" data-parent="#accordion" href="#collapse1"></i>
</span>

$(“.taskIcon”).on(“click”,function (){ 
    $(this).find(“glyphicon”).removeClass(“glyphicon-chevron-down”).addClass(“glyphicon-chevron-up”);
});

I have an icon, I’m trying to interlink it when the same and clicked, I did the above script adding the class I want but it doesn’t seem to get the correct class.

If anyone can help, I’d appreciate it.

  • The quotes seem to be wrong and try to put find(".glyphicon"), with the point at the beginning, to identify which is a class.

1 answer

1


The quotes you’re putting are quotes from a text editor like Microsoft Word for example, not the right quotes for Javascript or any code.

In the code the find("glyphicon") that has is unnecessary because the click is already done in the same element, and lacked a . to be a class selector.

See how it already works by getting these two details right:

$(".taskIcon").on("click",function (){ 
    $(this).removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span class="col-sm-1 text-center">
    <i class="taskIcon glyphicon glyphicon-chevron-down" data-toggle="collapse" data-parent="#accordion" href="#collapse1"></i>
</span>

But if the idea was to switch the arrow every time you click, then the function toggleClass is more useful, simply by alternating the two arrow classes:

$(".taskIcon").on("click",function (){ 
    $(this).toggleClass("glyphicon-chevron-down").toggleClass("glyphicon-chevron-up");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<span class="col-sm-1 text-center">
    <i class="taskIcon glyphicon glyphicon-chevron-down" data-toggle="collapse" data-parent="#accordion" href="#collapse1"></i>
</span>

Documentation for toggleClass function

  • Now I get it, bro, it was worth it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.