Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within <div> scroll to the first occurrence of a given string

In my div tag, there are many lines of really long text and the div element is currently scrollable. What I'd like to do is find the first occurrence of a particular string and automatically scroll to the line that contains that string. There is no line breaks or any kind of string delimiters I could use to readily approximate the scroll position.

I suppose I could do something like this:

var max_chars_per_line = approximated max # of chars that can fit into one line;
var font_height = approximated font height in px;
var needle = string to look for;
var haystack = content in the <div> tag;
var index = haystack.indexOf(needle);
var num_lines_to_skip = index / max_chars_per_line;
my_div_tag.scrollTo(num_lines_to_skip * font_height);

I can't help but wonder if there's a better (javascript/jQuery) solution out there. My own due diligence didn't find any.

like image 588
Edenbauer Avatar asked Jan 16 '26 20:01

Edenbauer


2 Answers

<p id="text">Lorem ipsum ... lots of text.... onion</p>

jQ:

var needle = 'onion';
$('#text').html($('#text').html().replace(needle, '<a id="imhere"></a>'+needle));
$('html,body').animate({scrollTop: $('#imhere').offset().top​}, 500);​​​​​​​​​​​​

Demo http://jsfiddle.net/vq7LD/

like image 122
Popnoodles Avatar answered Jan 19 '26 10:01

Popnoodles


If its the case that all of your text is in a single div, something like this solution works.

var goto = function(str){

    var content = $('#content').html();
    $('#content').html( content.replace(str,'<a name="goto">'+str+'</a>') );
    window.location = '#goto';
}

goto('Whatever your string is here');

http://jsfiddle.net/NmhHH/

like image 28
Geuis Avatar answered Jan 19 '26 08:01

Geuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!