JavaScript: Retrieve the Vertical Position of a Text Within a Division

Simply put, I am looking to implement a basic search feature within my HTML div. Each potential search tag is enclosed by $ and every tag is unique.

My objective is to develop a function that takes a tag, scans the div, and identifies the line (Y position) of that tag within the div.

The main challenge lies in determining the position of a string within the text. I can verify if the string exists, but establishing its precise location in the div poses a difficulty.

(In this case, it would be denoted by getLineWhereTagIsFound(tag)).

Note: One approach could involve counting the occurrences of <br> elements until locating the tag, though its reliability remains uncertain.

This is the current progress that has been made.

<div id="helpText" class='onlyTextScroll container'>        
    $Fruits$<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    Fruits are very nice.<br>
    <br>
    $Vegetables$<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    Vegetables are very evil.<br>
    <br>
</div>


<script>
function updateHelp(tag){
var y = getLineWhereTagIsFound('$' + tag + '$');
y *= lineHeight;
$("#helpText").scrollTop(y);

}
/* Example
function updateHelp('Vegetables'){
var y = getLineWhereTagIsFound('$' + 'Vegetables' + '$');
//y would be 10 because $Vegetables$ is found on line 10; 
//let say lineHeight is 10;     
y = y*lineHeight; //10*10

$("#helpText").scrollTop(100);

}
*/
</script>

Answer №1

function findLineNumberWithTag(tag){
    var helpText = document.getElementById("helpText");
    var lineCount = 0;
    for(var i=0;i<helpText.childNodes.length;i++){
        if(helpText.childNodes[i].nodeType==3){
            lineCount++;
            if(helpText.childNodes[i].nodeValue.indexOf(tag)>=0){
                break;
            }
        }
    }
    return lineCount;
    //lineCount would be 11, not 10, since $Vegetables$ is found on line 11
    //each <br/> represents one line
}

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

Preventing a user with the same name as the one in the table from being added by utilizing a jQuery contains check proved

Check out my fiddle here: http://jsfiddle.net/jd5pgdz2/4/ I encountered an issue when attempting to add a user with the same name as one already in my table (the displayed users are static in the HTML). Despite using 'contains' to check if the u ...

Utilize fixed values in type declaration

Strange Behavior of Typescript: export type MyType = 0 | 1 | 2; The above code snippet functions correctly. However, the following code snippet encounters an issue: export const ONE = 1; export const TWO = 2; export const THREE = 3; export type MyType = O ...

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

Troubleshooting Cross-Origin Resource Sharing Errors in JavaScript's XMLHttpRequest()

When making a preflight request, ensure that the 'Access-Control-Allow-Origin' header in the response does not use '*' as the value when the request's credentials mode is set to 'include'. This will prevent Origin '& ...

The command 'source-highlight' is not a recognized internal or external command

Recently, I delved into the world of asciidoc and decided to create an example in Python. However, every time I attempt to display a code blog in HTML, I encounter an exception that says 'source-highlight' is not recognized as an internal or exte ...

The onclick event in JavaScript is unresponsive on mobile devices

Our website is powered by Opencart 1.5.6.4 and the code snippet below is used to add items to the shopping cart. <input type="button" value="<?php echo $button_cart; ?>" onclick="addToCart('<?php echo $product['product_id']; ?&g ...

Issue with React tabulator ref being null after re-rendering

Utilizing Tabulator within React by employing the react-tabulator module has been a part of my development process. Now, I rely on 'ref' for the table component to execute actions such as downloading data or any other relevant activity. import R ...

Delete all event handlers associated with an element, leaving only one remaining

Is it possible to remove all events from a DOM element except for one using jQuery? Let's say I have a drop down <select> with multiple events attached to it, such as click, double click, and change. How can I specifically target and keep only ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

How can I retrieve the index of a v-for loop within a function in Vue.js HTML?

How can I splice the array from the fields in HTML Vue JS if the status is true? I also need to pass the index value to a function. Is this possible? The error I am encountering is: Uncaught ReferenceError: index is not defined at Object.success (80 ...

Utilizing the Bootstrap 4 jumbotron classes to create an interactive image carousel

I've made good progress on my mockup website by laying out the basics. #hero { background: url("https://picsum.photos/1280/710") no-repeat center; background-size: cover; } .book { height: 100px; width: 100px; bottom: 9vh; } &l ...

The second Ajax request recreates the HTML content, resulting in duplication

I am trying to implement an AJAX request that will prepend a specific html block when link 1 is clicked in my DOM: $("#link1").on("click", function(){ $.get("myBlock.html", function(data){ $(".wrapper").prepend(data); }); }); This html block, which co ...

A guide on defining the width of an element within a flex container when it overflows

Here is the code snippet I have: .divA { background: red; width: 500px; display: flex; flex-direction: row; overflow-y: scroll; } .epi { width: 50%; background: blue; } <div class="divA"> <div class="epi"> <h1>dsds ...

Tips for navigating through pagination indexes with Angular 6

Hey there, I'm currently working on a project where I need to automatically click through each pagination index. Initially, only the first index can be clicked. After that, the following page indexes are not clickable. Here's the code snippet: ...

Retrieve information from JSON dataset [object]

Click here for debugging screenshot $.ajax({ url: postUrl, type: 'GET', dataType: 'json', data: { "id": num }, contentType: "application/json; charset=utf-8", success: function (data) { $.each(data, ...

Obtain consistent outcomes by entering identical data in both Ajax and PHP

My code takes a number input in a <textarea>, then uses AJAX to validate it randomly with PHP (using rand()). The validated number is returned along with the words correct or incorrect to a <div> in HTML. The issue is that if the same number i ...

Send the response from Facebook to the flash callback on the external interface

I attempted to transfer the response from a Facebook API request obtained through the FB JS-SDK to my flash application using external interface. However, I am having trouble identifying the type of response as it displays [object object] when printed in t ...

Creating a CSS triangle that expands the full width of the page

Here is a triangle: #header-triangle-right { position: absolute; float: right; top:0px; right:0; z-index: 0; overflow: hidden; width: 0; height: 0; border-top: 400px solid transparent; border-right: 1000px solid #00 ...

The CSS elements are positioned beneath the top border when applying a scale transformation within columns

I have a layout with 4 columns of images that I want to scale on mouse hover using the 'column-count' property. The first column works correctly, but the next three end up positioned under the upper border during the transformation. I've e ...