Line break after every "." - javascript

I am using Axios to get data from an API. Then I am presenting the user with the data. The problem is that the text can be very lengthy and I wanted to add a line break after every "." for better presentation. Does anyone know a way to do it with CSS or any other way? Thank you. I'm using javascript by the way.
I am trying your code and my data is still not getting modified.
Am I making a mistake? I am new to js.
function App() {
const [cardChosen, setCardChosen] = useState(false);
const [cardName, setCardName] = useState("");
const [card, setCard] = useState({
passageName: "",
passages: "",
});
const searchCard = () => {
//this has been changed from the original
Axios.get(`https://bible-api.com/${cardName}`)
.then((response) => {
console.log(response);
setCard({
passageName: cardName,
passages: response.data.text,
passage: card.passages.replaceAll('. ', '.\n')
});
setCardChosen(true);
});
// addNewLines(card.passage);
};
// const addNewLines = () => {
// card.passage = card.passage.replaceAll('. ', '.\n');
// };
return (
<div className="App">
<div className="TitleSection">
<h1>Bible passages</h1>
<input type="text" onChange= {(event) => {
setCardName(event.target.value);
}}
/>
<button onClick={searchCard}>Search the Bible</button>
</div>
<div className="DisplaySection">
{!cardChosen ?
(<>
<h3> Please write the passage you want to read.</h3>
<h6>Format example: john 3:16</h6>
<h6>If you want several passages, write: john 3:1-16</h6>
</>)
:
(
<>
<h1>{card.passageName}</h1>
<h4>{card.passage}</h4>
</>
)}
</div>
</div>
);
}
export default App;

If you have the data as a string in javascript you can do this:
const myString = 'Hello, this is a string with one line. It will soon have 2 lines.'
const stringWithNewLines = myString.replaceAll('.', '.\n');
This will replace all occurrences of periods with a period followed by a new line (the \n is a newline). The new string is now:
Hello, this is a string with one line.
It will soon have 2 lines.
Notice there is a space at the start of the second line now, because there is a space following the period. If you want to get rid of the space do
const stringWithNewLines = myString.replaceAll('. ', '.\n');
So now it is replacing the space as well.
Note that replaceAll returns a new string and does not modify the original string.
I am fairly sure there is no way to do this in CSS, but if your string is already in javascript it will be very easy.

You need to add modify the text adding \n after each . (dot and space) with javascript.
const textFromAPI = 'Lorem ipsum. Dolor sit amet. Consectetur adipiscing elit.';
const modifiedText = textFromAPI.replaceAll(/\. /g, '.\n');
After that, you should put the text inside an element that has white-space: pre; or white-space: pre-wrap; CSS rule. More about white-space rule
<div style="white-space: pre;">
<!-- modifiedText goes here -->
</div>

You can achieve that in multiple ways, two of them are using:
string.prototype.split( ) and array.prototype.join( )
text = text.split('.').join('. <br/>');
string.prototype.replace( )
text = text.replace(/\./g, '. <br/>');
Please execute this snippet below. I've added some css, you can ignore it.
let text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum congue, enim sit amet dictum varius, purus massa tempus eros, eu porttitor magna tellus vel quam. In hac habitasse platea dictumst. Quisque sit amet placerat tortor, a euismod tortor. Phasellus eget placerat nisl, sit amet aliquet felis. Nulla lacus est, euismod vitae aliquam ut, mollis at odio. Cras tempor volutpat tellus, id sagittis orci mollis ut. Nulla aliquam mattis tortor. Curabitur lacus erat, ultrices in tempor sit amet, scelerisque sed risus. Nunc ultrices vulputate nisi, eu pulvinar neque laoreet auctor. Nunc ullamcorper nec enim in tincidunt. Duis sit amet viverra tellus, eu ultrices orci.';
const element = document.querySelector('.text');
//Either This
//text = text.split('.').join('. <br/>')
//or This
text = text.replace(/\./g, '. <br/>')
element.innerHTML = text;
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
.text{
font-size: 16px;
font-family: 'Roboto', sans-serif;
color:#ffeaa7;
}
.card{
border-radius: 0px 5px 0px 0px;
padding: 5px;
box-shadow: 0 5px 10px rgba(0,0,0,0.9);
background-color: #2d3436;
transition: all 0.2s;
}
<div class="card">
<p class="text"><p>
</div>

Related

Add more than one "Read More" link in a paragraph (readmore.js)

