javascriptjqueryhtmlajax

matching element with html content using jquery html()


I don't understand... if i replace remove font awesome and use text() instead of html() this will work... But if i try the same code using font awesome icons, nothing happens and the text isn't changing on the button. What am i doing wrong ?

<a class="read-more" id="read-more">
        <span class="view-more-images" id="view-more-images"><i class="fa fa-plus" aria-hidden="true"></i> VIEW MORE IMAGES <i class="fa fa-plus" aria-hidden="true"></i></span>
</a>
 
    <script>
    $( document ).ready(function() {
        $('.read-more').click(function(){
            $(this).parent().toggleClass('expanded');
        });
    
        $('.read-more').on('click', function() { 
            if ($('.view-more-images').html() == '<i class="fa fa-plus" aria-hidden="true"></i> VIEW MORE IMAGES <i class="fa fa-plus" aria-hidden="true"></i>') {
                $('.view-more-images').html('- VIEW LESS IMAGES -');
            } else {
                $('.view-more-images').html('<i class="fa fa-plus" aria-hidden="true"></i> VIEW MORE IMAGES <i class="fa fa-plus" aria-hidden="true"></i>');
            }   
        });
    
        $('.read-more').on('click', function() { 
            $('.view-more-toggle').css({ 'display': 'block' });
        });
    });
    </script>


Solution

  • I would instead use a relative children selector and toggle combined with having one hidden by default. I added some CSS to make your cursor a pointer and prevent the user from accidenly selecting text when spam clicking.

    $( document ).ready(function() {
        $('.read-more').on('click', function() {
            $(this).children().toggle();
        });
    });
    .read-more {
      cursor:pointer;
      -webkit-user-select: none; /* webkit (safari, chrome) browsers */
      -moz-user-select: none; /* mozilla browsers */
      -khtml-user-select: none; /* webkit (konqueror) browsers */
      -ms-user-select: none; /* IE10+ */
    }
    <link rel="stylesheet" href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" integrity="sha384-dNpIIXE8U05kAbPhy3G1cz+yZmTzA6CY8Vg/u2L9xRnHjJiAK76m2BIEaSEV+/aU" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a class="read-more" id="read-more">
        <span class="view-more-images" id="view-more-images"><i class="fa fa-plus" aria-hidden="true"></i> VIEW MORE IMAGES <i class="fa fa-plus" aria-hidden="true"></i></span>
        <span class="view-more-images" style="display:none" id="view-less-images"><i class="fa fa-minus" aria-hidden="true"></i> VIEW LESS IMAGES <i class="fa fa-minus" aria-hidden="true"></i></span>
    </a>