The compatibility issue between Jquery highlight and show more/less function is causing them to malfunction when used

I am facing an issue where, while trying to search for a specific word to highlight it, the "show more" button closes and only displays the text prior to clicking the button. How can I ensure that the expanded content remains open while searching for a word?

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script src="../bootstrap/test.js"></script>
  <link rel="stylesheet" href="test.css">
</head>
<body>
<div class="row">
    <input class="text_search" id=x placeholder="text">
    <div id=text_x>
        <div class="col-sm-4">
            <p class="content">
            Several Australian home owners have been utilizing the services of mortgage brokers to fulfill their dreams of owning a house at an affordable rate.
            </p>
            <p class="more-cont" style="display:none;">
            Whether you are aspiring to buy a new house or considering upgrading your existing home loan,
            Mortgage broking involves the act of intermediating between the borrower and the lender on the borrower’s behalf. The role of a mortgage broker starts right from the time when you plan to...
            </p>
            <a class="Show_more_less">Show more</a> 
        </div>
        ...
    </div>
</div>
</body>
</html>

This is my jQuery code:

$(document).ready(function(){
    $('.Show_more_less').click(function(e) {
        e.preventDefault();
        $(this).text(function(i, t) {
          return t == 'Show less' ? 'Show more' : 'Show less';
        }).prev('.more-cont').slideToggle()
    });
});

$(function() {

    $(".text_search").each(function() {

        var textModal = $('#text_' + this.id),html = textModal.html();

        $(this).on("keyup", function() {

            var reg = new RegExp($(this).val() || "&s;fakeEntity;", 'gi');

            textModal.html(html.replace(reg, function(str, index) {

                var t = html.slice(0, index+1),
                    lastLt = t.lastIndexOf('<'),
                    lastGt = t.lastIndexOf('>'),
                    lastAmp = t.lastIndexOf('&'),
                    lastSemi = t.lastIndexOf(';');

                if(lastLt > lastGt) return str;
                if(lastAmp > lastSemi) return str;
                return '<span class='highlight'>' + str + '</span>';
            }));
        });
    }); 
});

And here is my CSS code:

html, body {
    margin: 0px;
    width: 100vw;
    height: 100%;
    overflow-x: hidden;
    font-family: Helvetica;
    background-color: rgb(241, 238, 238);
}
.Show_more_less{
    cursor: pointer;
}
.highlight {
    background-color: yellow;
    font-weight: bold;
}
.text_search{
    margin-left: 2em;
}

Answer №1

When working with HTML replacements during a search, it is necessary to rebind after performing the search and replacement or highlighting.

One approach to try is:

function bindShowMoreLess(){
    $('.Show_more_less').click(function(e) {
        e.preventDefault();
        $(this).text(function(i, t) {
          return t == 'Show less' ? 'Show more' : 'Show less';
        }).prev('.more-cont').slideToggle()
    });

}

$(document).ready(bindShowMoreLess);

$(function() {

    $(".text_search").each(function() {

        var textModal = $('#text_' + this.id),html = textModal.html();

        $(this).on("keyup", function() {

            var reg = new RegExp($(this).val() || "&fakeEntity;", 'gi');

            textModal.html(html.replace(reg, function(str, index) {

                var t = html.slice(0, index+1),
                    lastLt = t.lastIndexOf("<"),
                    lastGt = t.lastIndexOf(">"),
                    lastAmp = t.lastIndexOf("&"),
                    lastSemi = t.lastIndexOf(";");

                if(lastLt > lastGt) return str;
                if(lastAmp > lastSemi) return str;
                return "<span class='highlight'>" + str + "</span>";
            }));
            
            bindShowMoreLess();
        });
    }); 
});

Link to a functional fiddle: https://jsfiddle.net/wvbcxj50/

Answer №2

