What could be causing my jQuery search feature to only function properly one time?

This is a code snippet that can search for, scroll to, and highlight a specific piece of text on a webpage.

For the code demo, you can check it out on jsFiddle: http://jsfiddle.net/z7fjW/137/

However, there seems to be an issue with the functionality. After the first search and highlight, the code does not work for subsequent searches. It appears that the previously highlighted search results are not being removed properly. The following code snippet may be responsible for this:

$('.highlighted').removeClass('highlighted');
$(selector).html($(selector).html()
    .replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));

I'm currently unsure of what is causing this problem, so any help or insights would be greatly appreciated.

Thank you.

Answer №1

Check it out here: http://jsfiddle.net/z7fjW/682/

This situation is really strange to me, I can't quite wrap my head around it. I did manage to come up with a workaround using delegated events, but I'm determined to keep digging until I uncover why the event is only triggering once.

$('body').on('click','#search-button',function() {
        if(!searchAndHighlight($('#search-term').val())) {
            alert("No results found");
        }
    });

UPDATE: Ah-ha!! Once I finally cracked the code, it all makes sense. Look at this snippet

$(selector).html($(selector).html()
                    .replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));

The selector is targeting the body. By calling html() on the entire body, you essentially replace the existing html with the same content plus the span tags. The click listener was attached to the #search-button, but gets overwritten because of the full html replacement. The tricky part for me was that the html appeared identical in the Chrome inspector, making it tough to realize the listener was no longer active.

This is why my workaround functioned, since event delegation attaches the listener to the body, which then looks for #search-button upon a click.

My suggestion is to avoid completely rewriting the body's html.. it just leads to headaches like this. Consider using this approach instead,

var selector = selector || "#bodyContainer";   

This way, you only replace the content within #bodyContainer, rather than the entire body html. This also allows you to keep your original event listener in place.

Helpful Resources: http://api.jquery.com/html/#html2

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

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

My HTML document is not displaying the JavaScript variable as expected

I have created a JavaScript function with several variables and attempted to test it to display the variables in my HTML document. However, I am facing an issue where the variables do not appear as expected. Specifically, I am trying to insert the variable ...

Managing extensive amounts of data with server-side scripting in a Datatable

I am exploring the use of the datatable plugin to effectively manage a large amount of data. Currently, I am interested in implementing "server side processing in datatables" with the help of server-side scripting. Since I have limited experience with AJA ...

Having trouble getting the Bootstrap 5 Modal to function properly within an Electron app

Facing an issue with my web app using Bootstrap 5, as the modal is not displaying properly. Below is the HTML code for the modal and the button that triggers it: <div class="modal" tabindex="-1" id=&quo ...

What is the best way to horizontally align text in a container without it remaining at the top?

My attempts to center the button using vertical-align: middle and text-align: center have been unsuccessful, as the styling does not affect the button's position and it remains at the top. I am puzzled by why the style is not being applied. While I c ...

Suggestions to reduce our website loading time

Query: How can one effectively reduce the file size of a webpage to improve loading speed? What specific optimization practices and coding techniques (in JavaScript and PHP) can be implemented to decrease page weight? Motivation: After reading an article ...

Obtain the href attribute's value from an HTML document using Javascript

I'm facing an issue here. Currently, I am utilizing Grid.js (http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/) for my project. Now, my goal is to incorporate a Lightbox with multiple thumbnails inside the dropout provide ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

What is the best way to eliminate the extra space above a span when the parent element's font size is very large?

Dealing with a situation where the parent DOM-element has a large em-value which results in all inline child elements having a significant margin above them despite their smaller font-size: Here is the source (http://jsfiddle.net/rapik/w87m7/2/): <div ...

Tools for generating Xpath or CSS selectors on Firefox and Chrome browsers

Struggling with finding helpful plugins for my Selenium webdriver development. Firebug for FF and Selenium IDE are not working for me. Despite trying multiple plugins for both FF & Chrome, I can't find anything to generate xpath or CSS strings. Lookin ...

Tips for changing the background color depending on the value

I am creating a table displaying the results of a tournament. Each team's final placement and original seeding will be listed. I plan to include a small bubble next to each team showing how their final placement compares to their initial seeding. To v ...

Using the setInterval function in conjunction with the remoteCommand to create a

I am attempting to create a remote command that calls a bean function and updates a progress bar every 2 seconds until cancelled. The remote command looks like this: <p:remoteCommand id="usedCall" name="queryUsed" onco ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

Issue encountered during an asynchronous call to an ASP.NET web method using $Ajax

Currently, I am dealing with an async web method (asmx file) and I am trying to call this method within an ajax jquery method. However, I am encountering numerous issues because the method also utilizes Entity Framework for various functionalities. Below ...

jquery refreshing tool

Hey there, I've got this script http://jsbin.com/ajaneh that uses Ajax when performing actions. $.ajax({ type: "POST", url: domain+"/home/register_working_time/", dataType: 'json', data: d ...

Aligning the Navigation icons on my webpage

<nav> <ul> <li><a href="index.php">Home</a></li> <li><a href="index.php?about">About</a></li> <li><a href="index.php?products">Products</ ...

Javascript Select Element with No Options

I'm currently working on a <select> element that is being populated from an array using the following code snippet: <select id="selector" name="selector"</select> <button type=button onclick=populateSelect(states)>Click me1!</ ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Incorporating AngularJS into your current JavaScript code base

We have a JavaScipt project underway that could greatly benefit from incorporating AngularJS. However, due to the size of the project, completely rewriting it in Angular is not feasible. Does anyone have any suggestions or tips on how to integrate Angula ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

The information from the textarea and select option is not getting through to the email

Despite following suggestions, I am still unable to figure out why my form is not functioning properly. The form I have collects various information such as name, email, phone number, a select option, and a message in a textarea input. I dynamically change ...