Bobmd
Bobmd

Reputation: 135

slideToggle Div and Rotate Icon if visible or hidden

If you click on a div, I want the target "panel" to slideToggle(). If the target panel is hidden, I want to add a class to a glyphicon which will spin it 270 degrees.

I've got everything working except the check for visible is failing. What am I doing wrong?

$(document).delegate(".showhide", "click", function(e) {
  var panel = $(this).attr('panel');
  $("#" + panel).slideToggle();
  var icon = $(this).attr('icon');

  if ($("#" + panel).is(":visible")) {
    $("#" + icon).removeClass('gly-rotate-270');
  } else {
    $("#" + icon).addClass('gly-rotate-270');
  }
});
.gly-rotate-270 {
  filter: progid: DXImageTransform.Microsoft.BasicImage(rotation=1);
  -webkit-transform: rotate(270deg);
  -moz-transform: rotate(270deg);
  -ms-transform: rotate(270deg);
  -o-transform: rotate(270deg);
  transform: rotate(270deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showhide" panel="panelskills" icon="skillsicon">
  <span class="glyphicon glyphicon-circle-arrow-down" id="skillsicon"></span> Skill Level
</div>

<div id="panelskills">
  Some content in here...
</div>

Here's the fiddle

Thanks for your help.

Upvotes: 1

Views: 490

Answers (2)

zer00ne
zer00ne

Reputation: 44086

UPDATE

  • Trimmed down the HTML
  • For rotation of icon use toggleClass('glyphicon-circle-arrow-down glyphicon-circle-arrow-right');

  • Change panel and icon to data-panel and data-icon

  • Change .attr() to .data().

panel and icon are not attributes. data-panel and data-icon are valid and the values are strings which is exactly what you need. .data() is the recommended method to use with data-* attributes.

Also .delegate() is deprecated use .on() instead.

SNIPPET

$('.showhide').on("click", function(e) {
  var panel = $(this).data('panel');
  console.log(panel);
  var icon = $(this).data('icon');
  console.log(icon);

  $("#" + panel).slideToggle();
  $("#" + icon).toggleClass('glyphicon-circle-arrow-down glyphicon-circle-arrow-right');

});
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="glyphicon glyphicon-circle-arrow-down" id="skillsicon"></span>  <a href='#/' class="showhide" data-panel="panelskills" data-icon="skillsicon">Skill Level</a>


<div id="panelskills">
  Some content in here...
</div>

Upvotes: 1

Suhail Akhtar
Suhail Akhtar

Reputation: 2033

HI Bro try this fiddle https://jsfiddle.net/pvc3s0ug/11/

Change your js like this

    $(document).ready(function() {    
    $(document).delegate(".showhide", "click", function(e) {

      var panel = $(this).attr('panel');

      $("#" + panel).slideToggle();

      var icon = $(this).attr('icon');
     $("#"+ icon).toggleClass('gly-rotate-270');

    });
 });

Upvotes: 1

Related Questions