React equivalent of toggleClass/addClass/removeClass - javascript

I'm in the process of learning React and am trying to achieve something that I was able to do quite easily before with jQuery. I want to do this purely in React though and have found a solution that gets me part of the way there but not entirely...
Basically I have a div that houses text. By default I have a class that sets a height to that element, I then have another class that removes the height restriction allowing for all the content to be visible.
In jQuery it would have been a simple one or two lines to remove the restricted height class and add on my non-restricted one.
Here is my React code thus far:
import React, { Component } from 'react'
import arrow from "./img/down-arrow.png";
class UserGen extends Component {
constructor(props) {
super(props);
this.state = {
active: false
}
}
handleClick() {
this.setState({
active: !this.state.active
})
}
render() {
return (
<div className="user-generated col-md-8 offset-md-2 col-sm-12">
<div onClick={this.handleClick.bind(this)} className= {this.state.active ? " user-generated-inner ug-expanded" : " user-generated-inner ug-collapsed"}>
<h4>User Generated Summary</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum tempus auctor magna in fermentum. Sed et arcu vitae sem elementum consequat. Sed rhoncus vestibulum risus, eu tempor diam faucibus a. In efficitur accumsan scelerisque. Ut convallis nulla nec eros consectetur, ut consectetur tellus accumsan. Aenean quam tortor, consequat quis ligula quis, posuere laoreet risus. Nam id cursus ligula, et sagittis libero. Nam id dui vel diam eleifend accumsan. Donec aliquet, enim vitae dapibus maximus, turpis ante cursus enim, iaculis mollis nibh quam lacinia magna. Curabitur metus lorem, posuere blandit tortor eget, molestie viverra purus. Mauris in justo eget velit suscipit convallis. Aliquam placerat mi nec erat venenatis tincidunt vel vitae ligula. Nulla mattis justo id lacus posuere, in fringilla ex commodo. Ut at sem ligula.</p>
<p>Duis eu diam ut urna egestas interdum. Integer sapien ligula, ultricies ac lobortis id, accumsan quis nisl. Donec pharetra condimentum mattis. Aliquam pretium lacinia ultricies. Maecenas vehicula nisi velit, dignissim consectetur nulla molestie ut. Suspendisse dictum porta semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras condimentum rhoncus volutpat. Fusce placerat, metus id finibus maximus, augue tellus hendrerit lacus, quis maximus magna erat et nisl. Aenean non leo metus. Suspendisse potenti. Maecenas sit amet lobortis nunc, ut vehicula tortor. Duis maximus est vel tortor vulputate dignissim. Integer ac laoreet risus, et ultricies mi.</p>
<p>Mauris est lorem, lobortis id accumsan faucibus, aliquet in ante. In porttitor nisl sit amet risus feugiat maximus. Mauris commodo dignissim fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sodales, nunc et dictum placerat, mi lacus placerat enim, nec faucibus sapien enim vel felis. Fusce ultricies condimentum mauris, eget accumsan risus dictum id. Mauris tincidunt, ipsum at suscipit faucibus, tortor ligula volutpat ante, a cursus sapien lacus non sem. Maecenas consectetur, felis et scelerisque laoreet, turpis turpis gravida turpis, eget vestibulum magna tellus et ex. Mauris dignissim lorem non dui ornare ullamcorper. Mauris interdum bibendum augue. Proin egestas laoreet sapien nec sodales.</p>
</div>
<div className="expand"><p>Read More<span className="expand-arrow"><img src={arrow} alt="arrow for the read more" /></span></p></div>
</div>
);
}
}
export default UserGen
This works... but I've only been able to figure out how to get this running if it's the div housing the content that I'm clicking on.
Ideally I want to be able to fire the same onClick function from my "expand" class.
Any help is greatly appreciated, as is any constructive feedback on how this code looks.