I am using readmore.js and I would like to expand my paragraph twice.
For now I am using one expand link with a value of 'More information' that shows all the text when clicked.
There is another link in the bottom with a value of 'Less information' that hides the text when clicked:
This is some text and continues for ages...
More information
This is some text and continues for ages...
but is not as long as you think.
Less information
I would like to add another expand link called 'Even more information'. In this situation 'More information' would only show a part of the text while 'Even more information' would show the complete text. This would look something like this:
This is some text and continues for ages...
More information
This is some text and continues for ages...
and it goes on and on and on...
Even more information
This is some text and continues for ages...
and it goes on and on and on...
but not as long as you think.
Less information
This snippet shows my current situation:
$('.example').readmore({
collapsedHeight: 300,
speed: 500,
embedCSS: false,
moreLink: 'More information',
lessLink: 'Less information',
beforeToggle: function(trigger, element, expanded) {
if (expanded === false) {
element.addClass('remove-after');
} else {
element.removeClass('remove-after');
}
}
});
.example+[data-readmore-toggle],
.example[data-readmore] {
display: block;
}
.example[data-readmore]::after {
background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 85%);
bottom: 0;
content: '';
display: inline-block;
height: 250px;
position: absolute;
right: 0;
width: 100%;
}
.remove-after::after {
display: none !important;
}
[data-readmore-toggle] {
margin-left: 15px;
}
img {
float: right;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/readmore-js#2.1.0/readmore.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="example col-md-12">
<p>They say everything looks better with odd numbers of things. But sometimes I put even numbers—just to upset the critics. Don't be afraid to make these big decisions. Once you start, they sort of just make themselves. Now let's put some happy little
clouds in here. We can always carry this a step further. There's really no end to this. Think about a cloud. Just float around and be there. We want to use a lot pressure while using no pressure at all.</p>
<p>Look around, look at what we have. Beauty is everywhere, you only have to look to see it. That's the way I look when I get home late; black and blue. All you have to do is let your imagination go wild. We have a fantastic little sky!</p>
<p>All kinds of happy little splashes. We don't want to set these clouds on fire. I was blessed with a very steady hand; and it comes in very handy when you're doing these little delicate things. It looks so good, I might as well not stop. We need dark
in order to show light. I really recommend you use odorless thinner or your spouse is gonna run you right out into the yard and you'll be working by yourself.</p>
<img src="https://dummyimage.com/200x200/2d5cc2/fff" />
<p>Van Dyke Brown is a very nice brown, it's almost like a chocolate brown. We're trying to teach you a technique here and how to use it. This present moment is perfect simply due to the fact you're experiencing it.</p>
<p>If what you're doing doesn't make you happy - you're doing the wrong thing. We spend so much of our life looking - but never seeing. In this world, everything can be happy. Everyone is going to see things differently - and that's the way it should be.
And just raise cain.</p>
<p>There's nothing wrong with having a tree as a friend. Maybe there was an old trapper that lived out here and maybe one day he went to check his beaver traps, and maybe he fell into the river and drowned. Tree trunks grow however makes them happy.</p>
<p>Let your imagination be your guide. You could sit here for weeks with your one hair brush trying to do that - or you could do it with one stroke with an almighty brush. We wash our brush with odorless thinner. Every highlight needs it's own personal
shadow. Don't kill all your dark areas - you need them to show the light. Working it up and down, back and forth.</p>
<p>Don't forget to tell these special people in your life just how special they are to you. The only thing worse than yellow snow is green snow. That's why I paint - because I can create the kind of world I want - and I can make this world as happy as
I want it. Let's build an almighty mountain. You have to make almighty decisions when you're the creator.</p>
<p>We have a fantastic little sky! Everybody's different. Trees are different. Let them all be individuals. Just go out and talk to a tree. Make friends with it. Go out on a limb - that's where the fruit is. There are no mistakes. You can fix anything
that happens.</p>
<p>You have to make those little noises or it won't work. We have no limits to our world. We're only limited by our imagination. I want everbody to be happy. That's what it's all about.</p>
<p>Nice little clouds playing around in the sky. It's a super day, so why not make a beautiful sky? We spend so much of our life looking - but never seeing. The secret to doing anything is believing that you can do it. Anything that you believe you can
do strong enough, you can do. Anything. As long as you believe. Everything's not great in life, but we can still find beauty in it.</p>
<p>If you've been in Alaska less than a year you're a Cheechako. You don't have to be crazy to do this but it does help. I'm going to mix up a little color. We’ll use Van Dyke Brown, Permanent Red, and a little bit of Prussian Blue. And I will hypnotize
that just a little bit. Nothing's gonna make your husband or wife madder than coming home and having a snow-covered dinner.</p>
<p>There it is. Don't fiddle with it all day. No worries. No cares. Just float and wait for the wind to blow you around.</p>
<p>All you need to paint is a few tools, a little instruction, and a vision in your mind. Let's put a touch more of the magic here. Now let's put some happy little clouds in here. We'll lay all these little funky little things in there. But we're not there
yet, so we don't need to worry about it. All you have to learn here is how to have fun.</p>
</div>
I think the better way is to modify directly the readmore.js plugin. So I have add a step and a new label:
$('article').readmore({
speed: 500,
collapsedHeight:200,
collapsedMoreHeight: 400, // Always bigger than collapsedHeigh. There isn't any control to that. Be careful.
moreLink: '<a class="white-shadow" href="#">More information</a>',
evenMoreLink: '<a class="white-shadow" href="#">Even More informations</a>', // Add new label
lessLink: 'Less information'
});
The biggest changes I did are these:
var $element = $(element),
newHeight = '',
newLink = '',
expanded = false,
collapsedHeight = $element.data('collapsedHeight'),
collapsedMoreHeight = this.options.collapsedMoreHeight; // add an Even More informations
if ($element.data('expandedHeight') <= collapsedMoreHeight){
//This is the normal code if the article's height is smaller than my new option
if ($element.height() <= collapsedHeight) {
newHeight = $element.data('expandedHeight') + 'px';
newLink = 'lessLink';
expanded = true;
}
else {
newHeight = collapsedHeight;
newLink = 'moreLink';
}
} else {
//Here it works the new step: 'Even More informations'
if ($element.height() <= collapsedHeight) {
newHeight = collapsedMoreHeight;
newLink = 'evenMoreLink';
expanded = false;
} else if ($element.height() > collapsedHeight && $element.height() <= collapsedMoreHeight){
newHeight = $element.data('expandedHeight') + 'px';
newLink = 'lessLink';
expanded = true;
}
else {
newHeight = collapsedHeight;
newLink = 'moreLink';
}
}
// This is the new Readmore.js file. Save this in external file.
/*!
* #preserve
*
* Readmore.js jQuery plugin
* Author: #jed_foster
* Project home: http://jedfoster.github.io/Readmore.js
* Licensed under the MIT license
*
* Debounce function from http://davidwalsh.name/javascript-debounce-function
*/
/* global jQuery */
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
'use strict';
var readmore = 'readmore',
defaults = {
speed: 100,
collapsedHeight: 50,
collapsedMoreHeight: 150, // add an Even More informations Height
heightMargin: 16,
moreLink: 'More informations',
evenMoreLink: 'Even more informations', // add new label
lessLink: 'Close',
embedCSS: true,
blockCSS: 'display: block; width: 100%;',
startOpen: false,
// callbacks
blockProcessed: function() {},
beforeToggle: function() {},
afterToggle: function() {}
},
cssEmbedded = {},
uniqueIdCounter = 0;
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (! immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
function uniqueId(prefix) {
var id = ++uniqueIdCounter;
return String(prefix == null ? 'rmjs-' : prefix) + id;
}
function setBoxHeights(element) {
var el = element.clone().css({
height: 'auto',
width: element.width(),
maxHeight: 'none',
overflow: 'hidden'
}).insertAfter(element),
expandedHeight = el.outerHeight(),
cssMaxHeight = parseInt(el.css({maxHeight: ''}).css('max-height').replace(/[^-\d\.]/g, ''), 10),
defaultHeight = element.data('defaultHeight');
el.remove();
var collapsedHeight = cssMaxHeight || element.data('collapsedHeight') || defaultHeight;
// Store our measurements.
element.data({
expandedHeight: expandedHeight,
maxHeight: cssMaxHeight,
collapsedHeight: collapsedHeight
})
// and disable any `max-height` property set in CSS
.css({
maxHeight: 'none'
});
}
var resizeBoxes = debounce(function() {
$('[data-readmore]').each(function() {
var current = $(this),
isExpanded = (current.attr('aria-expanded') === 'true');
setBoxHeights(current);
// Resize only if expanded
if(isExpanded){
current.css({
height: current.data('expandedHeight')
});
}
});
}, 100);
function embedCSS(options) {
if (! cssEmbedded[options.selector]) {
var styles = ' ';
if (options.embedCSS && options.blockCSS !== '') {
styles += options.selector + ' + [data-readmore-toggle], ' +
options.selector + '[data-readmore]{' +
options.blockCSS +
'}';
}
// Include the transition CSS even if embedCSS is false
styles += options.selector + '[data-readmore]{' +
'transition: height ' + options.speed + 'ms;' +
'overflow: hidden;' +
'}';
(function(d, u) {
var css = d.createElement('style');
css.type = 'text/css';
if (css.styleSheet) {
css.styleSheet.cssText = u;
}
else {
css.appendChild(d.createTextNode(u));
}
d.getElementsByTagName('head')[0].appendChild(css);
}(document, styles));
cssEmbedded[options.selector] = true;
}
}
function Readmore(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
embedCSS(this.options);
this._defaults = defaults;
this._name = readmore;
this.init();
// IE8 chokes on `window.addEventListener`, so need to test for support.
if (window.addEventListener) {
// Need to resize boxes when the page has fully loaded.
window.addEventListener('load', resizeBoxes);
window.addEventListener('resize', resizeBoxes);
}
else {
window.attachEvent('load', resizeBoxes);
window.attachEvent('resize', resizeBoxes);
}
}
Readmore.prototype = {
init: function() {
var current = $(this.element);
current.data({
defaultHeight: this.options.collapsedHeight,
heightMargin: this.options.heightMargin
});
setBoxHeights(current);
var collapsedHeight = current.data('collapsedHeight'),
heightMargin = current.data('heightMargin');
if (current.outerHeight(true) <= collapsedHeight + heightMargin) {
// The block is shorter than the limit, so there's no need to truncate it.
if (this.options.blockProcessed && typeof this.options.blockProcessed === 'function') {
this.options.blockProcessed(current, false);
}
return true;
}
else {
var id = current.attr('id') || uniqueId(),
useLink = this.options.startOpen ? this.options.lessLink : this.options.moreLink;
current.attr({
'data-readmore': '',
'aria-expanded': this.options.startOpen,
'id': id
});
current.after($(useLink)
.on('click', (function(_this) {
return function(event) {
_this.toggle(this, current[0], event);
};
})(this))
.attr({
'data-readmore-toggle': id,
'aria-controls': id
}));
if (! this.options.startOpen) {
current.css({
height: collapsedHeight
});
}
if (this.options.blockProcessed && typeof this.options.blockProcessed === 'function') {
this.options.blockProcessed(current, true);
}
}
},
toggle: function(trigger, element, event) {
if (event) {
event.preventDefault();
}
if (! trigger) {
trigger = $('[aria-controls="' + this.element.id + '"]')[0];
}
if (! element) {
element = this.element;
}
/////////////////////////
// I changed this part //
/////////////////////////
var $element = $(element),
newHeight = '',
newLink = '',
expanded = false,
collapsedHeight = $element.data('collapsedHeight'),
collapsedMoreHeight = this.options.collapsedMoreHeight; // add an Even More informations
if ($element.data('expandedHeight') <= collapsedMoreHeight){
//This is the normal code if the article's height is smaller than my new option
if ($element.height() <= collapsedHeight) {
newHeight = $element.data('expandedHeight') + 'px';
newLink = 'lessLink';
expanded = true;
}
else {
newHeight = collapsedHeight;
newLink = 'moreLink';
}
} else {
//Here it works the new step: 'Even More informations'
if ($element.height() <= collapsedHeight) {
newHeight = collapsedMoreHeight;
newLink = 'evenMoreLink';
expanded = false;
} else if ($element.height() > collapsedHeight && $element.height() <= collapsedMoreHeight){
newHeight = $element.data('expandedHeight') + 'px';
newLink = 'lessLink';
expanded = true;
}
else {
newHeight = collapsedHeight;
newLink = 'moreLink';
}
}
////////////////
// End change //
////////////////
// Fire beforeToggle callback
// Since we determined the new "expanded" state above we're now out of sync
// with our true current state, so we need to flip the value of `expanded`
if (this.options.beforeToggle && typeof this.options.beforeToggle === 'function') {
this.options.beforeToggle(trigger, $element, ! expanded);
}
$element.css({'height': newHeight});
// Fire afterToggle callback
$element.on('transitionend', (function(_this) {
return function() {
if (_this.options.afterToggle && typeof _this.options.afterToggle === 'function') {
_this.options.afterToggle(trigger, $element, expanded);
}
$(this).attr({
'aria-expanded': expanded
}).off('transitionend');
}
})(this));
$(trigger).replaceWith($(this.options[newLink])
.on('click', (function(_this) {
return function(event) {
_this.toggle(this, element, event);
};
})(this))
.attr({
'data-readmore-toggle': $element.attr('id'),
'aria-controls': $element.attr('id')
}));
},
destroy: function() {
$(this.element).each(function() {
var current = $(this);
current.attr({
'data-readmore': null,
'aria-expanded': null
})
.css({
maxHeight: '',
height: ''
})
.next('[data-readmore-toggle]')
.remove();
current.removeData();
});
}
};
$.fn.readmore = function(options) {
var args = arguments,
selector = this.selector;
options = options || {};
if (typeof options === 'object') {
return this.each(function() {
if ($.data(this, 'plugin_' + readmore)) {
var instance = $.data(this, 'plugin_' + readmore);
instance.destroy.apply(instance);
}
options.selector = selector;
$.data(this, 'plugin_' + readmore, new Readmore(this, options));
});
}
else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
return this.each(function () {
var instance = $.data(this, 'plugin_' + readmore);
if (instance instanceof Readmore && typeof instance[options] === 'function') {
instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
});
}
};
}));
// Init plugin
$('article').readmore({
speed: 500,
collapsedHeight:200,
collapsedMoreHeight: 400, // This is your new second height. Always bigger than collapsedHeigh. There isn't any control to that. Be careful.
moreLink: '<a class="white-shadow" href="#">More information</a>',
evenMoreLink: '<a class="white-shadow" href="#">Even More informations</a>', // Add new label
lessLink: 'Less information'
});
body { font: 16px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif; color: #444; }
code { color: #777; font-family: "Source Code Pro", "Menlo", "Courier New", monospace;}
a { color: #178DB1; }
.container { margin: 0 auto; max-width: 960px; }
#info + .readmore-js-toggle { padding-bottom: 1.5em; border-bottom: 1px solid #999; font-weight: bold;}
.white-shadow{
position:relative;
}
.white-shadow:after{
background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 85%);
bottom: 100%;
content: '';
display: inline-block;
height: 150px;
position: absolute;
right: 0;
width: 100%;
}
#demo { padding: 0 10%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<section id="demo">
<article>
<h2>Artisanal Narwahls</h2>
<p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
<article>
<h2>Portland Leggings</h2>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut odio neque, dapibus a tincidunt sed, molestie in diam. Quisque quis vulputate tellus. Nulla nisl mi, rhoncus et magna cursus, euismod vehicula erat. Integer fringilla urna orci, at tempor nisi suscipit ut. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec non laoreet ex. Cras et purus augue. Donec a urna et leo malesuada laoreet. Duis tortor massa, fermentum et porta id, pharetra suscipit lorem. Donec molestie nunc nisi, sed faucibus turpis facilisis eget. Morbi eros mauris, fringilla in est a, vehicula tempus felis. Nullam sodales tincidunt turpis sed dapibus.</p>
<p> Proin efficitur, leo ac sagittis faucibus, elit purus consectetur dolor, et scelerisque orci neque a orci. Nullam ut congue libero, in ornare mi. Quisque mattis porttitor nulla non fermentum. Suspendisse euismod facilisis magna, eget interdum leo semper sed. Nullam pretium, nisl sit amet auctor rhoncus, velit ipsum ullamcorper turpis, nec feugiat mauris diam ac lorem. Cras hendrerit non eros id ultricies. Aenean sed felis purus. Sed commodo, enim sed aliquet egestas, nisl odio porta ante, ac euismod justo turpis in mauris. Ut lobortis augue ut ex scelerisque, ut lacinia libero sollicitudin. Pellentesque vestibulum ac tellus sit amet commodo. Phasellus eu nunc nibh. In porta metus sed pharetra aliquet. Etiam eu magna id erat accumsan pellentesque pulvinar eget erat.</p>
<p> Etiam vitae aliquam nisi. Aliquam vel suscipit felis. Donec non dapibus odio. Vivamus tincidunt mauris in tortor fermentum, a laoreet sem semper. Sed luctus vitae turpis vitae vulputate. Integer a libero orci. Morbi eu porttitor nisi, facilisis consectetur velit. Suspendisse sed facilisis velit. Proin rutrum ligula a purus mattis ullamcorper. Quisque sit amet aliquam enim. Etiam eleifend nibh velit, sit amet pulvinar est pulvinar eget. Fusce egestas ornare tellus sagittis pulvinar. Nulla aliquam magna id sem consectetur tristique. Nullam auctor vestibulum ex eget laoreet. Quisque interdum quam in nisi rhoncus rutrum. </p>
</article>
<article>
<h2>This section is shorter than the Readmore minimum</h2>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
<article>
<h2>Portland Leggings</h2>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance</p>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut odio neque, dapibus a tincidunt sed, molestie in diam. Quisque quis vulputate tellus. Nulla nisl mi, rhoncus et magna cursus, euismod vehicula erat. Integer fringilla urna orci, at tempor nisi suscipit ut. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec non laoreet ex. Cras et purus augue. Donec a urna et leo malesuada laoreet. Duis tortor massa, fermentum et porta id, pharetra suscipit lorem. Donec molestie nunc nisi, sed faucibus turpis facilisis eget. Morbi eros mauris, fringilla in est a, vehicula tempus felis. Nullam sodales tincidunt turpis sed dapibus.</p>
<p> Proin efficitur, leo ac sagittis faucibus, elit purus consectetur dolor, et scelerisque orci neque a orci. Nullam ut congue libero, in ornare mi. Quisque mattis porttitor nulla non fermentum. Suspendisse euismod facilisis magna, eget interdum leo semper sed. Nullam pretium, nisl sit amet auctor rhoncus, velit ipsum ullamcorper turpis, nec feugiat mauris diam ac lorem. Cras hendrerit non eros id ultricies. Aenean sed felis purus. Sed commodo, enim sed aliquet egestas, nisl odio porta ante, ac euismod justo turpis in mauris. Ut lobortis augue ut ex scelerisque, ut lacinia libero sollicitudin. Pellentesque vestibulum ac tellus sit amet commodo. Phasellus eu nunc nibh. In porta metus sed pharetra aliquet. Etiam eu magna id erat accumsan pellentesque pulvinar eget erat.</p>
<p> Etiam vitae aliquam nisi. Aliquam vel suscipit felis. Donec non dapibus odio. Vivamus tincidunt mauris in tortor fermentum, a laoreet sem semper. Sed luctus vitae turpis vitae vulputate. Integer a libero orci. Morbi eu porttitor nisi, facilisis consectetur velit. Suspendisse sed facilisis velit. Proin rutrum ligula a purus mattis ullamcorper. Quisque sit amet aliquam enim. Etiam eleifend nibh velit, sit amet pulvinar est pulvinar eget. Fusce egestas ornare tellus sagittis pulvinar. Nulla aliquam magna id sem consectetur tristique. Nullam auctor vestibulum ex eget laoreet. Quisque interdum quam in nisi rhoncus rutrum. </p>
<p> Proin efficitur, leo ac sagittis faucibus, elit purus consectetur dolor, et scelerisque orci neque a orci. Nullam ut congue libero, in ornare mi. Quisque mattis porttitor nulla non fermentum. Suspendisse euismod facilisis magna, eget interdum leo semper sed. Nullam pretium, nisl sit amet auctor rhoncus, velit ipsum ullamcorper turpis, nec feugiat mauris diam ac lorem. Cras hendrerit non eros id ultricies. Aenean sed felis purus. Sed commodo, enim sed aliquet egestas, nisl odio porta ante, ac euismod justo turpis in mauris. Ut lobortis augue ut ex scelerisque, ut lacinia libero sollicitudin. Pellentesque vestibulum ac tellus sit amet commodo. Phasellus eu nunc nibh. In porta metus sed pharetra aliquet. Etiam eu magna id erat accumsan pellentesque pulvinar eget erat.</p>
<p> Etiam vitae aliquam nisi. Aliquam vel suscipit felis. Donec non dapibus odio. Vivamus tincidunt mauris in tortor fermentum, a laoreet sem semper. Sed luctus vitae turpis vitae vulputate. Integer a libero orci. Morbi eu porttitor nisi, facilisis consectetur velit. Suspendisse sed facilisis velit. Proin rutrum ligula a purus mattis ullamcorper. Quisque sit amet aliquam enim. Etiam eleifend nibh velit, sit amet pulvinar est pulvinar eget. Fusce egestas ornare tellus sagittis pulvinar. Nulla aliquam magna id sem consectetur tristique. Nullam auctor vestibulum ex eget laoreet. Quisque interdum quam in nisi rhoncus rutrum. </p>
</article>
</section>
</div>
EDIT 1: I added a white gradient to buttons to make it similar to your example. I forgot it, sorry.
Add this to your <head> tag:
<script type="text/javascript">
function moreInformation(){
document.getElementById("more-information").style.display = "block";
}
function evenMoreInformation(){
document.getElementById("even-more-information").style.display = "block";
}
function lessInformation(){
document.getElementById("more-information").style.display = "none";
document.getElementById("even-more-information").style.display = "none";
}
</script>
And add this to <body> tag:
This is some text and continues for ages...
<a onClick="moreInformation()" style="text-decoration:underline;cursor:pointer;">More information</a><br>
<br>
<div id="more-information" style="display:none">
This is some text and continues for ages...<br>
and it goes on and on and on...<br>
<a onClick="evenMoreInformation()" style="text-decoration:underline;cursor:pointer;">Even more information</a>
</div>
<br>
<div id="even-more-information" style="display:none">
This is some text and continues for ages...<br>
and it goes on and on and on...<br>
but not as long as you think.<br>
<a onClick="lessInformation()" style="text-decoration:underline;cursor:pointer;">Less information</a>
</div>
I hope understand you...
Create a function having arguments for collapsedHeight, moreLinkText, lessLinkText and other necessary configs;
function invokeReadMore(collapsedHeight, moreTxt, lessTxt, ...) {
//and make your call to $('.example').readMore
//with all the args received
}
Initially call that with your initial requirements (eg, 300, More Information")
Now, just like beforeToggle add a function for afterToggle (if it was a targeting expand) and call the function invokeReadMore from there with new requirements (eg 350, "Even More", "Less..") also you can maintain some flag that you are in next "Even More" view
Now, if your flag says that you are in "even more" then in afterToggle (if it was a targeting collapse) collapsed then, call the function invokeReadMore again with your initial parameters
Here (I just edited JS of your snippet) is a working example
var isExpandMode = false;
function invokeReadMore(collapsedHeight, speed, moreLinkTxt, lessLinkTxt) {
$('.example').readmore({
collapsedHeight: collapsedHeight,
speed: speed,
embedCSS: false,
moreLink: ''+ moreLinkTxt +'',
lessLink: ''+ lessLinkTxt +'',
beforeToggle: function(trigger, element, expanded) {
if (expanded === false) {
element.addClass('remove-after');
} else {
element.removeClass('remove-after');
}
},
afterToggle: function(trigger, element, expanded) {
if (expanded === false) {
if(isExpandMode===true) {
invokeReadMore(200, 1, 'More Information', 'Less Information')
isExpandMode = false;
}
} else {
if(isExpandMode===false) {
invokeReadMore(300, 500, 'Even More Information', 'Less Information')
isExpandMode = true;
}
}
}
});
}
invokeReadMore(200, 1, 'More Information', 'Less Information');
.example+[data-readmore-toggle],
.example[data-readmore] {
display: block;
}
.example[data-readmore]::after {
background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 85%);
bottom: 0;
content: '';
display: inline-block;
height: 250px;
position: absolute;
right: 0;
width: 100%;
}
.remove-after::after {
display: none !important;
}
[data-readmore-toggle] {
margin-left: 15px;
}
img {
float: right;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/readmore-js#2.1.0/readmore.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="example col-md-12">
<p>They say everything looks better with odd numbers of things. But sometimes I put even numbers—just to upset the critics. Don't be afraid to make these big decisions. Once you start, they sort of just make themselves. Now let's put some happy little
clouds in here. We can always carry this a step further. There's really no end to this. Think about a cloud. Just float around and be there. We want to use a lot pressure while using no pressure at all.</p>
<p>Look around, look at what we have. Beauty is everywhere, you only have to look to see it. That's the way I look when I get home late; black and blue. All you have to do is let your imagination go wild. We have a fantastic little sky!</p>
<p>All kinds of happy little splashes. We don't want to set these clouds on fire. I was blessed with a very steady hand; and it comes in very handy when you're doing these little delicate things. It looks so good, I might as well not stop. We need dark
in order to show light. I really recommend you use odorless thinner or your spouse is gonna run you right out into the yard and you'll be working by yourself.</p>
<img src="https://dummyimage.com/200x200/2d5cc2/fff" />
<p>Van Dyke Brown is a very nice brown, it's almost like a chocolate brown. We're trying to teach you a technique here and how to use it. This present moment is perfect simply due to the fact you're experiencing it.</p>
<p>If what you're doing doesn't make you happy - you're doing the wrong thing. We spend so much of our life looking - but never seeing. In this world, everything can be happy. Everyone is going to see things differently - and that's the way it should be.
And just raise cain.</p>
<p>There's nothing wrong with having a tree as a friend. Maybe there was an old trapper that lived out here and maybe one day he went to check his beaver traps, and maybe he fell into the river and drowned. Tree trunks grow however makes them happy.</p>
<p>Let your imagination be your guide. You could sit here for weeks with your one hair brush trying to do that - or you could do it with one stroke with an almighty brush. We wash our brush with odorless thinner. Every highlight needs it's own personal
shadow. Don't kill all your dark areas - you need them to show the light. Working it up and down, back and forth.</p>
<p>Don't forget to tell these special people in your life just how special they are to you. The only thing worse than yellow snow is green snow. That's why I paint - because I can create the kind of world I want - and I can make this world as happy as
I want it. Let's build an almighty mountain. You have to make almighty decisions when you're the creator.</p>
<p>We have a fantastic little sky! Everybody's different. Trees are different. Let them all be individuals. Just go out and talk to a tree. Make friends with it. Go out on a limb - that's where the fruit is. There are no mistakes. You can fix anything
that happens.</p>
<p>You have to make those little noises or it won't work. We have no limits to our world. We're only limited by our imagination. I want everbody to be happy. That's what it's all about.</p>
<p>Nice little clouds playing around in the sky. It's a super day, so why not make a beautiful sky? We spend so much of our life looking - but never seeing. The secret to doing anything is believing that you can do it. Anything that you believe you can
do strong enough, you can do. Anything. As long as you believe. Everything's not great in life, but we can still find beauty in it.</p>
<p>If you've been in Alaska less than a year you're a Cheechako. You don't have to be crazy to do this but it does help. I'm going to mix up a little color. We’ll use Van Dyke Brown, Permanent Red, and a little bit of Prussian Blue. And I will hypnotize
that just a little bit. Nothing's gonna make your husband or wife madder than coming home and having a snow-covered dinner.</p>
<p>There it is. Don't fiddle with it all day. No worries. No cares. Just float and wait for the wind to blow you around.</p>
<p>All you need to paint is a few tools, a little instruction, and a vision in your mind. Let's put a touch more of the magic here. Now let's put some happy little clouds in here. We'll lay all these little funky little things in there. But we're not there
yet, so we don't need to worry about it. All you have to learn here is how to have fun.</p>
</div>
Just add <br> tag at the end of texts for a blank.
Instead of using readmore.js why don't you create a custom one to make it easy to control. I've created a custom plugin for you, and it's awesome because you can use it on all of your posts on your page, without create a separate event for every function.
This is the complete code:
$(document).ready(function(){
$('div.post div.container').each(function(){
var Hval = $(this).height();
var Hval_P = $(this).parent().height();
if (Hval > Hval_P) {
$(this).parent().find('div#fade').css({'display':'block'});
$(this).parent().find('a#more').css({'display':'block'});
}
});
$('a#more').click(function(){
var Hval = $(this).parent().find('div.container').height();
var Hval_P = $(this).parent().height();
if (Hval > (Hval_P+500)) {
$(this).parent().css({'max-height':Hval_P+500});
var offset = $(this).offset().top - 150;
$([document.documentElement, document.body]).animate({
scrollTop: offset + 500
}, 250);
$(this).hide();
$(this).parent().find('a#evenmore').css({'display':'block'});
}else{
$(this).parent().css({'max-height':Hval-Hval_P});
$(this).hide();
$(this).parent().find('div#fade').css({'display':'none'});
$(this).parent().find('a#less').css({'display':'block'});
}
});
$('a#evenmore').click(function(){
var Hval = $(this).parent().find('div.container').height();
$(this).parent().css({'max-height':Hval});
var offset = $(this).offset().top - 150;
$([document.documentElement, document.body]).animate({
scrollTop: offset + 500
}, 250);
$(this).hide();
$(this).parent().find('div#fade').css({'display':'none'});
$(this).parent().find('a#less').css({'display':'block'});
});
$('a#less').click(function(){
$(this).parent().css({'max-height':'300px'});
var post_P = $(this).parent().offset().top;
$([document.documentElement, document.body]).animate({
scrollTop: post_P
}, 250);
$(this).hide();
$(this).parent().find('div#fade').css({'display':'block'});
$(this).parent().find('a#more').css({'display':'block'});
});
});
.post{
width: 500px;
height: auto;
max-height: 300px; /*whatever you want*/
margin: auto;
margin-bottom: 20px;
padding: 5px 30px 20px 20px;
position: relative;
overflow: hidden;
border: 1px solid rgba(0,0,0,.1);
font-family: sans-serif;
transition: all 250ms linear 0ms;
}
.container{
width: 500px;
height: auto;
margin: auto;
padding: 0px;
position: relative;
overflow: hidden;
}
.post div#fade{
width: 100%;
height: 150px;
margin: auto;
padding: 0px;
position: absolute;
bottom: 0px;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 85%);
z-index: 1;
display: none;
}
.post a#more{
position: absolute;
bottom: 10px;
right: 20px;
text-decoration: none;
color: #4bbfee;
z-index: 2;
display: none;
}
.post a#less{
position: absolute;
bottom: 10px;
right: 20px;
text-decoration: none;
color: #4bbfee;
z-index: 2;
display: none;
}
.post a#evenmore{
position: absolute;
bottom: 10px;
right: 20px;
text-decoration: none;
color: #4bbfee;
z-index: 2;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="post">
<div class="container">
<p>Look around, look at what we have. Beauty is everywhere, you only have to look to see it. That's the way I look when I get home late; black and blue. All you have to do is let your imagination go wild. We have a fantastic little sky!</p>
<p>All kinds of happy little splashes. We don't want to set these clouds on fire. I was blessed with a very steady hand; and it comes in very handy when you're doing these little delicate things. It looks so good, I might as well not stop. We need dark
in order to show light. I really recommend you use odorless thinner or your spouse is gonna run you right out into the yard and you'll be working by yourself.</p>
<img src="https://dummyimage.com/200x200/2d5cc2/fff" />
<p>Van Dyke Brown is a very nice brown, it's almost like a chocolate brown. We're trying to teach you a technique here and how to use it. This present moment is perfect simply due to the fact you're experiencing it.</p>
<p>If what you're doing doesn't make you happy - you're doing the wrong thing. We spend so much of our life looking - but never seeing. In this world, everything can be happy. Everyone is going to see things differently - and that's the way it should be.
And just raise cain.</p>
<p>There's nothing wrong with having a tree as a friend. Maybe there was an old trapper that lived out here and maybe one day he went to check his beaver traps, and maybe he fell into the river and drowned. Tree trunks grow however makes them happy.</p>
<p>Let your imagination be your guide. You could sit here for weeks with your one hair brush trying to do that - or you could do it with one stroke with an almighty brush. We wash our brush with odorless thinner. Every highlight needs it's own personal
shadow. Don't kill all your dark areas - you need them to show the light. Working it up and down, back and forth.</p>
<p>Don't forget to tell these special people in your life just how special they are to you. The only thing worse than yellow snow is green snow. That's why I paint - because I can create the kind of world I want - and I can make this world as happy as
I want it. Let's build an almighty mountain. You have to make almighty decisions when you're the creator.</p>
<p>We have a fantastic little sky! Everybody's different. Trees are different. Let them all be individuals. Just go out and talk to a tree. Make friends with it. Go out on a limb - that's where the fruit is. There are no mistakes. You can fix anything
that happens.</p>
<p>You have to make those little noises or it won't work. We have no limits to our world. We're only limited by our imagination. I want everbody to be happy. That's what it's all about.</p>
</div>
<div id="fade"></div>
More information
Less information
Even more information
</div>
You could nest the articles inside each other like this:
Big article
|
| Original content
| |
| | Small article
| | |
| | | Original content
| | | | "blah blah blah"
| | | |
| | | Read more
| | | | "more blahs"
| | | |
| | | End
| | |
| | End
| |
| Read more
| | "even more blahs"
| |
| End
|
End
Here are some key points:
Do not show Big article "Read more" link until the small article has been expanded
Do not show the Small article "Read less" link
It is best to close both articles in succession(which they might). If they don't, you can use a setTimeout() function to delay the closing of the Small article

