B Johnson
B Johnson

Reputation: 193

Change contents of <span> on click

I have a <span> that I'm trying to change the contents of on click. I've followed a few tutorials but I can't seem to get it right so that it will change. I'm using unicode characters so I think I need to use .html() instead of .text() but I could be wrong. Any reason why this shouldn't work?

Here is the source that I'm working with

$(document).ready(function() {
  $(".dropdownheader").click(function() {
    $("#childList").toggle("slow");
    if ($("#droparrow").html() == '&rtrif;') {
      $("#droparrow").html('&dtrif;');
    } else {
      $("#droparrow").html('&rtrif;');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdownheader">Expected Outcomes of a Corporate Course <span id="droparrow">&dtrif;</span></div>
<div id="childList">
  <ul>
    <li>A better relationship with your coworkers.</li>
    <li>A High Trust and open enivornment.</li>
    <li>A safe and fun environment to work in.</li>
  </ul>
</div>

Upvotes: 2

Views: 684

Answers (1)

Jamiec
Jamiec

Reputation: 136094

It is because this check:

 if ($("#droparrow").html() == '&rtrif;')

Always evaluates false. A better way to do this might be to store a data-expanded attribute on your element and use that to determine whether to toggle - remembering to update the data item each click.

$(".dropdownheader").click(function() {
    $("#childList").toggle("slow");
    if($("#droparrow").data("expanded") == "1") {
        $("#droparrow").data("expanded","0").html('&dtrif;');
    } else {
        $("#droparrow").data("expanded","1").html('&rtrif;');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdownheader">Expected Outcomes of a Corporate Course <span id="droparrow" data-expanded="1">&rtrif;</span></div>
    <div id="childList">
        <ul>
            <li>A better relationship with your coworkers.</li>
            <li>A High Trust and open enivornment.</li>
            <li>A safe and fun environment to work in.</li>
        </ul>
    </div>

Upvotes: 4

Related Questions