1

I have this string like:

Life is a characteristic distinguishing physical entities having signaling and self-sustaining processes from those that do not,[1][2] either because such functions have ceased (death), or because they lack such functions and are classified as inanimate.[3][4][5] Biology is a science concerned with the study of life.

The smallest contiguous unit of life is called an organism. Organisms are composed of one, or more, cells, undergo metabolism, maintain homeostasis, can grow, respond XXXXXX to stimuli, reproduce and, through evolution, adapt to their environment in successive generations.[1] A diverse array of living organisms can be found in the biosphere of Earth, and the properties common to these organisms—plants, animals, fungi, protists, archaea, and bacteria—are a carbon- and water-based cellular form with complex organization and heritable genetic information.

The Earth was formed about 4.54 billion years ago. The earliest life on Earth existed at least 3.5 billion years ago,[6][7][8] during the Eoarchean Era when sufficient crust had solidified following the molten Hadean Eon. The earliest physical evidence for life on Earth is biogenic graphite in 3.7 billion-year-old metasedimentary rocks discovered in Western Greenland[9] and microbial mat fossils found in 3.48 billion-year-old sandstone discovered in Western Australia.[10][11] Nevertheless, several studies suggest that life on Earth may have XXXXXXXXX started even earlier,[12] as early as 4.25 billion years ago according to one study,[13] and even earlier yet, 4.4 billion years ago, according to another study.[14] The mechanism by which life began on Earth is unknown, although many hypotheses have been formulated. Since emerging, life has evolved into a variety of forms, which biologists have classified into a hierarchy of taxa. Life can survive and thrive in a wide range of conditions.

Though life is confirmed only on the Earth, many think that extraterrestrial life is not only plausible, but probable or inevitable.[15][16] Other planets and moons in the Solar System have been examined for evidence of having once supported simple life, and projects such as SETI have attempted to detect radio transmissions from possible alien civilizations. According to the panspermia hypothesis, XXXXXXXXXXmicroscopic life exists throughout the Universe, and is distributed by meteoroids, asteroids and planetoids.[17]

The meaning of life—its significance, origin, purpose, and ultimate fate—is a central concept and question in philosophy and religion. Both philosophy and religion have offered interpretations as to how life relates to existence and consciousness, and on related issues such as life stance, purpose, conception of a god or gods, a soul or an afterlife. Different XXXXXXXXXXXXXcultures throughout history have had widely varying approaches to these issues.

I have the following elements:

<input type="button" value="Prev" id="P" name="P">
<input type="button" value="Next" id="N" name="N">

and a Textarea

<textarea id="enterAnyText"></textarea>

When the user clicks on that input #P, the page should scroll to the previous XXXXXXXXX or whatever text they(the user) inserted in the textarea, with a nice animation.

When the user clicks on that input #N, the page should scroll to the next XXXXXXXXXor whatever text they(the user) inserted in the textarea, with a nice animation.

The animation should not be too much fast and should be fluid.

I am running the latest jQuery version and there is no database.

The text is randomly generated from different story books... so XXXXXXX might signify any word, string or text they want to search inside the randomly generated looong text from a story book.

PLEASE NOTE: The story books are save in .html files i.e story1.html, story2.html.... They are loaded inside divs using jQuery.load()

EDIT2: We tried to use i.e. jQuery("p:contains(txt)") but that scrolls to the parent p tag not the text or word itself

a paragraph like:

The Earth was formed about 4.54 billion years ago. The earliest life on Earth existed at least 3.5 billion years ago,[6][7][8] during the Eoarchean Era when sufficient crust had solidified following the molten Hadean Eon. The earliest physical evidence for life on Earth is biogenic graphite in 3.7 billion-year-old metasedimentary rocks discovered in Western Greenland[9] and microbial mat fossils found in 3.48 billion-year-old sandstone discovered in Western Australia.[10][11] Nevertheless, several studies suggest that life on Earth may have a paragraph like: The Earth was formed about 4.54 billion years ago. The earliest life on Earth existed at least 3.5 billion years ago,[6][7][8] during the Eoarchean Era when sufficient crust had solidified following the molten Hadean Eon. The earliest physical evidence for life on Earth is biogenic graphite in 3.7 billion-year-old metasedimentary rocks discovered in Western Greenland[9] and microbial mat fossils found in 3.48 billion-year-old sandstone discovered in Western Australia.[10][11] Nevertheless, several studies suggest that life on Earth may have a paragraph like: The Earth was formed about 4.54 billion years ago. The earliest life on Earth existed at least 3.5 billion years ago,[6][7][8] during the Eoarchean Era when sufficient crust had solidified following the molten Hadean Eon. The earliest physical evidence for life on Earth is biogenic graphite in 3.7 billion-year-old metasedimentary rocks discovered in Western Greenland[9] and microbial mat fossils found in 3.48 billion-year-old sandstone discovered in Western Australia.[10][11] Nevertheless, several studies suggest that life on Earth may have XXXXXXXXX

will scroll to the p but not the XXXXXXXXXXX

Any suggestion is highly praised.

Universal Grasp
  • 1,835
  • 3
  • 20
  • 29
  • if jQuery("p:contains(txt)") works for you, then you can put the user entered text inside a span. So you'll easily get the offset of each span contains the user entered text. – Vilas Kumkar Oct 29 '14 at 14:25

2 Answers2

3

You could potentially do it this way.

HTML

<p>Here is a paragraph</p>
</p>Here is another paragraph</p>

<input type="button" value="previous" id="previous" />
<input type="text" placeholder="enter a searchstring" />
<input type="button" value="next" id="next" />