gradient border with javascript

I need to set border color for a round div with javascript. User picks two colors (red and blue, for example) and the border becomes red on top and blue on bottom. But from the sides the border should change from red to blue, vice versa. In other words, I need to make vertical gradient for div's borders.
I can make it with just css, but since I don't know which colors would be chosen, I need javascript to do that for me.
A pure-javascript solution to do just that. Note that you need to do a funky getCssValuePrefix to determine which browser, thus calling the appropriate linear-gradient function.
var clicky = document.getElementById("changeButton"),
color1 = document.getElementById("color1"),
color2 = document.getElementById("color2"),
changeDiv = document.getElementsByClassName("foo")[0];
clicky.addEventListener("click", function(evt){
evt.preventDefault();
if (color1.value && color2.value) {
var myGradientString = getCssValuePrefix()+"linear-gradient("+color1.value+", "+color2.value+")";
changeDiv.style.background = myGradientString;
}
});
function getCssValuePrefix()
{
var rtrnVal = '';//default to standard syntax
var prefixes = ['-o-', '-ms-', '-moz-', '-webkit-'];
// Create a temporary DOM object for testing
var dom = document.createElement('div');
for (var i = 0; i < prefixes.length; i++)
{
// Attempt to set the style
dom.style.background = prefixes[i] + 'linear-gradient(#000000, #ffffff)';
// Detect if the style was successfully set
if (dom.style.background)
{
rtrnVal = prefixes[i];
}
}
dom = null;
delete dom;
return rtrnVal;
}
.foo {
border: 1px solid black;
background-image: linear-gradient(red, blue);
}
label {
display: block;
}
<div class="foo">
<p>Vivamus suscipit tortor eget felis porttitor volutpat. Sed porttitor lectus nibh. Donec rutrum congue leo eget malesuada. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur aliquet quam id dui posuere blandit. Cras ultricies ligula sed magna dictum porta. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Sed porttitor lectus nibh.</p>
</div>
<label for="color1">Color 1: <input type="text" name="color1" id="color1" value="#ee3"></label>
<label for="color2">Color 2: <input type="text" name="color2" id="color2" value="#336"></label>
<button id="changeButton">Make it so!</button>
I think this is the best solution working exactly how you want :) I have tasted that on Chrome, MF and Opera. Paste my demo to empty html file. Good luck!
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
#test
{
width: 300px;
height: 300px;
border-width: 3px;
border-style: solid;
border-image:
linear-gradient(blue, red) 1;
}
</style>
<body>
<input id="first" type="text">
<input id="second" type="text">
<input type="submit" onclick="changeColor()">
<div id="test"> </div>
<script>
var one = document.getElementById("first");
var two = document.getElementById("second");
var testDiv = document.getElementById("test");
function changeColor()
{
testDiv.style.borderImage = "linear-gradient(" + one.value + ", " + two.value + ") 1 ";
}
</script>
</body>
</html>

