Multiple Click jQuery - javascript

I am trying to show/hide content on a page that contains the same class on multiple HTML elements. However, when I click on one of the anchor links, it opens BOTH paragraphs, rather than only the paragraph that I am trying to open. How do I fix this so that the Read more only toggles the intended paragraph?
JS:
$('.show-more').click(function(e) {
e.preventDefault();
if($('.show-more-snippet').css('height') != '96px'){
$('.show-more-snippet').stop().animate({height: '96px'}, 200);
$(this).text('Read more');
}else{
$('.show-more-snippet').css({height:'100%'});
var xx = $('.show-more-snippet').height();
$('.show-more-snippet').css({height:'96px'});
$('.show-more-snippet').stop().animate({height: xx}, 400);
$(this).text('Read less');
} }); });
HTML:
<div><p class="show-more-snippet"> Some first paragraph text</p>
<a class="show-more" href="#">Read more</a> </div>
<div><p class="show-more-snippet"> Some second paragraph text</p>
<a class="show-more" href="#">Read more</a> </div>
CSS:
.show-more-snippet {
height:16px;
overflow:hidden;
}

All you need is to change all of $('.show-more-snippet') with $(this).prev(). This will give you the access to the p that is just before the button clicked.

Try using this: http://jsfiddle.net/6jnwmkp4/
$('.show-more').click(function(e) {
e.preventDefault();
if($(this).siblings('.show-more-snippet').css('height') != '96px'){
$(this).siblings('.show-more-snippet').stop().animate({height: '96px'}, 200);
$(this).text('Read more');
}else{
$(this).siblings('.show-more-snippet').css({height:'100%'});
var xx = $(this).siblings('.show-more-snippet').height();
$(this).siblings('.show-more-snippet').css({height:'96px'});
$(this).siblings('.show-more-snippet').stop().animate({height: xx}, 400);
$(this).text('Read less');
}
});

Inside your callback you are using a class show-more-snippet which is used by both paragraph elements. That's why both of them are getting affected.

$('.show-more').click(function(e) {
e.preventDefault();
//write closing logic to close all if you want to close other tab on class name
$('.show-more-snippet').css({height:'100%'});
//Then open this tab .
if($(this).css('height') != '96px'){
$(this).stop().animate({height: '96px'}, 200);
$(this).text('Read more');
}else{
$(this).css({height:'100%'});
var xx = $(this).height();
$(this).css({height:'96px'});
$(this).stop().animate({height: xx}, 400);
$(this).text('Read less');
} }); });

Given your HTML structure, you need to use .parent().find() in your jQuery. This will target the clicked elements sibling rather than all elements with the .show-more-snippet class.
eg.
if($(this).parent().find('.show-more-snippet').css('height') != '96px')...
and
$(this).parent().find('.show-more-snippet').stop().animate({height: '96px'}, 200);
etc.
EDIT: A better way to do it would be to use .siblings() like so:
eg.
if($(this).siblings('.show-more-snippet').css('height') != '96px')...
and
$(this).siblings('.show-more-snippet').stop().animate({height: '96px'}, 200);
etc.

You have to use prev for that. see below code shipment.
Jquery
$(document).ready(function(){
$('.show-more').click(function(e) {
e.preventDefault();
if($(this).prev('.show-more-snippet').css('height') != '96px'){
$(this).prev('.show-more-snippet').stop().animate({height: '96px'}, 200);
$(this).text('Read more');
}else{
$(this).prev('.show-more-snippet').css({height:'100%'});
var xx = $(this).prev('.show-more-snippet').height();
$(this).prev('.show-more-snippet').css({height:'96px'});
$(this).prev('.show-more-snippet').stop().animate({height: xx}, 400);
$(this).text('Read less');
}
});
});
HTML
<div>
<p class="show-more-snippet"> Some first paragraph text</p>
<a class="show-more" href="#">Read more</a>
</div>
<div>
<p class="show-more-snippet"> Some second paragraph text</p>
<a class="show-more" href="#">Read more</a>
</div>

