Featured post
javascript - Select first word of every line (CSS/JS/Whatever) -
i'm trying select each first word, wrap in specific span.
lorem ipsum dolor sit amet, consectetur adipiscing elit. cras sagittis nunc non nisi venenatis auctor. aliquam consectetur pretium sapien, eget congue purus egestas nec. maecenas sed purus ut turpis varius dictum. praesent nunc ipsum, id mattis odio. donec rhoncus posuere bibendum. fusce nulla elit, laoreet non posuere.
if text, script should select lorem, aliquam, varius , elit
thanks in advance
you can this, using javascript wrap every word in paragraph in own span, , walking through spans finding out actual position on page is, , applying style changes spans y position greater preceding span. (best beginning-to-end, though, earlier ones may affect wrapping of latter ones.) it's going lot of work browser, , you'll have repeat each time window resized, effect have worth cost.
something (used jquery you've listed jquery
tag on question , makes code lot simpler):
jquery(function($) { var lasty; var $target = $('#target'); $target.html( "<span>" + $target.text().split(/\s/).join("</span> <span>") + "</span>"); lasty = -1; $target.find('span').each(function() { var $this = $(this), top = $this.position().top; if (top > lasty) { $this.css("fontweight", "bold"); lasty = top; } }); });
naturally that's making huge set of assumptions (that whitespace should replaced single space, there's no markup in text, others). idea.
here's version handles window resize, 50ms after last resize event occurs (so we're not doing interim) , gaby's suggestion (below) unbold @ start of resize:
jquery(function($) { var resizetriggerhandle = 0; // on load boldfirstword('#target'); // 100ms after end of resize operation, // because it's *expensive* $(window).resize(function() { if (resizetriggerhandle != 0) { cleartimeout(resizetriggerhandle); } unboldfirstword('#target'); resizetriggerhandle = settimeout(function() { resizetriggerhandle = 0; boldfirstword('#target'); }, 50); }); function boldfirstword(selector) { var lasty; // break spans if not done; // if done, remove previous bold var $target = $(selector); if (!$target.data('spanned')) { $target.html( "<span>" + $target.text().split(/\s/).join("</span> <span>") + "</span>"); $target.data('spanned', true); } else { unboldfirstword($target); } // apply bold first span of each new line lasty = -1; $target.find('span').each(function() { var $this = $(this), top = $this.position().top; if (top > lasty) { $this.css("fontweight", "bold"); lasty = top; } }); $target.data('bolded', true); } function unboldfirstword(selector) { var $target = selector.jquery ? selector : $(selector); if ($target.data('spanned') && $target.data('bolded')) { $target.find('span').css("fontweight", "normal"); $target.data('bolded', false); } } });
- Get link
- X
- Other Apps
Comments
Post a Comment