Auto fill divs with a large amount of content

I hava a large amount of content which make up with html tag or pure text.
And I have several divs.
How to autofill the remain content to other divs when the first div cannot contain all contents.
Very thankful if any suggestion provided. :)
--- Update ---
Actually, I'm making my own blog which designed like an opened book(a left page and a right page) containing all posts.
Each post is written with a markdown file.Initially, one post has only a left page.
When the mardown file parsed to html code, I will try insert the result html code into 'left page' of my book-like post.
Obviously, If the result html code is huge, one 'left page' is not possible contain all content.On this occasion, my blog will automatically create a new 'right page'(or another 'left page' when the 'right page' is neither enough) which the remain content should autofilled in;
What I'm asking is how I can detect if my 'left page' div is not enough containing the all result html code.And how can I cut the remain content and insert into 'right page'.I totally have no idea how to reach this request.
So, If someone already did this before, maybe you can give me some tips.I'll be very thankful
EDITED again:
Ok I will make this out of pure CSS. What you are asking me in the comments is a normal post(on the left side) and if the left sided post is unable to hold all of its content then a copy of the post is revealed on the right side that can hold all of the original content of the old left side.
This is what I am understanding from the information you have given me.
#media (min-width: 601px) {
#leftSide {
float: left;
}
/*THIS IS ON THE LEFT SIDE*/
h2 {
font-size: 2.5em;
}
p {
font-size: 1.5em;
}
#rightSide {
display: none;
}
}
#media (max-width: 600px) {
#rightSide {
display: block;
float: right;
}
/*THIS IS ON THE RIGHT SIDE*/
h2 {
font-size: 1.5em;
}
p {
font-size: 1em;
}
#leftSide {
display: none;
}
<div id="leftSide">
<h2>Post 1</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post 2</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post 3</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
</div>
<div id="rightSide">
<h2>Post #1</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post #2</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post #3</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
</div>
Here an answer to a question like yours.
I think you could divide your text in segments, each of a certain number of characters but without cutting any word.
Then you could put the first segment in the first page, the second on second page and so on...
The main problem is to trim yourBigText without cut any words, and here the solution I found on the other post helps.
var yourBigText = "CULIACAN, Mexico The Joaquin El Chapo Guzman story could hardly have seemed more unbelievable, with its multiple prison breaks, endless sewers and tunnels, outlandish sums of money and feverish manhunts. And then Sean Penn entered the story.While Guzman was the world's most-wanted fugitive, dodging Mexican military operations and U.S. Drug Enforcement Administration surveillance, he was secretly meeting with the Hollywood movie star in an undisclosed Mexican hideout and has now provided what appears to be the first public interview of his drug-running career, published Saturday by Rolling Stone."; //replace with your big text.
var cutLength;
var remainText = yourBigText.length;
var maxLength = 60;
while (remainText != 0) {
if (remainText >= maxLength) {
var trimmedText = yourBigText.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedText = trimmedText.substr(0, Math.min(trimmedText.length, trimmedText.lastIndexOf(" ")));
//subtract from the original big string the length of the trimmedText
cutLength = trimmedText.length;
if (yourBigText.length > cutLength) {
yourBigText = yourBigText.slice(cutLength);
}
document.write(trimmedText);
document.write('<br>');
} else {
document.write(yourBigText);
exit();
}
remainText = yourBigText.length;
}
I hope this helps.