Generally your code looks fine and you're almost there. You just need to add the same handleClick method, which I renamed to toggleActive, to the div.expanded as its onClick prop. This will also trigger the same action.
import React, { Component } from "react";
import arrow from "./img/down-arrow.png";
class UserGen extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
};
}
toggleActive = () => {
this.setState({
active: !this.state.active,
});
};
render() {
const { active } = this.state;
const containerClass = `user-generated-inner ug-${
active ? "expanded" : "collapsed"
}`;
return (
<div className="user-generated col-md-8 offset-md-2 col-sm-12">
<div onClick={this.toggleActive} className={containerClass}>
<h4>User Generated Summary</h4>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum
tempus auctor magna in fermentum. Sed et arcu vitae sem elementum
consequat. Sed rhoncus vestibulum risus, eu tempor diam faucibus a.
In efficitur accumsan scelerisque. Ut convallis nulla nec eros
consectetur, ut consectetur tellus accumsan. Aenean quam tortor,
consequat quis ligula quis, posuere laoreet risus. Nam id cursus
ligula, et sagittis libero. Nam id dui vel diam eleifend accumsan.
Donec aliquet, enim vitae dapibus maximus, turpis ante cursus enim,
iaculis mollis nibh quam lacinia magna. Curabitur metus lorem,
posuere blandit tortor eget, molestie viverra purus. Mauris in justo
eget velit suscipit convallis. Aliquam placerat mi nec erat
venenatis tincidunt vel vitae ligula. Nulla mattis justo id lacus
posuere, in fringilla ex commodo. Ut at sem ligula.
</p>
<p>
Duis eu diam ut urna egestas interdum. Integer sapien ligula,
ultricies ac lobortis id, accumsan quis nisl. Donec pharetra
condimentum mattis. Aliquam pretium lacinia ultricies. Maecenas
vehicula nisi velit, dignissim consectetur nulla molestie ut.
Suspendisse dictum porta semper. Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Cras condimentum rhoncus volutpat.
Fusce placerat, metus id finibus maximus, augue tellus hendrerit
lacus, quis maximus magna erat et nisl. Aenean non leo metus.
Suspendisse potenti. Maecenas sit amet lobortis nunc, ut vehicula
tortor. Duis maximus est vel tortor vulputate dignissim. Integer ac
laoreet risus, et ultricies mi.
</p>
<p>
Mauris est lorem, lobortis id accumsan faucibus, aliquet in ante. In
porttitor nisl sit amet risus feugiat maximus. Mauris commodo
dignissim fringilla. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Fusce sodales, nunc et dictum placerat, mi lacus
placerat enim, nec faucibus sapien enim vel felis. Fusce ultricies
condimentum mauris, eget accumsan risus dictum id. Mauris tincidunt,
ipsum at suscipit faucibus, tortor ligula volutpat ante, a cursus
sapien lacus non sem. Maecenas consectetur, felis et scelerisque
laoreet, turpis turpis gravida turpis, eget vestibulum magna tellus
et ex. Mauris dignissim lorem non dui ornare ullamcorper. Mauris
interdum bibendum augue. Proin egestas laoreet sapien nec sodales.
</p>
</div>
<div className="expand" onClick={this.toggleActive}>
<p>
Read More
<span className="expand-arrow">
<img src={arrow} alt="arrow for the read more" />
</span>
</p>
</div>
</div>
);
}
}
export default UserGen;
If you wish to only expand and not collapse on the div.expanded you need to create a new function that only sets active in your state to true.
expand = () => {
this.setState({ active: true });
}
Hope this helps!
EDIT: Trying to answer the question in the comment section.
(Needed to be here, as the text would have been too long.)
I'm not sure if I understood the question. However, I'm going to try to answer: Your component UserGen has an internal state which in this case consists only of the boolean active. Now in your render method you're doing specific things based on the current value of boolean active of the state. The render method doesn't care where the state change came from, it simply takes the state and does what you told it to do.
To demonstrate this on another level, you could even add your components setState method to the window object and change the state from your dev tools, without clicking on any element on the page. The component would still simply render whatever you told it to depending on the current state.
// (...)
constructor(props) {
super(props);
this.state = {
active: false,
};
// Do this only for demonstration purposes, do not ship this
window.__userGenSetState = this.setState;
}
Now in your dev tools simply call __userGenSetState({ active: true }) or __userGenSetState({ active: false }) and you'll see that the render method doesn't care where the state change came from.

I think you can achieve what you want to do with using React Ref's.Here is a official documentation for how to implemet them.
https://tr.reactjs.org/docs/forwarding-refs.html

Related

vuejs - i18n : translate pieces of text stored in database

I have a very long text stored in database and i want to translate a piece dynamically.
for exemple i want to translate only "Donec venenatis posuere" of this text how can i do this ?
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec venenatis posuere sapien nec bibendum. Vestibulum sagittis efficitur lorem vitae consectetur. Etiam nisl purus, facilisis et scelerisque convallis, vehicula eget ex. Cras tempor, libero et dapibus laoreet, justo massa mattis purus, eu fermentum lectus elit vitae mi. Maecenas feugiat sed tortor sed tincidunt. Suspendisse potenti. Sed aliquet neque nulla, nec finibus lacus iaculis faucibus. Integer non ante mattis, ornare sem eget, consectetur dolor. Integer nec diam sed ante interdum convallis. Sed porta neque sed mattis gravida. Nam rutrum ac erat a facilisis. Quisque dignissim commodo enim, quis efficitur ante tincidunt in. Nunc pellentesque, mauris sit amet porta aliquet, magna elit ultrices lectus, at cursus arcu ligula non enim. Aliquam erat volutpat. Aliquam eget interdum mauris. Pellentesque varius purus sit amet ex venenatis cursus. "

Does window.find() work across <p> elements or line breaks?