Just select particular prev div.
$('.show-more').click(function(e) {
e.preventDefault();
if($(this).prev('.show-more-snippet').css('height') != '96px'){
$(this).prev('.show-more-snippet').stop().animate({height: '96px'}, 200);
$(this).text('Read more');
}else{
$(this).prev('.show-more-snippet').css({height:'100%'});
var xx = $('.show-more-snippet').height();
$(this).prev('.show-more-snippet').css({height:'96px'});
$(this).prev('.show-more-snippet').stop().animate({height: xx}, 400);
$(this).text('Read less');
} });

The issue is that you are not specifying which of the <p class=".show-more-snippet"></p> to use. This should be the one you clicked the "show more" button for.
You can solve this using the e value in your click listener. See below for var paragraph which gets the proper <p> element which you can use for what you need to do.
Just replace $('.show-more-snippet') with $(paragraph) in your code.
Solution:
$('.show-more').click(function (e) {
e.preventDefault();
// get the correct paragraph
var paragraph = e.target.parentNode.querySelector('.show-more-snippet');
if ($(paragraph).css('height') != '96px') {
$(paragraph).stop().animate({height: '96px'}, 200);
// ... etc ...
}
});

Add active class on the div parent of the anchor you click, other divs remove active class. This way will simplify your code.
in code
$('.show-more').click(function(e) {
e.preventDefault();
$('.show-more-snippet.active').removeClass('active');
$(this).closest('.show-more-snippet').addClass('active');
});
In css
.show-more-snippet.active {
height:96px;
overflow:hidden;
}

