Expanding a Read more / Read less jQuery script - javascript

I have this great script that uses jQuery to display a small portion of content & allow the user to read more/read less of the content.
Here is my current Fiddle: http://jsfiddle.net/Tqwdh/1/
Summary: When you click the image, it needs to reveal the additional text.
I would love to know how I can update this script to allow the user to click the associated image and it would display more of the text (as well as keeping the text link in place).
Can someone show me how I can achieve this?
Here is my example HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article><!-- #post-## -->
and my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
Thank you :-)

You could just add a click handler to img like this:
DEMO
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});​

You will need to move the logic from the toggle handler to your own implementation, as you have more than one event source.
<article id="post-5" >
<div class="more-less">
<div class="more-block">…</div>
</div>
<p>
…
</p>
</article>
$(function(){
var adjustheight = 130; // The height of the content block when it's not expanded
var texts = {
more: "Click to read more…",
less: "Click to read less…"
};
$("article").each(function() {
var block = $(".more-block", this).css({height:adjustheight, overflow:'hidden'}),
cont = $("p.continue", this),
toggle = $('<a href="#'+this.id+'" class="adjust">').text(texts.more),
open = false;
$(".more-less", this).append($('<p style="display:block;margin-top:8px">').append(link));
$("a.adjust", this).click(function() {
open = !open;
block.css("height", open ? "auto" : adjustheight);
link.text(texts[open ? "less" : "more"]);
cont[open ? "show" : "hide"]();
}
});
});

Simply add the same behaviour of the "Click to read more" element to the image elements.
When you set the toggle handlers like this:
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
Just use jQuery's multiple selector to select the image elements also, like in this example:
$(".adjust, #img1, #img2").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
Demo
Hope it helps.

var maxLength = 50;
$('.N_DESC').each( function (e) {
const thisVal = $(this).text();
const thisLength = $.trim(thisVal).length;
const noticeStr = thisVal.substring(0, maxLength);
const removedStr = thisVal.substring(maxLength, thisLength);
if(thisLength > maxLength){
$(this).empty().html(noticeStr);
$(this).append('<span class="more-text">'+ removedStr +'</span>');
$(this).append(`Read More..`);
}
});
$(document).on('click', '.read-more', function (e) {
$(this).closest('span').find('.more-text').show();
$(this).addClass('read-less');
$(this).removeClass('read-more');
$(this).html('Read Less..');
});
$(document).on('click', '.read-less', function (e) {
$(this).closest('span').find('.more-text').hide();
$(this).addClass('read-more');
$(this).removeClass('read-less');
$(this).html('Read More..');
});
.N_DESC .more-text{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor.</span>
<br>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim.</span>
<br>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero</span>

Related

How to call an ID specifically within the parent element and ignore all other elements with the same ID (using pure JS)?

I'm fairly new to JS. So, pardon me for asking such stupid question.
I want to implement a Read more/ less button based on this article.
This worked perfectly fine, because it had unique id. But when I implement this in a multiple read more blocks with same id, it triggers only the first element.
I have two div with id card1 and card2 under the parent div of class wrapper. I want to show clicked read more div (let say of card1) and hide the other div (card2) completely (and vice-versa).
Here's my code.
As you can see, it works perfectly fine for the first div (card1), but due to the contradiction of using same id, it doesn't work for other div.
It is possible, to call id specifically of parent div where the button is clicked and ignore the elements of other div with the same id. Is there any other simple way to solve my problem?
So far I don't know jQuery, so, solving the problem with pure JS will be very helpful.
Thank you.
function myFunction(t) {
var x = document.getElementById(t.id).parentNode;
var y = x.parentNode;
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
y.style.visibility = "visible";
} else {
y.style.visibility = "hidden";
x.style.visibility = "visible";
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
#more {
display: none;
}
<div class="wrapper">
<div id="card1">
<h2>Read More Read Less </h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" id="myBtn">Read more</button>
</div>
<div id="card2">
<h2>Read More Read Less 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" id="myBtn">Read more</button>
</div>
</div>
Several things
IDs need to be unique, use a class
It is not recommended to use inline event handlers - your code is a perfect target for delegation
So I
Created a hide class and added it to what needed to be hidden from start
TOGGLE the class
Change the text based on the presence of the hide class
document.getElementById("wrapper").addEventListener("click", function(e) {
const tgt = e.target.closest("button"); // in case you want something inside the button
if (tgt && tgt.classList.contains("readMoreBtn")) {
const parent = tgt.closest(".card");
const dots = parent.querySelector(".dots");
const moreText = parent.querySelector(".more");
dots.classList.toggle("hide")
moreText.classList.toggle("hide")
tgt.innerHTML = moreText.classList.contains("hide") ? "Read more" : "Read less";
}
})
body {
background: #111;
color: #eee;
}
.hide {
display: none;
}
<div id="wrapper">
<div class="card" id="card1">
<h2>Read More Read Less </h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more hide">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button type="button" class="readMoreBtn">Read more</button>
</div>
<div class="card" id="card2">
<h2>Read More Read Less 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more hide">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button type="button" class="readMoreBtn">Read more</button>
</div>
</div>

Sliding text from under image

I need to show txt nicely sliding from under image after click. When user will click on other image, previous text have to slide out (not be vissible).
I am not good in javascript at all. Now I have something like this:
.html
<img src="image.jpg" width="100%" height="100px;">
<div class="slidingDiv">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc venenatis auctor quam eget imperdiet. Vestibulum et nibh sit amet lectus mattis rutrum. Nam blandit vel massa eu laoreet. Etiam quam eros, iaculis in ornare viverra, gravida eu justo. Fusce nisi tortor, ornare et metus a, consequat sollicitudin mi. Nulla ipsum erat, ultricies semper ipsum sit amet, aliquet finibus ipsum. Fusce sodales lacus eget quam ullamcorper, mollis rhoncus lectus ullamcorper. Fusce tempor metus vel tincidunt condimentum. Fusce nunc risus, vehicula a cursus sit amet, vestibulum pretium felis. Praesent ex dolor, porta id sollicitudin non, venenatis ut ante. Maecenas porta velit augue, vel suscipit neque commodo et. Aenean ac dolor ac neque tristique porta. Ut neque diam, porta ut diam sit amet, vulputate auctor justo.</div>
</div>
<img src="image.jpg" width="100%" height="100px;">
<div class="slidingDiv">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc venenatis auctor quam eget imperdiet. Vestibulum et nibh sit amet lectus mattis rutrum. Nam blandit vel massa eu laoreet. Etiam quam eros, iaculis in ornare viverra, gravida eu justo. Fusce nisi tortor, ornare et metus a, consequat sollicitudin mi. Nulla ipsum erat, ultricies semper ipsum sit amet, aliquet finibus ipsum. Fusce sodales lacus eget quam ullamcorper, mollis rhoncus lectus ullamcorper. Fusce tempor metus vel tincidunt condimentum. Fusce nunc risus, vehicula a cursus sit amet, vestibulum pretium felis. Praesent ex dolor, porta id sollicitudin non, venenatis ut ante. Maecenas porta velit augue, vel suscipit neque commodo et. Aenean ac dolor ac neque tristique porta. Ut neque diam, porta ut diam sit amet, vulputate auctor justo.</div>
</div>
.js
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
var isvisible = $(this).next('.slidingDiv').is(':visible');
if ( isvisible ) {
$(this).next('.slidingDiv').hide();
} else{
$(this).next('.slidingDiv').show();
}
});
});
https://jsfiddle.net/Elfiszcze/49vd6d6k/2/
Could someone help me with this one?
When using jquery hide() and show() you can set the parameter duration that will be used in animation duration, see jquery docs. For example, 500 miliseconds:
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
//hide all sliding divs
var arrayLikeOfSlidingDivs = $('.slidingDiv');
arrayLikeOfSlidingDivs.each(function(){
if ($(this).is(':visible')){
$(this).hide(500);
}
});
var isvisible = $(this).next('.slidingDiv').is(':visible');
if ( isvisible ) {
$(this).next('.slidingDiv').hide(500);
} else{
$(this).next('.slidingDiv').show(500);
}
});
});

