I am highlighting selected text by using the following xpath and offsets.
Here is an example selection of text I am using to debug.
[{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
startOffset:0,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]",
endOffset:1,
color: "purple"
}]
This selection above works nicely and highlights the selected paragraph.
Now here is the part I am stuck on, as soon as I add text to the paragraph it fails to highlight the text.
Here is the example with selected paragraph and text, so in theory this should only select the text inside the paragraph that you selected. Changes are marked in bold
[{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startOffset:288,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
endOffset:330,
color: "purple"
}]
test.html (this uses highlight.show)
function highlightTest() {
$MON.highlight.show([
{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
startOffset:0,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0001]",
endOffset:1,
color: "yellow"
},
{
commonAncestorContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
startOffset:288,
endContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0]",
endOffset:330,
color: "purple"
}
]);
highlight.js(this uses xpath.element)
show: function(selections)
{
for (var i in selections)
{
var selection = selections[i];
var ancestor = $MON.xpath.element(selection["commonAncestorContainer"]);
ancestor.contentEditable = "true";
var col = selection["color"] ? selection["color"] : "yellow";
var range = document.createRange();
var startElement = $MON.xpath.element(selection["startContainer"]);
var startOffset = selection["startOffset"];
var endElement = $MON.xpath.element(selection["endContainer"]);
var endOffset = selection["endOffset"];
range.setStart(startElement, startOffset);
range.setEnd(endElement, endOffset);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand("HiliteColor", false, col);
window.getSelection().removeAllRanges();
ancestor.contentEditable = "false";
}
}
xpath.js
(this returns the corresponding element given the xpath, back to highlight.js)
element: function (expr) {
var resolver = function (prefix) {
if ("xhtml" == prefix) {
return "http://www.w3.org/1999/xhtml";
}
}
var result = document.evaluate(expr, document, resolver, 9, null).singleNodeValue;
return result;
}
HTML
<body>
<p>
1 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
2 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
3 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
4 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
5 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
<p>
6 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tellus ligula, ullamcorper vitae elementum sed, rhoncus a ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et pulvinar augue. Proin non semper mi. Nullam justo velit, vehicula eu congue vitae, tincidunt sit amet urna. Aliquam blandit rutrum dignissim. Donec dapibus nisl arcu, eu eleifend tellus lobortis quis. Praesent quis hendrerit diam. Quisque ultricies lorem et turpis aliquam ornare. Phasellus dolor purus, lacinia eget porta vel, iaculis ac nisl. Phasellus vestibulum faucibus erat sit amet interdum.
</p>
</body>
Log on text selection, gets the selected xpath
38:Selected text: Lorem
44:Collapsed: false
45:Ancestor container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
46:Start container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
47:Start offset: 7
48:End container: /xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[0001]
49:End offset: 12
Update (my problem was)
I had to add
document.designMode = "on";
before i set the hilite color
here is a link to js fiddle
http://jsfiddle.net/E2BbX/11/
XPath indexes are one-based. Try
startContainer: "/xhtml:html[0001]/xhtml:body[0001]/xhtml:p[0002]/text()[1]
and so on.
Related
is there any way to delete or replace text with (...) if the text is inside the .class p tag is greater than 100 characters?
Example I have this long text inside on the p tag:
<div class='classname'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
Expected Result:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat ...
let peles = document.querySelectorAll('.classname > p')
for(p of peles){
let txt = p.innerText
txt = txt.replace(txt.substring(100),'...')
p.innerText = txt
}
<div class='classname'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
<div>
// Gets all p elements inside element with class: classname
const paras = document.querySelectorAll(".classname > p");
paras.forEach( p => {
const text = p.textContent;
if (text.length > 100){
const newText = text.slice(0, 100) + " ...";
p.textContent = newText;
}
})
<div class='classname'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</div>
EDIT: Answering question in the comments
const parasExceptFirst = document.querySelectorAll(".classname p:not(:first-child)");
parasExceptFirst.forEach( p => {
p.remove()
})
<div class='classname'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nibh velit, suscipit bibendum sagittis non, consequat vestibulum ante. Praesent in fermentum turpis. Nam nec erat vulputate, imperdiet mi ac, porttitor diam. Quisque posuere odio vel nulla varius dictum. Vestibulum malesuada tellus id cursus pretium. Cras volutpat, diam vel molestie bibendum, neque risus ullamcorper augue, vel convallis odio purus hendrerit quam. Mauris convallis dolor vel ex placerat, non imperdiet dolor lacinia. </p>
</div>
try this
$(document).ready(function() {
// Configure/customize these variables.
var showChar = 100; // How many characters are shown by default
var ellipsestext = "...";
$('.more').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + h + '</span> ' + moretext + '</span>';
$(this).html(html);
}
});
$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
You can also try css, like this:
display: -webkit-box;
overflow: hidden;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
line-height: 1.5;
It feels a little better to use this way.
Let's say we have this text inside a single <p> that uses the entire screen space:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum
sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo
pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in
laoreet auctor. Donec in tortor in augue maximus fermentum et non erat.
Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor lectus, consectetur.
If we were using a smaller display, it would look like something this:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed vestibulum sem
consectetur, tempor massa quis, bibendum
mauris. Curabitur et leo pharetra,
condimentum mi vel, gravida mi. Integer
pulvinar nibh in laoreet auctor. Donec
in tortor in augue maximus fermentum et
non erat. Sed auctor feugiat dolor eget
efficitur. Vivamus nec urna lorem. Duis
lobortis semper tempor. Vestibulum dolor
lectus, consectetur.
The paragraph has now more lines than before. With that said, I want to convert this single paragraph into one <p> per line to apply different styling to each one of them, but also taking into acount that the number of lines can change from the viewport/browser window size. This is so that the text styling can be responsive.
HTML:
<p>Lorem ipsum dolor sit amet, consectetur</p>
<p>adipiscing elit. Sed vestibulum sem</p>
<p>consectetur, tempor massa quis, bibendum</p>
<p>mauris. Curabitur et leo pharetra,</p>
<p>condimentum mi vel, gravida mi. Integer</p>
<p>pulvinar nibh in laoreet auctor. Donec</p>
<p>in tortor in augue maximus fermentum et</p>
<p>non erat. Sed auctor feugiat dolor eget</p>
<p>efficitur. Vivamus nec urna lorem. Duis</p>
<p>lobortis semper tempor. Vestibulum dolor</p>
<p>lectus, consectetur.</p>
I'm looking for a pure JavaScript (aka no jQuery) solution.
document.body.addEventListener("load", function(){
var defaultCharacterWidth = 8; //8 px
var textboxWidth = document.querySelector(".orgText").offsetWidth;
var breakIndex = Math.floor(textboxWidth/defaultCharacterWidth);
var i = 0;
var savedIndex = 0;
var whitespace = 0;
document.querySelector(".orgText").textContent.match(/[\s\S]/g).forEach(function(element, index){
if (element.match(/\s/))
{
whitespace = index;
}
if (i == breakIndex)
{
i = -1;
//get nearest whitespace
document.querySelector(".textcontainer").innerHTML += "<p>" + document.querySelector(".orgText").value.slice(savedIndex, whitespace) + "</p>";
savedIndex = whitespace; //save the last whitespace
}
i++;
});
}, true);
<textarea class="orgText" style="overflow:hidden;width:100%">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum sem consectetur, tempor massa quis, bibendum mauris. Curabitur et leo pharetra, condimentum mi vel, gravida mi. Integer pulvinar nibh in laoreet auctor. Donec in tortor in augue maximus fermentum et non erat. Sed auctor feugiat dolor eget efficitur. Vivamus nec urna lorem. Duis lobortis semper tempor. Vestibulum dolor lectus, consectetur.
</textarea>
<div class="textcontainer">
</div>
This is a little testcode. It uses the fact that a textarea has a fixed character width. But that's not the case for most fonts. The above code iterates over every character and checks if it's exceeds the width of the container based upon the detection of a whitespace character.
You can also use the code below to calculate the width of a string.
function getPixelLengthOfString()
{
var tempNode = document.createElement("span");
tempNode.innerHTML = this;
document.body.appendChild(tempNode);
var stringPixelLength = tempNode.offsetWidth;
document.body.removeChild(tempNode);
return stringPixelLength;
}
These pieces of code should point you in a direction of the correct answer.
I have copied text from my webpage , the selected copied text are
var someText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec lorem eu ante ullamcorper semper. In venenatis augue sed dolor tincidunt aliquet. Quisque aliquam consectetur nunc eu congue. Ut aliquet nunc a vulputate ullamcorper. Fusce posuere nec tortor eget varius. Aenean blandit ultricies posuere. - See more at: https://mywebaddress.com#sthash.pUpdg9k4.dpuf";
I want to get rid of see more at: url.. using javascript.
You can use substr() and indexOf():
var someText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec lorem eu ante ullamcorper semper. In venenatis augue sed dolor tincidunt aliquet. Quisque aliquam consectetur nunc eu congue. Ut aliquet nunc a vulputate ullamcorper. Fusce posuere nec tortor eget varius. Aenean blandit ultricies posuere. - See more at: https://mywebaddress.com#sthash.pUpdg9k4.dpuf";
someText = someText.substr(0, someText.indexOf('-'));
console.log(someText);
My end goal is to create a tooltip over a text selection. The user will then be able to interact with the tooltip similar to . Please note that I was able to accomplish this by wrapping selected text in a tag and then creating the tooltip on it however this is no longer an option for me due to some other requirements and functionality issues. If you notice in the image above in element inspector, the selected text is not wrapped in any kind of tag, the tooltip is just created over the selection. I have already looked at this and it will not work for me because mouse position may not be the same as the end of selection. I need the actual selection position.
General question: What is the best way to accomplish this?
More specific questions:
Should I be using the coordinates of the selection? If so is there a way to get the coordinates of the top corners of the rectangular selection so I can find the mid point and create a the tooltip over that.
Is there a way to get that selection as an element? So I can just place a tooltip over that? (Note the selection can be multiple nodes)
Assuming something selected
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
rect is now a Object which holds the positions relative the the current scroll coordinates of the Window. More info on this here. If you want to be even more precise, you can use getClientRects which returns a list of such Objects, which you would then have to put together to form the area of the selection.
Now, to draw a box around it (I'll take the easy route using fixed for demonstration purposes)
var div = document.createElement('div'); // make box
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
You will probably want to take into consideration the scroll position so you can use absolute positioning. If there are no other scrollable elements, this means you just need to factor in the values of window.scrollX and window.scrollY, which are the position of the window's x and y coordinates in pixels at the time they're accessed.
var div = null;
function drawBorderAroundSelection() {
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
if (rect.width > 0) {
if (div) {
div.parentNode.removeChild(div);
}
div = document.createElement('div'); // make box
div.class = 'rect';
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
}
}
window.onmouseup = drawBorderAroundSelection;
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis
nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue
vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque.
</p>
$(document).ready(function () {
function tweetButtonClick() {
let selectedText = document.getSelection().toString();
/*window.open(
"https://twitter.com/intent/tweet?url=https://www.linkedin.com/in/harsha-vardhan-ch-245197bb/&text=" +
selectedText
);*/
console.log("This is your selected text: ",selectedText);
}
const textSelectionTooltipContainer = document.createElement("div");
textSelectionTooltipContainer.setAttribute(
"id",
"textSelectionTooltipContainer"
);
textSelectionTooltipContainer.innerHTML = `<button id="textShareTwitterBtn">TWEET</button>`;
const bodyElement = document.getElementsByTagName("BODY")[0];
$("body").on("click", "#textShareTwitterBtn", tweetButtonClick);
bodyElement.addEventListener("mouseup", function (e) {
var textu = document.getSelection().toString();
if (!textu.length) {
textSelectionTooltipContainer.remove();
}
});
document
.getElementById("textToSelect")
.addEventListener("mouseup", function (e) {
let textu = document.getSelection().toString();
let matchu = /\r|\n/.exec(textu);
if (textu.length && !matchu) {
let range = document.getSelection().getRangeAt(0);
rect = range.getBoundingClientRect();
scrollPosition = $(window).scrollTop();
containerTop = scrollPosition + rect.top - 50 + "px";
containerLeft = rect.left + rect.width / 2 - 50 + "px";
textSelectionTooltipContainer.style.transform =
"translate3d(" + containerLeft + "," + containerTop + "," + "0px)";
bodyElement.appendChild(textSelectionTooltipContainer);
}
});
});
#textSelectionTooltipContainer {
will-change: transform;
position: absolute;
width: 100px;
height: 40px;
background: #f7d39d;
top: 0px;
left: 0px;
display: flex;
padding: 5px 10px;
box-sizing: border-box;
justify-content: center;
}
#textSelectionTooltipContainer button {
font-size: 14px;
border: 1px solid black;
background: none;
cursor: pointer;
margin: 0 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel='stylesheet' href='shareText.css' />
<title>Text Share Feature</title>
<script>
</script>
</head>
<body>
<div id="textToSelect">
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
elit sit amet quam. Vivamus pretium ornare est.</p>
<p>
Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
</p>
</blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
</div>
<script src="shareText.js"></script>
</body>
</html>
window.open lets you open the twitter page(https://twitter.com/intent/tweet) where you can share the selected text and also url.
I have tried using the accordion plugin, but it does not work, and I know there is a simpler solution using pure jQuery.
In essence, I would like it so that when you click a <h2> with the class="expand", it should 'expand' the next div with class="collapse". All the divs should be collapsed by default.
Any help would be much appreciated, thanks in advance!
For testing purposes see this jsFiddle demo.
const $headers = $('.header');
const $contents = $('.content');
$headers.on("click", function() {
const $cont = $(this).next(".content");
$contents.not($cont).slideUp(); // Hide all
$cont.slideToggle(); // Toggle one
});
.header { background: #ddd; cursor: pointer; margin: 0; }
.content{ display:none; }
<h2 class="header">Click to expand and collapse</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<h2 class="header">Click to expand and collapse 2</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<h2 class="header">Click to expand and collapse 3</h2>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin
ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut
tortor tempus auctor.</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It hides all opened elements before collapsing the closed one.
And it toggles the open state if the element is opened.
This is simple, just use the below
$('.expand').click(function() {
$(this).next('.collapse').slideToggle(); // or use .toggle() for no animation
});
Fiddle: http://jsfiddle.net/garreh/WQYc7/2/
To be collapsed by default just add the below css:
.collapse {
display: none;
}
Use jQuery, I've updated your Fiddle.
HTML:
<div id="accordion">
<h2 class="toggle">Click to expand and collapse</h2>
<div class="pane">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut tortor tempus auctor.
</div>
<h2 class="toggle">Click to expand and collapse 2</h2>
<div class="pane"><br>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean bibendum dolor nec nunc aliquam placerat. Nullam vehicula nibh felis. Nulla tincidunt aliquam nisl nec sagittis. Donec convallis hendrerit nisl, ut lacinia elit sagittis a. Nullam sollicitudin ultricies nibh, tincidunt adipiscing erat tristique vitae. Sed id ipsum ac ipsum fringilla molestie et sit amet elit. Cras commodo augue id dolor suscipit commodo. Ut varius porta orci, quis dignissim ante adipiscing et. Pellentesque rhoncus purus ut tortor tempus auctor.
</div>
</div>
Javascript:
<script>
$(document).ready(function() {
$('#accordion h2').click(function() {
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
$(this).toggleClass('current').siblings('h2').removeClass('current');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
}
});
});
</script>
CSS:
.toggle {
background: gray;
padding: 5px;
cursor: pointer;
}
.pane { display: none; }
.current { background: green }