To keep track of the state of elements and their IDs during a key-up event, you can implement the following code:

    var more = "";

    $(this).on("keyup", function() {

var state = document.getElementsByClassName("more-cont");
$( state ).each(function( index ) {
if(this.style.display === ""){
    more = more.concat(this.id+",");
  }
});

To revert back to the original state, use this code:

var res = more.split(",");
      for (var i = 0, len = res.length; i < len; i++) {
        [].forEach.call(res, function(el) {
        if (el !==""){
          document.getElementById(el).style.display = "";
          }
        });

Here is a working solution:

function bindShowMoreLess(){
$(document).ready(function() {
  $('.Show_more_less').click(function(e) {
    e.preventDefault();
    $(this).text(function(i, t) {
      return t == 'Show less' ? 'Show more' : 'Show less';
    }).prev('.more-cont').slideToggle()
  });
});
}

$(document).ready(bindShowMoreLess);


$(function() {

  $(".text_search").each(function() {

    var textModal = $('#text_' + this.id),
      html = textModal.html();

    var more = [];

    $(this).on("keyup", function() {

var state = document.getElementsByClassName("more-cont");
$( state ).each(function( index ) {
if(this.style.display === ""){
    more.push(this.id); 
    return more;
  }
});



      var reg = new RegExp($(this).val() || "&fakeEntity;", 'gi');

      textModal.html(html.replace(reg, function(str, index) {

        var t = html.slice(0, index + 1),
          lastLt = t.lastIndexOf("<"),
          lastGt = t.lastIndexOf(">"),
          lastAmp = t.lastIndexOf("&"),
          lastSemi = t.lastIndexOf(";");

        if (lastLt > lastGt) return str;
        if (lastAmp > lastSemi) return str;
        return "<span class='highlight'>" + str + "</span>";

      }));
      
bindShowMoreLess();

      for (var i = 0, len = more.length; i < len; i++) {
        [].forEach.call(more, function(el) {
        if (el !==""){
          document.getElementById(el).style.display = "";                
          $("#"+el).next("a").text("Show less");
          }
        });
      };
    });
  });
});
html,
body {
  margin: 0px;
  width: 100vw;
  height: 100%;
  overflow-x: hidden;
  font-family: Helvetica;
  background-color: rgb(241, 238, 238);
}

.Show_more_less {
  cursor: pointer;
}

.highlight {
  background-color: yellow;
  font-weight: bold;
}

.text_search {
  margin-left: 2em;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script src="../bootstrap/test.js"></script>
  <link rel="stylesheet" href="test.css">
</head>

<body>
  <div class="row">
    <input class="text_search" id="x" placeholder="text">
    <div id=text_x>
      <div class="col-sm-4">
        <p class="content">
          Several Australian home owners have been utilizing the services of mortgage brokers to fulfill their dreams of owning a house at an affordable rate.
        </p>
        <p class="more-cont" id="more-cont1" style="display:none;">
          Whether you are aspiring to buy a new house or considering upgrading your existing home loa
          <br>Mortgage broking involves the act of intermediating between the borrower and the lender borrower’s behalf. The role of mortgage broker starts right from the time when you plan to
        </p>
        <a class="Show_more_less">Show more</a>
      </div>
      <div class="col-sm-4">
        <p class="content">
          Several Australian home owners have been utilizing the services of mortgage brokers to fulfill their dreams of owning a house at an affordable rate.
        </p>
        <p class="more-cont" id="more-cont2" style="display:none;">
          Whether you are aspiring to buy a new house or considering upgrading your existing home loa
          <br>Mortgage broking involves the act of intermediating between the borrower and the lender borrower’s behalf. The role of mortgage broker starts right from the time when you plan to
        </p>
        <a class="Show_more_less">Show more</a>
      </div>
      <div class="col-sm-4">
        <p class="content">
          Several Australian home owners have been utilizing the services of mortgage brokers to fulfill their dreams of owning a house at an affordable rate.
        </p>
        <p class="more-cont" id="more-cont3" style="display:none;">
          Whether you are aspiring to buy a new house or considering upgrading your existing home loa
          <br>Mortgage broking involves the act of intermediating between the borrower and the lender borrower’s behalf. The role of mortgage broker starts right from the time when you plan to
        </p>
        <a class="Show_more_less">Show more</a>
      </div>
    </div>
  </div>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for exporting JSON-LD and embedding it into an HTML document

Can JSON-LD be stored externally and then linked to an HTML document like so? <script type="text/javascript" src="http://www.example.com/data123.jsonld"></script> I haven't been able to find any information about this online.... ...

Center-aligned Bootstrap responsive column with a fixed width

Currently, I am working on creating a login page with a fixed width and a centered column layout. This is similar to the design of the login page at https://www.amazon.com/sign-in. I attempted to achieve this layout using offset columns, as shown below: ...

Utilize the CSS property font-family to inherit styles for headings

Is it possible to use a different font family for headings than the one used in the body text while still maintaining a consistent look across all heading levels? One way to achieve this is by specifying the font family for each heading level individually ...

Looking for a way to limit the number of characters allowed per line in a textarea using jQuery

I have the following HTML textarea: <textarea name="splitRepComments" cols="20" rows="3" ></textarea> I have implemented a maxlength restriction using jQuery with the following function: var max = 100; $('#splitRepComments').bind(" ...

What could be the reason why my POST endpoint isn't able to receive this AJAX request?

I am currently working on a JavaScript function that is supposed to send JSON data to my escreve POST REST method. $(document).ready(function() { $("#idform").on('submit', function(e) { e.preventDefault(); alert($("#idform"). ...

Troubleshooting: Navbar Hover Effect in Tailwind CSS Not Functioning as Expected

This week, I've been working on building a navbar and it seems like the layout is coming together nicely. However, I've encountered a couple of small issues with the hover effect and the links for the menu items on the left and the logo in the ce ...

Azure API Management encountering Cross-Origin Resource Sharing (CORS) problem

Utilizing Azure API management to interact with my Python Flask web service has been efficient for GET operations. However, encountering an issue when attempting POST requests using jQuery AJAX calls where the request is converted to OPTIONS resulting in t ...

Require modifying the radio button's value based on the presence of a certain class in an input field

Feeling overwhelmed. I am currently working on implementing a credit card auto system using the Stripe Payment plugin, but I find myself at a loss. Specifically, when a MasterCard is entered in the card number input field, it should receive the "masterca ...

Guide on fetching and parsing JSON data in jQuery by utilizing a URL

As a newcomer to jquery, I am struggling to understand and parse the json format. In my icenium project, I have included this JavaScript function in my js folder but it doesn't seem to be functioning properly. $(document).ready(function () { ...

What measures are in place to prevent content from being copied on this website?

I'm facing an issue with my website where users are unable to select and copy text using their mouse. The site is hand-coded in PHP and I've tested it on multiple browsers, but the problem persists. I understand that some people may want to preve ...

The JQuery app dynamically adds a new input row each time the current input row is filled, repeating this process N

I am looking to dynamically add rows to a table with 3 input fields each. After filling out all the inputs in one row, I want to append a new row with identical input fields. <table> <thead> <tr> <th>H</th> ...

The <select> list appears wider on Windows compared to Mac

Is there a way to achieve consistent width for a wide select list on different operating systems and browsers? I've noticed that the width of the select box varies between Windows and Mac OS when viewed in Chrome or other browsers. For example, if yo ...

Using Angular to scroll within a <div> that is obstructed by other <div>s and concealed by

I am currently in the process of developing a website using Angular. I have implemented a card feature that allows for text selection from a menu on the left side. The texts are displayed using the *ngIf directive. However, I encountered an issue where if ...

Exploring Vue.js: Leveraging v-bind for multiple classes in Vue.js applications

Can someone assist me in figuring out how to apply multiple options to v-bind:class? In my Uno game, I need to determine the text color of cards based on their color property stored as a list of objects like this: ([{ Color: green, Value: 6}]. Here is my ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

PHP/HTML failing to upload extra large files

Allowing users to upload large files is causing an issue for me. I tested uploading a 22 MB file and it was successful. However, when I tried uploading a 200 MB file, it seems that the file does not enter the if block and instead returns the output from th ...

Pedestrian crossing Cordova experiences delayed response despite ontouchstart attempts to fix it

I have been experiencing a delay issue when using a CSS button with the ":active" pseudo-class on my phone. Every time I click the buttons, there is a noticeable delay before entering the active phase. Here is my CSS code: .btn {...} .btn:active{...} To ...

Confirmation message for deletion using jQuery on dynamic elements

My div is populated with dynamically added records. Whenever I click on the 'Remove' link, a confirmation box pops up multiple times corresponding to the number of records present in the div. I want the confirmation box to appear only for the spe ...

Stacking issue - elements not properly aligned

Is there a way to move my H1 text below the blue category button instead of beside it? Thank you in advance! http://jsfiddle.net/TDBzN/ <div id="article" class="animated2 fadeInLeftBig"> <div class="article-close"></div> <div c ...

Is there a faster method to execute this basic jQuery statement?

Is there a way to make the script 'refresh' itself after using .slideToggle with just 3 lines of code? I want it to return to its original state when slid back up, but that doesn't happen when I use 3 lines and .slideToggle. Apologies for th ...