Keep in mind that this HTML won't actually scroll as its probably a lot shorter than your screen. Instead of scrolling, add a console log in the code below to see that it is pointing to right position from the top.

jQuery

// the following function will search for all 'tags' containing 'value' in DOM order
var working = false;
function searchWordsReturnOffsets(value, tags){
    // this will prevent the function from executing while its still in an execution cycle.
    if(working) return;
    else working = true;
    var all = [];
    $(tags).each(function(){
        if($(this).text().indexOf(value) >= 0){
            // temporarily wrap them in a findable object we can locate
            $(this).html($(this).html().replace(value,"<span class='searchvalue'>" + value + "</span>"));
            // lets do another foreach to find every instances' offset
            $(this).find("span.searchvalue").each(function(){
                all.push($(this).offset().top);
            });
            // remove the findable objects again
            $(this).html($(this).html().replace("<span class='searchvalue'>" + value + "</span>",value));
        }
    });
    return all;
}
$(document).ready(function(){
    var current = 0;
    var positions = [];
    $("#search").on("keyup", function(){
        // here we will keep track of the paragraphs and reset to the first
        positions = searchWordsReturnOffsets($(this).val(), "p");
        current = 0;
        $("body,html").animate({scrollTop : positions[current]});
    });
    $("#next").click(function(){
        if(positions[current + 1] != undefined){
            current++;
            $("body,html").animate({scrollTop : positions[current]});
        }
    });
    $("#previous").click(function(){
        if(positions[current - 1] != undefined){
            current--;
            $("body,html").animate({scrollTop : positions[current]});
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var working = false;
function searchWordsReturnOffsets(value, tags){
    if(working) return;
    else working = true;
 var all = [];
 $(tags).each(function(){
  if($(this).text().indexOf(value) >= 0){
   $(this).html($(this).html().replace(value,"<span class='searchvalue'>" + value + "</span>"));
    $(this).find("span.searchvalue").each(function(){
           all.push($(this).offset().top);
       });
   $(this).html($(this).html().replace("<span class='searchvalue'>" + value + "</span>",value));
  }
 });
    working = false;
 return all;
}

$(document).ready(function(){
 var current = 0;
 var positions = [];
    $("#search").on("keyup", function(){
     positions = searchWordsReturnOffsets($(this).val(), "p");
     current = 0;
        if(positions[current] != undefined){
          console.log(positions[current]);
        }
    });
    $("#next").click(function(){
     if(positions[current + 1] != undefined){
      current++;
            console.log(positions[current]);
     }
    });
    $("#previous").click(function(){
     if(positions[current - 1] != undefined){
      current--;
            console.log(positions[current]);
     }
    });
})
</script>

<p>Here is a paragraph</p>
<p>Here is another paragraph<br/>With a second line to see we get three results when searching 'ere'.</p>

<input type="button" value="previous" id="previous" />
<input type="text" placeholder="enter a searchstring" id="search" />
<input type="button" value="next" id="next" />
somethinghere
  • 16,311
  • 2
  • 28
  • 42
  • Please I beg for a Fiddle.... looks great though... Please Fiddle it up!!!... Thank you – Universal Grasp Oct 29 '14 at 14:05
  • I get error: `TypeError: $(...).find(...).offset(...) is undefined` and add the `id="search"` to the `textarea` – Universal Grasp Oct 29 '14 at 14:12
  • The code won't work: `$().text(......)` will escape the HTML code. For solutions, see here: http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript – Aaron Digulla Oct 29 '14 at 14:14
  • @AaronDigulla I know, I used jQuery `.text()` and I should us `.html()`. I have amended the function so it now temporarily wraps your results in span tags and adds the offsets of those to the array. I have not thought about having multiple tags in the same paragraph yet, but that can be amended by adding a `foreach` '.searchvalue' and adding those offsets of the top. – somethinghere Oct 29 '14 at 14:14
  • Idea for an improvement: Assign IDs to the `span`, then you can scroll to them using the ID (i.e. leave the span in the text). If you assign a class to all of them, you can easily remove them when you search again. – Aaron Digulla Oct 29 '14 at 14:16
  • @AaronDigulla the problem with that is that you will get a whole bunch IDs that never get cleaned up. By using a class you can find the word, find the offset of a newly wrapped element, remove the element and save the offset. This makes sure you don't get overly jumbled code. I also think the indexOf won't work otherwise... – somethinghere Oct 29 '14 at 14:17
  • I used this Text... http://pastebin.com/RPambNY6 it simply logs certain numbers and does nothing else... please HELP – Universal Grasp Oct 29 '14 at 14:21
  • @somethinghere: Don't the IDs die with the `` when I remove them? – Aaron Digulla Oct 29 '14 at 14:22
  • @somethinghere is there a way to have the m`acthed` Highlighted using your CODES if `scrolling` will be kinda Heard...??.... Please Help!! – Universal Grasp Oct 29 '14 at 14:25
  • @UniversalGrasp Scrolling: the values that are being reported are the offsets from the top of every match. Use something like `$("body,html").animate({scrollTop: [VALUE] + "px"});` to make it scroll. You could potentially keep the span tags, but removing the spans and replacing them by their original text again is a bit more complicated of a process. – somethinghere Oct 29 '14 at 14:37
0

You can use :contains() to find specific text:

var target  = $( "div:contains('text to search for')" );

Then find the offset of target and scroll to it.

Caution, :contains finds all instances of the text in the page so which one you scroll to might be interesting.

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Pat Dobson
  • 3,249
  • 2
  • 19
  • 32