Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing HTML entities in jQuery

Tags:

html

jquery

I have the following html, which is a dl tag containing a dt tag with a class of toggle and containing the FAQ, and then a dd tag with a class of expand that contains the answer to the FAQ:

<dl>
<dt class="toggle">&#9660; Here is a FAQ</dt>
<dd class="expand">
    <p>And here is the answer</p>
</dd>
....
</dl>

and the following jQuery:

$(function () {
    $('.expand').hide();

    $('.toggle').click(function() {
        var $expand = $(this).next('.expand');
        if ($expand.is(':hidden')) {
            $expand.slideDown();
        } else {
            $expand.slideUp();
        }
    });
});

This function expands or collapses the FAQ answer.

What I would really like to do is additionally replace the ▼ down arrow with a ▲ up arrow when the text is expanded. I do not want to use images or sprites.

No matter how I try to encode / use the slice or substring functions I have so far been unable to achieve this.

Any comments appreciated, but be kind as this is my first post.

like image 469
Freeway Avatar asked Dec 21 '25 01:12

Freeway


2 Answers

Another option is just to rely on CSS to show hide the up and down arrows.

$(".toggle").on("click", function () {
    $(this).toggleClass("open");
});
.toggle {
    cursor: pointer;  
}

.toggle > span + span {
  display : none;
}

.toggle.open > span {
  display : none;
}

.toggle.open > span + span {
  display : inline;
}

.toggle + dd.expand { display : none; } 
.toggle.open + dd.expand { display : block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
<dt class="toggle"><span>&#9650</span><span>&#9660;</span> Here is a FAQ</dt>
<dd class="expand">
    <p>And here is the answer</p>
</dd>
</dl>
like image 69
epascarello Avatar answered Dec 22 '25 15:12

epascarello


Place your arrow inside an <i> tag so that you can target it using jQuery:

<dt class="toggle"><i>&#9660;</i> Here is a FAQ 1</dt>

Example:

$(function () {

  $('.expand').hide();

  $('.toggle').click(function() {
    var $expand = $(this).next('.expand');
    var isHidden = $expand.is(':hidden');
    $expand.slideToggle();
    $("i", this).html(isHidden? "&#9650;" : "&#9660;");
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 1</dt>
  <dd class="expand">
    <p>1 And here is the answer</p>
  </dd>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 2</dt>
  <dd class="expand">
    <p>2 And here is the answer</p>
  </dd>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 3</dt>
  <dd class="expand">
    <p>3 And here is the answer</p>
  </dd>
</dl>
like image 32
Roko C. Buljan Avatar answered Dec 22 '25 14:12

Roko C. Buljan