I'm trying to use window.find() in JavaScript to find and select text across elements. Overall it works as expected, except across <p> elements (or line breaks?).
Here's my simplified HTML:
findText("first with style"); // true
findText("second"); // true
findText("third"); // true
findText("second\nthird"); // false
findText("second\n\nthird"); // false
findText("second\rthird"); // false
findText("second\r\nthird"); // false
findText("second<br>third"); // false
findText("second</p><p>third"); // false
findText("second
third"); // false
function findText(needle) {
console.log(window.find(needle));
}
.as-console-wrapper{ max-height:75px !important; }
<p>first<b> with style</b></p>
<p>second</p>
<p>third</p>
Here's a JS fiddle.
What am I missing?
I don't think any browser allows doing multiline search with their native search feature, so it's normal the DOM API doesn't either, since it's supposed to more or less mirror that feature.
If all you want to do is to check if the given text is present in the current visible text, you can get the document's innerText which will return only the visible text (here "visible" means the ones that are rendered, not necessarily the ones that are in screen).
const text = document.documentElement.innerText;
const toFind = "orci.\n\nPhasellus"; // end of first paragraph + start of second.
console.log(text.includes(toFind));
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed malesuada, massa nec elementum imperdiet, enim arcu fringilla purus, ac bibendum massa augue nec odio. Donec vel hendrerit ligula. Maecenas ante dolor, faucibus tristique commodo non, sollicitudin
at augue. In lobortis quis est a mattis. Aenean blandit lorem at porta ultrices. Nullam sit amet mauris a justo congue iaculis. Duis urna velit, luctus vel tempus quis, consequat id ex. Etiam accumsan urna ac imperdiet gravida. Etiam gravida rhoncus
quam sit amet placerat. In tincidunt lorem non lacus semper hendrerit. Phasellus nec ultrices orci.
</p>
<p>
Phasellus sit amet porttitor leo. Phasellus ut eleifend nulla. Morbi luctus odio quis risus aliquam fermentum. Aenean ultrices tortor leo, eu fermentum tortor tincidunt in. Maecenas sodales nisl erat, nec porta tortor mollis non. Donec vulputate non quam
imperdiet ornare. Integer ex mauris, hendrerit in est sed, sagittis lacinia nulla. Curabitur efficitur dui et neque condimentum, eu lacinia nisi rutrum.
</p>
<p>
Ut vel lorem id justo sodales venenatis. Vestibulum nec mattis risus. Ut a imperdiet lacus, eget molestie dolor. Sed nisl diam, facilisis a nunc non, faucibus suscipit diam. Quisque aliquet, eros sed sodales cursus, ex metus vulputate ante, sagittis dapibus
leo diam sed ligula. Fusce felis nulla, euismod in facilisis vel, viverra sed eros. Praesent ut diam quis nunc ultrices dignissim et vitae ligula. Donec quam orci, consequat eget leo sit amet, fringilla tempus leo. Nullam felis enim, sodales non lectus
ut, pretium tincidunt felis. Sed eget odio sit amet nunc consequat vulputate. Vivamus nisl nisl, condimentum vitae malesuada non, tempus ac metus. Nulla placerat arcu eu risus feugiat, efficitur semper diam fringilla. Curabitur et blandit felis. Curabitur
vel eleifend mi.
</p>
<p>
Maecenas tincidunt mi vestibulum nisi aliquet, at rhoncus mi tristique. Nullam sagittis sed dolor ut aliquet. Sed neque nunc, pulvinar vel ornare id, convallis ut nulla. Integer rhoncus velit non pulvinar commodo. Praesent finibus libero ante, eget venenatis
augue dignissim id. Nam id odio id ante maximus blandit vel nec purus. Sed eleifend leo ut commodo maximus. Nam pretium a mauris a scelerisque.
</p>
<p>
Duis laoreet lorem a nibh dapibus sodales. Curabitur ac orci scelerisque lorem maximus blandit nec ut leo. Nulla feugiat maximus congue. Proin velit leo, suscipit et mollis eu, tempor non eros. Morbi nec mi non lectus auctor fermentum vitae at lectus.
Sed ut massa sapien. Vivamus eu ipsum quis ante mollis volutpat at ac ipsum. Vivamus ut est sem. Quisque eget nulla posuere sapien rutrum ullamcorper. Donec porta nisl quis quam dignissim elementum sit amet ut turpis. Suspendisse ullamcorper non sapien
vitae faucibus. Praesent mollis bibendum pretium. Donec auctor lectus nec urna tincidunt egestas vitae vel quam. Sed a neque eleifend, elementum metus quis, sagittis diam. Pellentesque id purus sed nulla euismod tincidunt.
</p>
</div>
If you also need to select the text, you might be able to do so with the Selection API and walking over every node to find where the match was, but that will be quite tedious to build that, so I leave it as an exercise for now.
Maximum you can do is to query for elements and select in between:
findText("first with style"); // true
findText("second"); // true
findText("third"); // true
findMultiple("body p:nth-child(2)","body p:nth-child(4)"); // true
function findText(needle){
console.log(window.find(needle));
}
function findMultiple(start,end){
var range = document.createRange();
var root_node = document.body;
range.setStart(root_node.querySelector(start).firstChild, 0);
range.setEnd(root_node.querySelector(end).firstChild, root_node.querySelector(end).innerText.length);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
<p>first<b> with style</b></p>
<p>second</p>
<p>middle</p>
<p>third</p>
You could also querySelect all elements and check if contains your text, store that element then run the function. But that can be slower, depends.
Please refer this solution - JavaScript window.find doesn't work absolutely
Below solution will give us the boolean value based on the matches of string irrespective of the lines.
I hope you're looking for the below one.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p>first<b> with style</b></p>
<p>second</p>
<p>third</p>
<p id="demo"></p>
<script>
let name = window.name;
document.getElementById("demo").innerHTML = "Result of matching: "+ containsStr$("second third");
function containsStr$(str) {
return $('body:contains("'+str+'")').length > 0;
}
</script>
</body>

Is there any way to run asscroll package in react project?

I was searching a few libraries for scroll animations and I found a very good npm package called #ashthornton/asscroll and I wanted to use the same on my react project.
But I am not been able to implement the same. It's not working the way it should. Can someone help me implement the same package in react?
Here, are the links for asscroll package and a Codesandbox for anyone to give it a try.
In order to run it with react you need to initialize ASScroll inside useEffect and also make sure to point out which div element is asscroll-container.
Since this is a little different in react you need to add to the div asscroll-container="true" (keep in mind that true has to be passed as string).
I have added this library to my codesandbox as you can see here
import React from "react";
import ASScroll from "#ashthornton/asscroll";
import "./styles.css";
class App extends React.Component {
componentDidMount() {
const pageEl = document.querySelector(".page");
this.asscroll = new ASScroll({
// containerElement: '.my-container',
scrollElements: pageEl,
ease: 0.1,
touchEase: 1,
customScrollbar: true,
scrollbarEl: ".my-scrollbar",
scrollbarHandleEl: ".my-scrollbar-handle",
scrollbarStyles: true,
disableNativeScrollbar: true,
touchScrollType: "scrollTop",
disableRaf: true,
disableResize: true,
limitLerpRate: true,
blockScrollClass: ".asscroll-block"
});
this.asscroll.enable();
requestAnimationFrame(this.onRaf);
}
onRaf = () => {
this.asscroll.update();
requestAnimationFrame(this.onRaf);
};
render() {
return (
<div asscroll-container="true">
<div class="page">
<img
src="https://raw.githubusercontent.com/ashthornton-gc/asscroll/master/docs/banner.jpg"
alt=""
/>
<div class="content">
<h1 class="title">
<span>A</span>
<span>S</span>
<span>S</span>
<span>C</span>
<span>R</span>
<span>O</span>
<span>L</span>
<span>L</span>
<span>🍑</span>
</h1>
<div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
ornare quis nibh eget convallis. Nam aliquam tempus dolor, at
blandit elit vulputate eu. Mauris iaculis sem at nulla euismod
auctor. Duis dui risus, lacinia quis fringilla a, dictum a
lectus. Aliquam id dui a nisi dignissim aliquet nec sed augue.
Vestibulum congue felis sit amet iaculis scelerisque. Vivamus
facilisis lacus sit amet eros eleifend dapibus in eget neque.
Aliquam nisi urna, porttitor et nisi in, pretium lacinia orci.
Cras vitae leo posuere, condimentum magna et, vulputate mi.
Nullam maximus ullamcorper leo eu auctor. Quisque eget fermentum
est, aliquet cursus libero. Sed scelerisque mauris sed enim
tristique tempus ornare vestibulum quam. Etiam eget aliquam
augue. In nec lectus convallis, lobortis risus in, euismod
lorem. Sed eleifend nisi ut lorem convallis, nec blandit ante
egestas.
</p>
<p>
Quisque quis tincidunt nunc. In magna est, malesuada quis tempus
id, fermentum eleifend urna. Fusce facilisis rhoncus nibh, eget
pellentesque mauris rhoncus ut. Nulla congue vel lacus nec
pellentesque. Praesent eget elit nisi. Ut eu enim arcu. Duis et
nisi ligula. Maecenas eu ante eget augue pulvinar efficitur.
Aenean vitae luctus dolor. Ut iaculis orci ut orci tincidunt, id
efficitur nulla accumsan. Nullam feugiat porta hendrerit.
Pellentesque eget fringilla leo. Quisque laoreet ligula quis
consectetur aliquam.
</p>
<p>
Nam vel auctor nisl. Cras vel suscipit nibh. Donec nec massa
sagittis, vehicula magna ac, scelerisque velit. Etiam mollis
felis orci, id placerat ipsum egestas a. Class aptent taciti
sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Aenean faucibus vulputate feugiat. Nam condimentum
arcu urna, id tincidunt nisl rhoncus quis. Duis mauris mi,
dapibus et nisl at, facilisis tristique lectus. Nam vel felis in
metus hendrerit placerat ac quis massa. Nam eget turpis nunc.
Nullam at tincidunt lacus. Nulla viverra magna in nisi semper,
non interdum nunc tempus. In pellentesque porttitor bibendum.
Vestibulum blandit congue tempor.
</p>
<p>
Cras congue, nunc et imperdiet porttitor, dui nisl ultricies
ipsum, sed bibendum neque leo auctor sem. Nam velit ipsum,
dictum eget dolor pellentesque, pulvinar imperdiet purus.
Quisque leo dui, eleifend non porttitor quis, auctor convallis
tortor. Integer vel justo at odio suscipit gravida vitae ut
tellus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Mauris sapien urna, iaculis quis magna at, facilisis ultrices
elit. Maecenas ac elementum metus, sit amet congue nunc.
Maecenas vitae posuere lectus. Integer maximus neque at nunc
vestibulum imperdiet. Aenean imperdiet ligula semper nibh
dapibus facilisis. Pellentesque gravida dignissim lacus, et
vulputate sapien dapibus commodo. Etiam efficitur facilisis
sollicitudin. Quisque velit nulla, condimentum ac tellus eget,
rutrum placerat ipsum. Cras auctor auctor sem sed ullamcorper.
</p>
</div>
</div>
</div>
</div>
);
}
}
export default App;
Example

Section breaks for very long CSS columns

Using CSS columns I can format contiguous data into columns without having to manually break it into sections. This is especially useful when displaying complex, dynamic content.
However when the columns' content is so long that their height is greater than the viewport, dividing into columns makes for a poor reading experience. When the reader reaches the bottom of one column they must manually scroll up to begin reading the next.
In traditional print layouts, readability issues with very long columns are generally mitigated by breaking the columns into sections that 'restart' the column. (Physical pages themselves form a natural separation that the endlessly scrolling webpage does not have). The image below shows how horizontal section breaks makes columnar content that is longer than the height of the viewport more readable.
(Note that by 'restart the columns' I mean that once you reach the end of a left-hand column section you then read the right-hand column of that section before scrolling down to read both columns of the next section. https://www.shutterstock.com/image-vector/newspaper-template... might illustrate it more clearly).
There are very few guarantees for the column content. It may contain any number of paragraphs, images, nested block elements, nested inline elements and so on. Example markup is shown below.
.columns {
columns: 2 200px;
}
.columns * {
max-width: 100%;
}
<div class="columns">
<div class="introduction">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas posuere dictum tincidunt. Cras in lectus eget libero suscipit venenatis at sit amet dolor. Donec tempor cursus justo, volutpat sodales dolor tempor eu.</p>
<p class="a-class">Pellentesque nec tempor sapien, sed vehicula sem. Ut pretium leo eget nisi cursus viverra. Ut ultrices porta nibh, sed laoreet felis condimentum sit amet. Aliquam a felis nec urna dignissim placerat sed sit amet elit. Donec elementum sagittis purus, facilisis convallis urna dapibus eu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat. Phasellus vel placerat metus. In efficitur enim eget lacinia ultrices. Duis ultricies dignissim nisi, id ultricies nulla venenatis vitae.</p>
</div>
<img src="https://i.kym-cdn.com/entries/icons/original/000/016/546/hidethepainharold.jpg">
<div class="body" style="">
<p>Suspendisse quis ante ullamcorper, lobortis orci ut, vestibulum dolor. Aenean sit amet purus commodo, sagittis leo vel, consequat nisi. Vestibulum sit amet sem vitae sapien pulvinar finibus. Ut sapien purus, luctus condimentum iaculis quis, lobortis at elit. Cras nulla ante, scelerisque ut aliquet in, elementum vel turpis. Vestibulum ipsum magna, congue sit amet sodales vel, aliquam vel nunc. <img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/SNice.svg" width="100"> Sed eu dapibus nulla. In ut libero sit amet elit elementum gravida. Suspendisse quis quam consequat, pretium felis vel, laoreet turpis. Proin fringilla lobortis magna. Duis quam sapien, sodales nec accumsan id, ullamcorper eget tellus. Aliquam vitae orci cursus, porttitor ligula ut, fringilla odio. Donec a lorem ac eros interdum varius ultricies quis nulla.</p>
</div>
<p contenteditable="true">Nunc in elit tincidunt, ultrices massa sed, ultricies elit. In nec accumsan metus. Nullam ultricies eget tortor ut malesuada. Fusce in elit sit amet dolor bibendum malesuada.</p>
<div style="display:none">
<p>Curabitur sed hendrerit massa, vitae porta enim.</p>
</div>
<div><div><span>hey</span><div id="an-id">
Nullam ultricies eget tortor ut malesuada. Fusce in elit sit amet dolor bibendum malesuada. Nulla sed nisi vel nulla aliquam blandit. Nam vel tellus ut libero ultrices volutpat. Curabitur blandit quis arcu rutrum ullamcorper. Cras et pharetra augue, eget eleifend sem.
<img src="https://socialnewsdaily.com/wp-content/uploads/2018/08/Webp.net-resizeimage-27.jpg">
</div></div></div>
<p>
Mauris accumsan condimentum porttitor. Quisque tellus justo, suscipit sit amet posuere in, scelerisque nec orci. Aenean iaculis nisi in porta viverra. Sed eget ultricies nibh. Donec accumsan laoreet interdum. Donec risus mauris, dapibus et pulvinar at, posuere non nisi. Mauris at viverra nunc. Ut laoreet suscipit erat et cursus. Aenean id lacus volutpat lectus condimentum posuere. Nam ut lectus elit. Morbi sagittis elementum libero. Donec congue dolor sed tristique efficitur.
</p>
<p>
<div>
<p>Sed elementum velit sapien, et tristique justo bibendum at. Aliquam tincidunt magna nec nisi congue varius. Etiam dolor eros, rhoncus quis purus a, tempus malesuada quam. Sed bibendum condimentum eros vitae varius. Donec fermentum magna vel tellus tempus, nec finibus neque fermentum. Mauris tempus nisl sit amet lacus fermentum, at egestas urna egestas.</p>
<p>Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse ultrices lectus vitae nisl congue, sed porta dolor luctus. Donec aliquet at sapien sit amet tincidunt. Mauris vestibulum consectetur augue at imperdiet.</p>
</div>
</p>
</div>
I would like to automatically break my columns into regular sections after the columns reach a maximum height, as in the image above.
I have not found any property that controls the layout of CSS columns in this way. CSS regions look promising but have very poor browser support.
Computing the height of content with JavaScript and then inserting wrappers for each column block is probably possible, but not ideal. The content is dynamic and may change at any time, meaning the function must be run on every change. In addition the content may be very complex with sub elements that need to traverse section breaks, so naively inserting wrappers for each section will likely break the layout.
How can I automatically set section breaks for columnar content after a maximum height? (I am not married to the idea of CSS columns; perhaps a creative use of flex or inline-block will give the result I need).
There's actually a pretty simple solution using CSS columns. And the column-span attribute.
You can achieve all of this WITHOUT injecting anything into the content and simply styling HTML tags.
Basically, the CSS Columns Layout Module is intended to replicate print design layouts (like a newspaper) where the stylistic rule is that headlines should cross all columns of a story. Therefore any element with column-span: all will separate columns and cause the wrapping to reset. (notice the colors in my example show the wrap).
In this case, since you don't control the content its best to provide a common structure to your users. For example, I'd set H1, H2, H3 tags as well as <hr> and maybe some images to break columns. Allow your users to implement these tags as they normally would in writing and you'll achieve a nice layout. However, if they decide NOT to implement any of that stuff, that's up to them and you should let it wrap and cause a long scroll. (I might also suggest providing a preview so they can see what the result will look like)
Example of column-span
.columns {
margin: 30px;
columns: 2;
}
h1, h2, h3, h4, h5 {
column-span: all;
}
// simply to show where things wrap
h2 {
background-color: #eee;
padding: 5px 10px;
}
h5 {
border-bottom: 1px solid #ddd;
padding-bottom: 5px;
text-align: center;
}
p:nth-of-type(1) {
color: blue;
}
p:nth-of-type(2) {
color: green;
}
p:nth-of-type(3) {
color: orange;
}
p:nth-of-type(4) {
color: teal;
}
<div class="columns">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras venenatis tellus non nunc tincidunt, vitae rutrum metus dapibus. Fusce at ante massa. Nam et nibh aliquet, porta nibh quis, rhoncus tortor. Aenean vestibulum neque sed urna lacinia aliquet.
Vestibulum facilisis egestas commodo. Cras sed maximus odio. Mauris posuere, ante id posuere facilisis, ligula libero consectetur lacus, at pellentesque nibh elit at magna. Proin sollicitudin quis nibh at viverra. Duis feugiat, lorem vitae facilisis
blandit, augue tortor cursus orci, sed porttitor eros elit at sapien. Quisque eleifend pulvinar pellentesque.
</p>
<h2>This is a header (h2) with column-span: all set on it</h2>
<p>
Donec blandit sapien leo, id aliquam purus vulputate a. Sed vel turpis ut eros suscipit blandit vel id eros. Nullam ut mauris luctus magna sollicitudin venenatis. Pellentesque leo mauris, malesuada nec purus ut, vestibulum malesuada lectus. Nullam ultricies
tellus sapien, ut fermentum risus pretium a. Nullam magna urna, ullamcorper non congue a, efficitur nec orci. Ut aliquam molestie nisi. In at accumsan purus. Etiam non tempor ipsum. Maecenas gravida mauris in nibh vehicula ullamcorper. Sed libero lorem,
faucibus eu lorem ut, gravida eleifend enim. Nunc vehicula fermentum consequat. Phasellus a pellentesque nisl. Nulla vel suscipit nibh, ac cursus dui. Suspendisse elementum dapibus risus. Nam egestas congue finibus.
</p>
<p>
Nunc vel risus nec nulla dignissim congue. Cras sit amet lacus nec nisl mollis pellentesque in vel purus. Suspendisse efficitur mollis nibh, congue facilisis libero auctor ac. Nulla facilisi. Etiam ut erat eget erat egestas suscipit. Curabitur vitae varius
mauris. Sed accumsan diam eros, id dapibus metus rutrum at. Nunc vitae pretium massa. Aenean quis mauris leo. Nulla egestas ligula eu libero interdum feugiat. Aliquam maximus erat et tortor auctor varius. Nulla in pharetra leo, vel suscipit nunc. Orci
varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec nec egestas ante, vitae sollicitudin arcu. Pellentesque posuere tempus nibh, nec tempus eros pellentesque ac.
</p>
<p>
Curabitur tempus massa dolor, nec congue purus efficitur id. Phasellus a dictum mauris. In porta nulla lectus, pretium semper erat semper id. Fusce ornare fringilla mi, ut auctor tortor semper non. Aliquam sed felis fermentum, molestie dolor vel, eleifend
diam. Donec accumsan bibendum mi, sed pretium tortor pulvinar nec. Aliquam et metus accumsan, pretium neque eu, elementum ipsum. Nam dapibus risus sed velit viverra, non consequat nibh pretium. Morbi nec gravida turpis. Quisque convallis justo ut rhoncus
porttitor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
<h5>This is a header (h5) with column-span: all set on it</h5>
<p>
Proin fringilla, sapien molestie mattis commodo, leo ligula viverra massa, eget semper leo purus sit amet est. Quisque eu diam interdum, pretium dui sed, dictum sem. Sed cursus eu est in ultrices. Suspendisse eleifend imperdiet lectus eu consectetur.
Duis semper libero nec magna commodo, sollicitudin pharetra magna luctus. Fusce pellentesque sollicitudin dolor, eu scelerisque elit condimentum vel. Curabitur id condimentum nisi, eu rhoncus arcu. Proin metus purus, condimentum nec semper vitae, blandit
at leo. Proin commodo et ipsum ac euismod. Aliquam erat volutpat. Nam neque nisi, ornare sit amet metus ac, faucibus tempor nulla. Quisque tristique malesuada finibus. Praesent fermentum posuere urna, a blandit risus sollicitudin nec.
</p>
</div>
Using 'break-inside: avoid;' each paragraph
In the solution I attached, I gave each DIV a break-avoid class to avoid breaking in the middle of the paragraph.
Like you asked, if the paragraph is not over yet you can scroll down. I added a gray color that you can see in the paragraphs.
You can control when it will break and you can also insert a div into a div if you want it in sequence.
Hope the solution is effective for you.
.columns {
columns: 5 250px;
}
.columns * {
max-width: 100%;
}
.break-avoid{
break-inside: avoid;
background-color: #ccc;
}
<div class="columns">
<div class="introduction break-avoid">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas posuere dictum tincidunt. Cras in lectus eget libero suscipit venenatis at sit amet dolor. Donec tempor cursus justo, volutpat sodales dolor tempor eu.</p>
<p class="a-class">Pellentesque nec tempor sapien, sed vehicula sem. Ut pretium leo eget nisi cursus viverra. Ut ultrices porta nibh, sed laoreet felis condimentum sit amet. Aliquam a felis nec urna dignissim placerat sed sit amet elit. Donec elementum sagittis purus, facilisis convallis urna dapibus eu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat. Phasellus vel placerat metus. In efficitur enim eget lacinia ultrices. Duis ultricies dignissim nisi, id ultricies nulla venenatis vitae.</p>
</div>
<img src="https://i.kym-cdn.com/entries/icons/original/000/016/546/hidethepainharold.jpg">
<div class="body break-avoid" style="">
<div>
<p>Suspendisse quis ante ullamcorper, lobortis orci ut, vestibulum dolor. Aenean sit amet purus commodo, sagittis leo vel, consequat nisi. Vestibulum sit amet sem vitae sapien pulvinar finibus. Ut sapien purus, luctus condimentum iaculis quis, lobortis at elit. Cras nulla ante, scelerisque ut aliquet in, elementum vel turpis. Vestibulum ipsum magna, congue sit amet sodales vel, aliquam vel nunc.Suspendisse quis ante ullamcorper, lobortis orci ut, vestibulum dolor. Aenean sit amet purus commodo, sagittis leo vel, consequat nisi. Vestibulum sit amet sem vitae sapien pulvinar finibus. Ut sapien purus, luctus condimentum iaculis quis, lobortis at elit. Cras nulla ante, scelerisque ut aliquet in, elementum vel turpis. Vestibulum ipsum magna, congue sit amet sodales vel, aliquam vel nunc.Suspendisse quis ante ullamcorper, lobortis orci ut, vestibulum dolor. Aenean sit amet purus commodo, sagittis leo vel, consequat nisi. Vestibulum sit amet sem vitae sapien pulvinar finibus. Ut sapien purus, luctus condimentum iaculis quis, lobortis at elit. Cras nulla ante, scelerisque ut aliquet in, elementum vel turpis. Vestibulum ipsum magna, congue sit amet sodales vel, aliquam vel nunc.Suspendisse quis ante ullamcorper, lobortis orci ut, vestibulum dolor. Aenean sit amet purus commodo, sagittis leo vel, consequat nisi. Vestibulum sit amet sem vitae sapien pulvinar finibus. Ut sapien purus, luctus condimentum iaculis quis, lobortis at elit. Cras nulla ante, scelerisque ut aliquet in, elementum vel turpis. Vestibulum ipsum magna, congue sit amet sodales vel, aliquam vel nunc. <img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/SNice.svg" width="100"> Sed eu dapibus nulla. In ut libero sit amet elit elementum gravida. Suspendisse quis quam consequat, pretium felis vel, laoreet turpis. Proin fringilla lobortis magna. Duis quam sapien, sodales nec accumsan id, ullamcorper eget tellus. Aliquam vitae orci cursus, porttitor ligula ut, fringilla odio. Donec a lorem ac eros interdum varius ultricies quis nulla.</p>
</div>
</div>
<p class="break-avoid" contenteditable="true">Nunc in elit tincidunt, ultrices massa sed, ultricies elit. In nec accumsan metus. Nullam ultricies eget tortor ut malesuada. Fusce in elit sit amet dolor bibendum malesuada.</p>
<div style="display:none;" class="break-avoid">
<p>Curabitur sed hendrerit massa, vitae porta enim.</p>
</div>
<div class="break-avoid"><div><span>hey</span><div id="an-id">
Nullam ultricies eget tortor ut malesuada. Fusce in elit sit amet dolor bibendum malesuada. Nulla sed nisi vel nulla aliquam blandit. Nam vel tellus ut libero ultrices volutpat. Curabitur blandit quis arcu rutrum ullamcorper. Cras et pharetra augue, eget eleifend sem.
<img src="https://socialnewsdaily.com/wp-content/uploads/2018/08/Webp.net-resizeimage-27.jpg">
</div></div></div>
<div class="break-avoid">
<p>
Mauris accumsan condimentum porttitor. Quisque tellus justo, suscipit sit amet posuere in, scelerisque nec orci. Aenean iaculis nisi in porta viverra. Sed eget ultricies nibh. Donec accumsan laoreet interdum. Donec risus mauris, dapibus et pulvinar at, posuere non nisi. Mauris at viverra nunc. Ut laoreet suscipit erat et cursus. Aenean id lacus volutpat lectus condimentum posuere. Nam ut lectus elit. Morbi sagittis elementum libero. Donec congue dolor sed tristique efficitur.
</p>
</div>
<div class="break-avoid">
<p>Sed elementum velit sapien, et tristique justo bibendum at. Aliquam tincidunt magna nec nisi congue varius. Etiam dolor eros, rhoncus quis purus a, tempus malesuada quam. Sed bibendum condimentum eros vitae varius. Donec fermentum magna vel tellus tempus, nec finibus neque fermentum. Mauris tempus nisl sit amet lacus fermentum, at egestas urna egestas.</p>
<p>Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse ultrices lectus vitae nisl congue, sed porta dolor luctus. Donec aliquet at sapien sit amet tincidunt. Mauris vestibulum consectetur augue at imperdiet.</p>
</div>
</div>

change javascript html, use jquery css [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i have a javascript worked html code. but i dont need a html, i need a jquery css
which have the same functionality.
i try to change js html by jquery css but it does not worked
js html
$('html, div:contains('+yourstring+')', document.body).each(function(){
console.log(this);
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi'), '<span class=someclass>'+yourstring+'</span>'
));
});
to css query
$('html, div:contains('+yourstring+')', document.body).each(function(){
console.log(this);
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi').css('background-color' 'blue')
));
});
In your example, this code, will not work:
$('html, div:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi').css('background-color' 'blue')
));
});
Since a new RegExp is not a jQuery Object, you cannot call .css() up it. You must still have an HTML Element or a jQuery Object to work with.
Another thing to be aware of is that :contains() is case sensitive. So if you're testing with "test" it will not find "Test" in your <div> element. So you may have some search issues right away with this selector.
Consider this example:
$(function() {
function replacer(sObj, n) {
var c = sObj.text().trim().split(" ");
var re = new RegExp(n, "i");
var hits = [];
$.each(c, function(k, v) {
if (v.match(re) != null) {
hits.push(k);
var newObj = $("<span>", {
class: "highlight"
}).html(v);
c[k] = newObj.prop("outerHTML");
}
});
sObj.html(c.join(" "));
return hits;
}
$("div").each(function(ind, el) {
replacer($(el), "lorem");
});
});
.para {
margin: 10px;
}
.highlight {
background-color: #ccf;
padding: 0.02em;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel dictum nunc, nec pellentesque elit. Integer eget tempor tellus, sit amet volutpat purus. Proin magna est, sollicitudin in suscipit quis, tincidunt at lacus. Morbi sollicitudin sit amet justo
sit amet pellentesque. Nunc placerat ligula sapien, non laoreet tellus dictum ac. Fusce est leo, bibendum ac justo sit amet, rhoncus placerat enim. Mauris sit amet lectus felis. Aenean eget feugiat leo, rhoncus hendrerit felis. Donec placerat mi quis
justo varius tempor. Nunc ultricies mi in dolor placerat, non consequat est lobortis. Quisque ac libero in sem cursus pharetra. Fusce pretium rutrum viverra.</div>
<div class="para">Nullam tincidunt ut nisl eu venenatis. Duis non finibus orci, nec imperdiet augue. Sed consectetur orci ut magna sollicitudin sagittis. In mattis tempus molestie. Suspendisse vitae hendrerit nulla. Sed scelerisque metus eros, eu molestie felis auctor
convallis. In tempor mauris non mi bibendum mollis. Nulla eu sapien non mi aliquam interdum. Donec lorem elit, tincidunt nec lorem at, finibus commodo mauris.</div>
<div class="para">Donec non lectus auctor, imperdiet ante quis, varius erat. Aenean vitae mi magna. Nunc dui tortor, dictum volutpat porta quis, hendrerit nec nunc. Morbi blandit, lectus eget ultrices vestibulum, odio arcu rutrum sem, quis placerat lectus dui sit amet
augue. Phasellus congue gravida tortor. Sed nec mauris tempus, convallis justo ac, sollicitudin mauris. Pellentesque pretium facilisis augue in dignissim. Pellentesque sollicitudin erat vitae consectetur lacinia. Nunc faucibus lobortis sem vel faucibus.
Suspendisse a ligula aliquet, tempus neque at, egestas mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eleifend felis lorem. Vivamus sollicitudin, purus nec finibus luctus, dui urna tincidunt est, posuere imperdiet erat magna
quis turpis. Donec vestibulum nisl eu porttitor laoreet.</div>
<div class="para">Duis vel nibh a libero elementum porttitor sit amet feugiat nisl. Quisque nec maximus turpis. Maecenas in libero sit amet urna consectetur posuere. Maecenas vulputate vitae eros a malesuada. Nullam malesuada nulla et varius aliquam. Nulla hendrerit mi
ac nisi scelerisque, id molestie nibh ultricies. Vivamus venenatis, diam ac vehicula gravida, magna diam consectetur nibh, ac mollis libero enim a orci. Nam tincidunt est id vulputate ullamcorper. In nec lectus blandit, ullamcorper tortor vel, ornare
neque. In accumsan tempus orci in finibus. Mauris ac fermentum dui, ac volutpat erat.</div>
<div class="para">Praesent sed purus risus. Quisque porttitor suscipit feugiat. Quisque est massa, porttitor ut feugiat vel, consectetur nec mauris. Fusce iaculis lacus vel felis rhoncus accumsan. Vestibulum interdum lacus magna, id gravida tellus sollicitudin in. Cras
mauris turpis, elementum a imperdiet ut, faucibus sit amet elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec venenatis eget libero ut aliquet. Praesent a mollis est, ut consequat arcu. Sed nec
molestie diam. Nunc vestibulum consectetur odio non accumsan. Suspendisse eget tempus lacus. Cras quis dignissim odio, eget tincidunt nulla.</div>
This might be overboard from what you want to do. It's a good way to highlight words with a loop.
Hope that helps.

Categories