jquery - trimming image to remove div

i am trying through jquery to remove a div completely when there is no child element within it. The variable I am using is an image. I can't seem to select the variable as an image, i only know how to do this through text. Could someone please help me and resolve this issue, so it detects that there is a img contained within the div and displays it and when there isn't an image it doesn't display it.
I have uploaded it through jsfiddle:http://jsfiddle.net/cLkFD/
<div class="content-container"><!--content-container-->
<h3>title</h3>
<div class="picture"><!--picture-->
<img src="images/buddha.jpg" width="981" height="324" alt=""/>
</div><!--/picture-->
<div class="content"><!--content-->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et cursus neque, sit amet blandit tellus. Cras leo mauris, laoreet quis consequat et, pharetra mattis risus. Duis tortor lorem, ultrices egestas arcu sed, pretium egestas est. Morbi condimentum sem quis tortor placerat iaculis. Ut nisl augue, rutrum sed sem et, blandit hendrerit nibh. Donec et rhoncus odio, id tempor enim. Praesent ultricies justo vulputate dui gravida fermentum. Pellentesque id aliquet leo. Quisque vulputate, dolor vel rutrum accumsan, turpis odio faucibus sem, vel malesuada eros turpis ac magna. Nullam fermentum vehicula odio, ut ornare justo varius nec. Morbi lectus leo, porttitor nec elementum at, suscipit aliquam nunc. Ut gravida a sem ut imperdiet. Duis et turpis eget magna lobortis accumsan. In ac tincidunt nibh, quis pulvinar risus.
</p>
<button class="btn btn-1 btn-1a">Read More</button>
</div><!--content-->
</div><!--content-container-->
(function($) {
$.fn.equalHeights = function(minHeight, maxHeight) {
tallest = (minHeight) ? minHeight : 0;
this.each(function() {
if($(this).height() > tallest) {
tallest = $(this).height();
}
});
if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
return this.each(function() {
$(this).height(tallest).css("overflow","hidden");
});
}
})(jQuery);
You can check to see whether any image inside your div or not using length:
$(function () {
$('.picture').each(function () {
if ($(this).find('img').length) {
$(this).hide();
}
});
});
http://jsfiddle.net/9VBJP/
The above fiddle should work
$('.picture').each(function(){
var imageElem = $(this).find('img');
if(imageElem.length == 0) {
$(this).hide();
}
});