How to change color of the selected text dynamically on click of button?

I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..
var pinktext = "#cc0099";
document.execCommand("ForeColor", false, pinktext);
document.getElementById("change_color").onclick = function() {
// Get Selection
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Set design mode to on
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Colorize text
document.execCommand("ForeColor", false, "red");
// Set design mode to off
document.designMode = "off";
}
<span id="content" contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet odio eu magna mattis vehicula. Duis egestas fermentum leo. Nunc eget dapibus eros, id egestas magna. Fusce non arcu non quam laoreet porttitor non non dui. Ut elit nisl, facilisis id hendrerit et, maximus at nunc. Fusce at consequat massa. Curabitur fermentum odio risus, vel egestas ligula rhoncus id. Nam pulvinar mollis consectetur. Aenean dictum ut tellus id fringilla. Maecenas rutrum ultrices leo, sed tincidunt massa tempus ac. Suspendisse potenti. Aenean eu tempus nisl.
</span>
<br/><br/>
<button id="change_color">Change Selected Text Color</button>
Try this
mark up
<p>
I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..
</p>
Script
<script type="text/javascript" >
$(document).ready(function(){
$("p").on("mouseup" , function(){
selectedtext = selectedText();
var replceText = "<span style='background:#cccccc' >"+selectedtext+"</span>";
var gethtmlText = $(this).text();
var replcedtext = gethtmlText.replace(selectedtext , replceText);
$(this).html(replcedtext)
});
});
function selectedText(){
if(document.getSelection){
return document.getSelection();
}
else if(document.selection){
return document.selection.createRange().text;
}
}
</script>
Check DEMO here http://jsfiddle.net/yeyene/GYuBv/7/
Select text, and click button to change selected text color.
function selectHTML() {
try {
if (window.ActiveXObject) {
var c = document.selection.createRange();
return c.htmlText;
}
var nNd = document.createElement("span");
var w = getSelection().getRangeAt(0);
w.surroundContents(nNd);
return nNd.innerHTML;
} catch (e) {
if (window.ActiveXObject) {
return document.selection.createRange();
} else {
return getSelection();
}
}
}
$(function() {
$('#changeColor').click( function() {
var mytext = selectHTML();
// you can modify any css style here...
$('span').css({"color":"red"});
});
});
The following code works when you select a text or word, the color will change:
<style>
::selection {
color:blue;
background:yellow;
font-size:14px;
}
::-moz-selection {
color:blue;
background:yellow;
font-size:14px;
}
</style>
I've created a pretty short fiddle that demonstrates the use of jQuery to change the color of a piece of text.
HTML:
<p id="paragraph">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium?</p>
<button id="colorChanger">This Button changes the text color of the paragraph.</button>
CSS:
#paragraph {
color: green;
}
JavaScript:
$('#colorChanger').click(function() {
$('#paragraph').css('color','black');
});
The code above shows that with any text you can change the color using jQuery's css method. Additionally, I used #paragraph to access the paragraph; however, you can use nth-child through jQuery, you can cycle through the children of a container using a loop and checking for the right one then using the css method from jQuery. These are just a few of the ways to change the color of a piece of text.

