Toggle icon with JQuery

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 merge it when it's clicked, I made the above script adding the class I want but it does not seem to get the correct class.

If someone can help, thank you.

    
asked by anonymous 28.10.2017 / 00:19

1 answer

1

The quotation marks you are putting are quotes from a text editor like Microsoft Word for example, not the right quotation marks for JavaScript or any code.

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

See how it works by hitting these two details:

$(".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><linkhref="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 each time you click, then the toggleClass function is more useful, just by switching 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><linkhref="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 the toggleClass function

    
28.10.2017 / 01:03