How can we use jQuery Expander plugin to expand/collapse according to number of lines rather than characters?

I have checked the following links
jQuery expander with max-lines property
How to get first 2 lines or 200 characters from <p> using jQuery
but in these its not possible to predict the line height if your div contains headings and text of different font sizes
eg.
<div class='info'>
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ornare cursus elementum.
Mauris et sem vitae dui vehicula lobortis a non orci. In tortor lacus,
vehicula id placerat nec, pharetra non nunc. Aliquam id ipsum quis orci
posuere pellentesque et vel urna. Vestibulum mattis sem ornare neque fermentum vel
imperdiet nunc eleifend. Suspendisse potenti. Nam scelerisque sodales porttitor. Vestibulum cursus
lobortis magna, id vehicula justo faucibus iaculis. Proin facilisis facilisis mauris. Pellentesque ultrices
pharetra diam. Fusce a eleifend quam. Aenean eu odio dolor. Mauris augue leo, fringilla eu sagittis at, fermentum
vitae dui. Maecenas scelerisque mi at erat posuere vitae porta metus tempor. Vivamus at ante id velit rutrum
aliquet eget sit amet purus. Proin sed vehicula elit. Aenean a viverra nunc.</p>
I've worked some of the code in the two links you posted. The following JSfiddle will show you how it works and what the html and css that is required is. I suggest only using the .class for truncating on the paragraph. This answer will account for different font sizes.
http://jsfiddle.net/Pjgzq/1/
Basically, once you add the jquery function in the js fiddle you need to call
$('.class').truncate();
Options can be passed in that match the "default" options in the function.
Here is the function.
$.fn.truncate = function(options) {
$(this).append('<span class="truncate_lh" style="display:none;"> </span>')
var defaults = {
maxlines: 2,
moreText: 'More',
lessText: 'Less',
ellipsis: '...'
};
$.extend(options, {
lineheight: ($('.truncate_lh').css('height').replace('px', ''))
});
$.extend(options, {
maxheight: (options.maxlines * options.lineheight)
});
options = $.extend(defaults, options);
return this.each(function() {
var text = $(this);
if (text.height() > options.maxheight) {
text.css({
'overflow': 'hidden',
'height': options.maxheight + 'px'
});
var link = $('' + options.moreText + '');
var wrapDiv = $('<div class="truncate_wrap" />');
text.wrap(wrapDiv);
text.after(link);
link.click(function() {
if (link.text() == options.moreText) {
link.text(options.lessText);
text.css('height', 'auto');
} else {
link.text(options.moreText);
text.css('height', options.maxheight + 'px');
}
return false;
});
}
});
};

How can I select the first word of every line of a block of text?

I'm trying to select each first word, to wrap it in a 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 a nunc ipsum, id
mattis odio. Donec rhoncus posuere
bibendum. Fusce nulla elit, laoreet
non posuere.
If this is the text, the script should select Lorem, Aliquam, varius and nulla.
You can do this, by using JavaScript to wrap every word in the paragraph in its own span, and then walking through the spans finding out what their actual position on the page is, and then applying your style changes to the spans whose Y position is greater than the preceding span. (Best do it beginning-to-end, though, as earlier ones may well affect the wrapping of latter ones.) But it's going to be a lot of work for the browser, and you'll have to repeat it each time the window is resized, so the effect will have to be worth the cost.
Something like this (used jQuery as you've listed the jquery tag on your question):
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;
}
});
});
<div id='target' style='width: 20em'>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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Naturally that's making a huge set of assumptions (that all whitespace should be replaced with a single space, that there's no markup in the text, probably others). But you get the idea.
Here's a version that handles window resize, 50ms after the last resize event occurs (so we're not doing it interim) and with Gaby's suggestion (below) that we unbold at the start of the resize:
jQuery(function($) {
var resizeTriggerHandle = 0;
// Do it on load
boldFirstWord('#target');
// Do it 100ms after the end of a 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 into spans if not already done;
// if already done, remove any 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 to 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);
}
}
});
<div id='target'>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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. 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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. 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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. 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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. 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 a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Try this:
$(function() {
$('p').each(function() {
var text_splited = $(this).text().split(" ");
$(this).html("<strong>"+text_splited.shift()+"</strong> "+text_splited.join(" "));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor.</p>
<p>Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum.</p>
<p>Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</p>
To bold every first word of a <p> tag, including whitespace after the initial <p>, use some regular expressions:
$('p').each(function(){
var me = $(this);
me.html( me.text().replace(/(^\w+|\s+\w+)/,'<strong>$1</strong>') );
});

Categories

Resources