Jassi Jassi - 2 months ago 15
CSS Question

Slidetoggle and changing glyphicon

This is my first project and my first post here so go easy on me ;)

jQuery is what I'm struggling on. I want to have a button with an arrow pointing down to allow the user to slide out more informations, and when i click it, it should change that glyphicon to point up. So they understand how to hide the informations.

This is what I have currently:

Html:

<section id="about">
<a name="about"></a>
<div class="container">
<h2>Über</h2>
<p class="topDist">Hier steht erklärender Text über uns.</p>

<a href="javascript:return false;" id="button" class="btn btn-primary
btn-lg">Mehr<i class="glyphicon glyphicon-menu-down"></i></a>

<div id="hidden_content">Hier steht die detallierte Beschreibung. Dieser Text wird erst nach einem Klick auf den Button eingeblendet.</div>
</div>
</section>

jQuery

$(document).ready(function(){
$("#button").click(function(){
$("#hidden_content").slideToggle("slow");
});
});

$('#button').click( function(){
$(this).find('i').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
});


I found this How do I change a glyphicon upon clicking it in Bootstrap 3.2? and tried to use it for my project. It worked one time but then only the slidetoggle worked and the changing glyphicon didn´t.

I could really use your help here.
Thank you so much!

Answer

Your HTML is invalid. Change:

<span i class="glyphicon glyphicon-menu-down"></i></span>

to

<span><i class="glyphicon glyphicon-menu-down"></i></span>

Beside this you can combine your click listeners and the toggleClass into one call.

$(function() {
    $("#button").click(function() {
        $("#hidden_content").slideToggle("slow");
        $(this).find('i').toggleClass('glyphicon-menu-down glyphicon-menu-up');
    });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<section id="about">
  <a name="about"></a>
  <div class="container">
    <h2>Über</h2>
    <p class="topDist">foo</p>
    <a href="javascript:return false;" id="button" class="btn btn-primary btn-lg">
      more
      <span><i class="glyphicon glyphicon-menu-down"></i></span>
    </a>
    <div id="hidden_content">bar</div>
  </div>
</section>

Comments