you have got too many answers for your problem above but If you want a clean solution using some external js then you can use expander.
main source:here
$(document).ready(function(){
$('div.show-more-snippet').expander({
slicePoint: 280, //It is the number of characters at which the contents will be sliced into two parts.
widow: 2,
expandSpeed: 0, // It is the time in second to show and hide the content.
userCollapseText: 'Read Less (-)' // Specify your desired word default is Less.
});
$('div.show-more-snippet').expander();
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://www.discussdesk.com/online_demo/read-more-less-content-in-jquery-expander-plugin/jquery.expander.js"></script>
<div class="show-more-snippet">
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
</div>
<div class="show-more-snippet">
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor pulvinar mi in pellentesque. In et faucibus nisi. Vivamus nec bibendum eros. Ut in augue ac leo facilisis lobortis. Cras sit amet pulvinar massa. Donec sed tempus velit. Praesent dignissim iaculis pretium.</p>
</div>

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>

how to show JS alert on open of each tab of the slider?

I'm using the liquidslider script on my webpage and I created the slider on my page, the html code looks like this:
<div class="liquid-slider" id="slider-id">
<div>
<h2 class="title">Slide 1</h2>
// Content goes here
</div>
<div>
<h2 class="title">Slide 2</h2>
// Content goes here
</div>
<div>
<h2 class="title">Slide 3</h2>
// Content goes here
</div>
</div>
There's also my current javascript:
$('#slider-1').liquidSlider({
autoHeight:false,
slideEaseFunction:'animate.css',
slideEaseDuration:1000,
heightEaseDuration:1000,
animateIn:"fadeIn",
animateOut:"fadeOut",
callback: function() {
var self = this;
$('.slider-1-panel').each(function() {
$(this).removeClass('animated ' + self.options.animateIn);
});
$('.slider-1-panel').each(function() {
alert("you opened panel");
});
}
});
and currently the message "you opened panel" is shown 4 times each time the user clicks the panel tab, that's because of those lines:
$('.slider-1-panel').each(function() {
alert("you opened panel");
});
How can I change it so that the message is displayed only once for each panel? Later on I want to add animations in css to each panel so that they're invoked when the user selects the panel and I thought the good start would be to know when the user selects any panel.
as you suggested, I created a jsfiddle, I added resources, but I can't make it up and running properly, I don't know what I'm doing wrong there.. But the css code is visible there, hopefuly that's helpful enough
EDIT:
I've decided to add a little bit more details. I managed to create an option that changes all the tabs while the user clicks any tab:
$('#slider-1').liquidSlider({
autoHeight:false,
slideEaseFunction:'animate.css',
slideEaseDuration:1000,
heightEaseDuration:1000,
animateIn:"fadeIn",
animateOut:"fadeOut",
callback: function() {
var self = this;
$('.slider-1-panel').each(function() {
$(this).removeClass('animated ' + self.options.animateIn);
});
$('#slider-1-nav-ul a').each(function() {
$(this).css('background', '#'+Math.floor(Math.random()*16777215).toString(16));
$(this).css('color', '#'+Math.floor(Math.random()*16777215).toString(16));
})
}
});
but now I need to change the $('#slider-1-nav-ul a').each(function() { part to not to look at all tabs, but on the one that has just been clicked. How can I do that?
Add class to each (here I use .tabs) divelement, it makes easy to loop over those div.
Use use jquery each method to loop over all the div
$('.liquid-slider .tabs').each(
function() {
$(this).click(
function() {
alert('you open panel ' + $(this)[0].id);
}
);
}
);
Edit
Then try this to your project:
$('#slider-1-nav-ul a').each(function() {
$(this).click(function() {
$(this).css('background', '#'+Math.floor(Math.random()*16777215).toString(16));
$(this).css('color', '#'+Math.floor(Math.random()*16777215).toString(16));
});
})
Explain
Each loop over all <a> element, and this represent the current element which is clicked. Then you change the background and the color of this clicked element.
Hope it helps you!
Demo
You can move your alert out of the each, then the message will be displayed only once for each panel.
Add different id to each <h2> tag and add the following code in your js
$(".title").click(function(e){
var panelName=$(this).attr('id');
alert(panelName);
});
hope this will help
You need to give each tab an id to reference with your jquery/javascript
<div class="liquid-slider" id="monitor-slider">
<div id= "name_this>
<h2 class="title">Slide 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas metus nulla, commodo a sodales sed, dignissim pretium nunc. Nam et lacus neque. Sed volutpat ante id mauris laoreet vestibulum. Nam blandit felis non neque cursus aliquet. Morbi vel enim dignissim massa dignissim commodo vitae quis tellus. Nunc non mollis nulla. Sed consectetur elit id mi consectetur bibendum. Ut enim massa, sodales tempor convallis et, iaculis ac massa. Etiam suscipit nisl eget lorem pellentesque quis iaculis mi mattis. Aliquam sit amet purus lectus. Maecenas tempor ornare sollicitudin.</p>
</div>
<div id= "name_this_different>
<h2 class="title">Slide 2</h2>
<p>Proin nec turpis eget dolor dictum lacinia. Nullam nunc magna, tincidunt eu porta in, faucibus sed magna. Suspendisse laoreet ornare ullamcorper. Nulla in tortor nibh. Pellentesque sed est vitae odio vestibulum aliquet in nec leo.</p>
</div>
<div id= "name_this_different_again>
<h2 class="title">Slide 3</h2>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi.</p>
</div>
</div>
$("This").click(function(){
alert("This tab.");
});

Expanding a Read more / Read less jQuery script

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>

Delay on-click div replacement

When the area in div 1 is clicked it is replaced with div 2 instantly. How do I add a 10 second delay between the transition?
<div id = "div1" style="display:block" onclick = "replace()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. </div>
<div id = "div2" style="display:none">Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus. </div>
<script type = "text/javascript">
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
}
</script>
You can use setTimeout function of javascript.
Change your replace function to:
function replace() {
document.getElementById("div1").style.display="none";
setTimeout( function(){
document.getElementById("div2").style.display="block";}, 10000);
}

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