Automatically close all the other <details> tags after opening a specific <details> tag

Here is my code.
<details>
<summary>1</summary>
Demo 1
</details>
<details>
<summary>2</summary>
Demo 2
</details>
<details>
<summary>3</summary>
Demo 3
</details>
What I want to do is -- if the details of any single <details> tag is open and I open/view another <details> tag, then the earlier one should close/hide/minimize.
How can this be achieved?
I'm aware the <details> tag is not supported in IE or Edge.
Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.
// Fetch all the details element.
const details = document.querySelectorAll("details");
// Add the onclick listeners.
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
// Close all the details that are not targetDetail.
details.forEach((detail) => {
if (detail !== targetDetail) {
detail.removeAttribute("open");
}
});
});
});
<details>
<summary>1</summary>Demo 1
</details>
<details>
<summary>2</summary>Demo 2
</details>
<details>
<summary>3</summary>Demo 3
</details>
Whao ! before my posting...
No one has ndicated that <details> elements work with the toggle event?
-- instead of click
-- and the toggle event also works with keyboard interaction.
No one has indicated that the open attribute is a boolean,
make it to true or false, don't do a .removeAttr("open") ;)
the doc : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
const All_Details = document.querySelectorAll('details');
All_Details.forEach(deet=>{
deet.addEventListener('toggle', toggleOpenOneOnly)
})
function toggleOpenOneOnly(e) {
if (this.open) {
All_Details.forEach(deet=>{
if (deet!=this && deet.open) deet.open = false
});
}
}
<details>
<summary>1</summary>
Demo 1
</details>
<details>
<summary>2</summary>
Demo 2
</details>
<details>
<summary>3</summary>
Demo 3
</details>
The same thing in a shorter way with ES10? => .ontoggle direct event method
document.querySelectorAll('details').forEach((D,_,A)=>{
D.ontoggle =_=>{ if(D.open) A.forEach(d =>{ if(d!=D) d.open=false })}
})
See it in action : ( Plus some CSS improvements ;)
document.querySelectorAll('details').forEach((D,_,A)=>{
D.ontoggle =_=>{ if(D.open) A.forEach(d =>{ if(d!=D) d.open=false })}
})
details {
border : 1px solid lightgrey;
width : 24em;
padding : 0 .6em;
border-radius : .3em;
margin : .3em;
}
details > summary {
font-weight : bold;
margin : 0em -.6em;
list-style : none;
display : block;
padding : .5em;
}
details[open] {
padding-bottom : .6em;
}
details[open] summary {
border-bottom : 1px solid #aaa;
margin-bottom : .6em ;
}
summary::marker {
display : none;
}
summary::-webkit-details-marker {
display : none;
}
summary::after {
display : block;
float : right;
content : '\1405';
cursor : pointer;
transition : 180ms;
transform : rotate(90deg);
}
details[open] > summary:after {
transform : rotate(-90deg);
}
summary:hover {
outline : none;
background-color : whitesmoke;
}
<details>
<summary>Lorem ipsum one</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
<details>
<summary>Lorem ipsum two</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
<details>
<summary>Lorem ipsum three</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
Same concept, just a bit shorter.
$('details').click(function (event) {
$('details').not(this).removeAttr("open");
});
Yet another answer for those who don't want to use obsolete jQuery and those who loves functional javascript
[...document.getElementsByTagName("details")].forEach( (D,_,A) =>
D.addEventListener("toggle", E =>
D.open && A.forEach(d =>
d!=E.target && (d.open=false)
)
)
)
<details>
<summary>1</summary>Demo 1
</details>
<details>
<summary>2</summary>Demo 2
</details>
<details>
<summary>3</summary>Demo 3
</details>
Better late than never...
I would like to point out this quote from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
Note: You have to remove this attribute entirely to make the details hidden. open="false" makes the details visible because this attribute is Boolean.
(Read the note appended right at the end of the attributes paragraph.)
Apparently, in this case boolean means existing or not and not settable to true or false...
Browser magic going further!
I have come up with a solution. Please correct me if this is a wrong approach.
I added an onclick event to all of the details tag and made a function thisindex(this) which returns the index of the clicked tag and the obtained index number is then passed to the another function closeAll() which minimizes/closes all the other open tags except for one whose index matches with what we obtained earlier.
Here is the code.
function thisindex(elm){
var nodes = elm.parentNode.childNodes, node;
var i = 0, count = i;
while( (node=nodes.item(i++)) && node!=elm )
if( node.nodeType==1 ) count++;
return count;
}
function closeAll(index){
var len = document.getElementsByTagName("details").length;
for(var i=0; i<len; i++){
if(i != index){
document.getElementsByTagName("details")[i].removeAttribute("open");
}
}
}
<details onclick="closeAll(thisindex(this));">
<summary>1</summary>Demo 1
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 2
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 3
</details>
Same with the help of jQuery
$(document).ready(function(){
$('details').click(function (event) {
var index = $('details').index(this);
var len = $("details").length;
for(var i=0; i<len; i++){
if(i != index){
$("details")[i].removeAttribute("open");
}
}
});
});
Kindly suggest me a better approach if this not up to the mark.
Modification for use with polyfill jquery-details.js [Edge]
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
const details = Array.from(document.querySelectorAll("details"));
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
details.forEach((detail) => {
if (detail !== targetDetail) {
if(isEdge) {
detail.className = detail.className.replace(/\bopen\b/g,"");
detail.open = false;
detail.querySelector("summary").setAttribute("aria-expanded","false");
var chil = detail.querySelectorAll("details > *");
for(var j = 0; j < chil.length; j++) {
if(chil[j].tagName != "SUMMARY") {
chil[j].style.display = "none";
}
}
} else {
detail.removeAttribute("open");
}
}
});
});
});**strong text**
Solutions offered appear less than clear to me.
Consider this instead:
const closeDetails = event => {
const targetDetails = event.target.parentElement;
const openDetails = document.querySelectorAll('details[open]');
for (const details of openDetails) {
if (details === targetDetails) continue;
details.removeAttribute('open');
}
};
const summaries = document.querySelectorAll('summary');
for (const summary of summaries) {
summary.addEventListener('click', closeDetails);
}
This production version follows the same thought process but is extended to cater for multiple accordions, and reduces the number of event listeners:
https://codepen.io/2kool2/pen/poOgxKb

Categories

Resources