0

I have the following bootstrap data toggle markup and I want to change the icon and the text to change on toggle. I can get the text to change but not the icon. What I'm I doing wrong?

 <div id="collapseDiv" >
    <dl>
      <dt>...</dt>
      <dd>...</dd>
    </dl> 
 </div>

 <a href="#collapseDiv" data-toggle="collapse" class="icon-before" data-icon="&#xf196">Show More</a>

Jquery code is as follows

 $('#collapseDiv').on('shown.bs.collapse', function () {
   $('.icon-before').data('icon', '&#xf147').text('Show Less');
 });

$('#collapseDiv').on('hidden.bs.collapse', function () {
    $('.icon-before').data('icon', '&#xf196').text('Show More');
});
adam78
  • 9,668
  • 24
  • 96
  • 207

3 Answers3

1

Try using attr()

attr('data-icon', '&#xf147')

Also check this excellent answer

EXPLANATION

Check the following example.

If you click on span#one the attribute changes with attr() function, if you click on span#two we will try to change the attribute with data() function.

When you try to select the element with [data-test="false"] only the first element has changes it's data attribute.

Only the element with data-test="false" will get red:

$(document).on('click', 'span', function() {
  var that = $(this);
  var id = that.attr('id');
  if (id == 'one') {
    //Try with attr()
    that.attr('data-test', 'false');
  } else if (id == 'two') {
    //Try with data()
    that.data('test', 'false');
  }
  $('[data-test="false"]').css({'color':'red'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="one" data-test="true">one</span>
<span id="two" data-test="true">two</span>
Community
  • 1
  • 1
kapantzak
  • 11,610
  • 4
  • 39
  • 61
0

You should update the attribute value, rather than updating data property:

$('#collapseDiv').on('shown.bs.collapse', function () {
 $('.icon-before').attr('data-icon', '&#xf147').text('Show Less');
});

$('#collapseDiv').on('hidden.bs.collapse', function () {
 $('.icon-before').attr('data-icon', '&#xf196').text('Show More');
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You should also update class of .ui-icon inside.

var oldIcon = $('.icon-before').data('icon'),
    newIcon = '&#xf147';
    uiIcon = $('.icon-before').data('icon', newIcon).find('.ui-icon');
uiIcon.removeClass('ui-icon-' + oldIcon).addClass('ui-icon-' + newIcon);
Alexey Rytikov
  • 558
  • 6
  • 12