I need to truncate the text(with ... at the end) and on mouseover the entire text should get expanded.
I have tried to truncate by the below code. Problem with this code is, it expands the content on click of the ... but I need it to get opened when user mouse over anywhere on p tag
var len = 100;
var p = document.getElementById('truncateMe');
if (p) {
var trunc = p.innerHTML;
if (trunc.length > len) {
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
trunc += '<a href="#" ' +
'onmouseover="this.parentNode.innerHTML=' +
'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
'...<\/a>';
p.innerHTML = trunc;
}
}
DEMO
I am looking for an easy way to do it.
Thanks in advance.
PS: No CSS solution please, as it is not compatible with all browsers (IE7).
You can use Jquery Like this :
HTML :
<p>Some Text</p>
JS :
var lengthText = 30;
var text = $('p').text();
var shortText = $.trim(text).substring(0, lengthText).split(" ").slice(0, -1).join(" ") + "...";
$('p').text(shortText);
$('p').hover(function(){
$(this).text(text);
}, function(){
$(this).text(shortText);
});
DEMO : http://jsfiddle.net/1yzzbv4b/2/
Or you can also achieve this with css3 property text-overflow:ellipsis;
CSS :
p{
text-overflow:ellipsis;
width: 250px;
white-space: nowrap;
overflow: hidden;
}
p:hover{
text-overflow:clip;
width:auto;
white-space: normal;
}
DEMO : http://jsfiddle.net/1yzzbv4b/
Assuming that you set the class of your p-elements to be of escape-text, the following jQuery-code should work.
$(document).ready(function() {
$ps = $('.escape-text');
$ps.each(function(i, el) {
$(el).data('full-text', el.innerHTML);
strip(el);
});
$ps.on('mouseover', function() {
$(this).text($(this).data('full-text'));
}).on('mouseout', function() {
$(this).text(strip(this));
})
});
var length = 100;
var strip = function(el) {
el.innerHTML = el.innerHTML.substr(0, length) + '...';
}
Related
I am trying to style the first letter of a paragraph using CSS and wanted to add some animation using greensock, But actually the requirement is to style the each word's first letter not just the first letter paragraph.
Whats the suggestion/ideas on this?
p{
font-size:150%;
color:#000000;
}
p::first-letter {
font-size: 200%;
color: #ff0000;
}
<p>Hello This Is The Title</p>
UPDATE I tried handling the following way (adding span tag and targeting first element of each span) but it doesn't work:
p span:nth-child(1)::first-letter {
font-size: 200%;
color: #ff0000;
}
use with split(" ") for create the array form string and forEach() is iterate the each word. Then slice(0,1) the cut first letter of the word then append with span .And add the css effect with span
var str = $('p').text().split(" ");
$('p').empty();
str.forEach(function(a) {
$('p').append(' <span>' + a.slice(0, 1) + '</span>' + a.slice(1))
})
p {
font-size: 150%;
color: #000000;
}
span {
font-size: 200%;
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello This Is The Title</p>
const p = document.getElementById('text')
const styleMe = l => '<span class="styled">' + l + '</span>'
const newS = p.innerText.split(' ').map(w => w.split('').map((l,i) => (i === 0) ? styleMe(l) : l).join('')).join(' ')
p.innerHTML = newS
.styled {
color:red
}
<p id="text">Hello This Is The Title</p>
There is no css first-word css selector. So you can use jquery to achieve this.
Solution 1: To style only 1st word of a paragraph .
$(function() {
$('p').each(function() {
var text = this.innerHTML;
var firstSpaceIndex = text.indexOf(" ");
if (firstSpaceIndex > 0) {
var substrBefore = text.substring(0,firstSpaceIndex);
var substrAfter = text.substring(firstSpaceIndex, text.length)
var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
this.innerHTML = newText;
} else {
this.innerHTML = '<span class="firstWord">' + text + '</span>';
}
});
});
.firstWord{ color:red; font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Styling the first word of pragraph.</p>
Solution 2 : Too style each first letter of paragraph line
$(document).ready(function() {
var words = $('p').text().split(' ');
var html = '';
$.each(words, function() {
html += '<span class="firstLetter">'+this.substring(0,1)+'</span>'+this.substring(1) + ' ';
});
$('p').html(html);
});
.firstLetter{ color:red; font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Styling each first letter of the word in pragraph.</p>
What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-letter-every-word.
The easiest option would be to wrap the first letter of each word in a <span>. Another option would be to try a javascript solution.
I need help with optimizing this small system that takes in a string and looks for any words that match the words stored in an array. The system should reprint the same string with the new words every time there was a match. However, it only changes after the first match currently.
Sample text:
his de is good
but his en is worse then nl
The result for the above is currently:
his Dutch is good
but his English is worse then nl
But the result I want to get is:
his Dutch is good
but his English is worse then Danish
So how can I fix the system to print the second result?
Here is my system in JSFIDDLE.
function check(string, wrapper) {
var terms = ['de', 'en', 'nl'];
var match = false;
for(var i=0;i<terms.length && !match;i++) {
if(string.indexOf(terms[i]) > -1) {
match = true;
var newString='';
wrapper.css("background", "#a1e4ff");
var matchString = string.substring(string.indexOf(terms[i]), (string.indexOf(terms[i])+terms[i].length));
var rx = RegExp("\\b" + matchString + "\\b", "g");
switch(matchString) {
case 'de':
newString = string.replace(rx, "Dutch");
break;
case 'en':
newString = string.replace(rx, "English");
break;
case 'nl':
newString = string.replace(rx, "Danish");
break;
default:
alert('no matches');
}
$(".corrections").append("<li>" + newString + "</li>");
}
}
}
$(document).ready(function() {
$('textarea').focusout(function() {
var x = $(this).val();
$('.orig-list').html(x.replace(/\n(?!>)/g, '<li>'));
});
$('#down').click(function() {
$('.orig-list li').each(function() {
var phrase = $(this).text();
var matchHighlight = $(this);
check(phrase, matchHighlight);
});
});
});
The main point is that you did not add <li> tag before the first item, and that is why you $('.orig-list li').each did not select it and that is why the string consisting of one line did not work. Change the $('.orig-list').html() code to
$('.orig-list').html("<li>" + x.replace(/\n(?!>)/g, '<li>'));
Besides, it will be much easier if you put the terms with replacements into a dictionary, and use it like
if (/en|de|nl/.test(string)) {
wrapper.css("background", "#a1e4ff");
newString = string.replace(/en|de|nl/g, function(x) {
return terms[x] || "";
});
$(".corrections").append("<li>" + newString + "</li>");
}
See the updated snippet below.
function check(string, wrapper) {
var terms = {'de':'German', 'en':'English', 'nl':'Dutch'};
if (/en|de|nl/.test(string)) {
wrapper.css("background", "#a1e4ff");
newString = string.replace(/en|de|nl/g, function(x) {
return terms[x] || "";
});
$(".corrections").append("<li>" + newString + "</li>");
}
}
$(document).ready(function() {
$('textarea').focusout(function() {
var x = $(this).val();
$('.orig-list').html("<li>" + x.replace(/\n(?!>)/g, '<li>'));
});
$('#down').click(function() {
$('.orig-list li').each(function() {
var phrase = $(this).text();
var matchHighlight = $(this);
check(phrase, matchHighlight);
});
});
});
span#down {
background: #4f5152;
width: 100px;
color: #fff;
display: block;
margin-top: 20px;
padding: 9px;
border-radius: 4px;
line-height: 1;
font-weight: 600;
cursor:pointer;
margin-bottom: 50px;
}
.receiver div {
border: 1px solid red;
width: 40%;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-wrapper">
<div class="receiver">
<textarea></textarea>
<span id="down">Generate List</span>
<div>
<h4>Generated List with unicode errors</h4>
<ol class="orig-list"></ol>
</div>
<div class="corrections-wrapper">
<h4>Corrected Names</h4>
<ol class="corrections"></ol>
</div>
</div>
</div>
I'm looking for a way to fill a div with single characters.
The div should be the width of the viewport. I get the width with:
$(window).width();
JS should build a HTML-code like this:
<div id="text">ccccccccccccccccccccccccccccccccccccccccc</div>
Thanks for your inputs.
Here's a way to do it:
var char = 'i';
$('#text').html($('#text').html() + char)
var initialheight = $('#text').height();
while ($('#text').height() === initialheight) $('#text').html($('#text').html() + char)
$('#text').html($('#text').html().slice(0,-1))
#text {
word-break: break-all;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text"></div>
The way this works is that the script inserts a character int the div and gets the height. Then in repeatedly adds characters until the height changes, which indicates that more than one line has occurred. Then it trims the last character that caused it to overflow onto two lines. It's independent of any font characteristics.
Because a character size can be fixed or not accordig to the font I suggest to use a function to approximate the numbers of characters to print:
function writeMaxNumCharsInOneLine(textObj, charToWrite) {
var innWidth = textObj.innerWidth();
textObj.append('<span id="charSize" style="visibility: visible; white-space: nowrap;">' + charToWrite + '</span>');
var charSize = $('#charSize').width();
var numCharsToWrite = (innWidth / charSize).toFixed(0);
var strToWrite = charToWrite.repeat(numCharsToWrite);
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
while (charSize < innWidth) {
strToWrite = strToWrite + charToWrite;
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
}
if (charSize > innWidth) {
strToWrite = strToWrite.slice(0,-1);
}
$('#charSize').remove();
textObj.text(textObj.text() + '\n' + strToWrite);
}
$(function () {
writeMaxNumCharsInOneLine($('#text'), 'Y')
writeMaxNumCharsInOneLine($('#text'), 'a')
writeMaxNumCharsInOneLine($('#text'), 'b')
writeMaxNumCharsInOneLine($('#text'), 'c')
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div id="text" style="border: double;width: 50%;height: 100px;"></div>
Next time you may want to add more information as well as what you have tried, your question doesn't show much troubleshooting on your side; however I think the code below should work or help you figure out something for what you are trying to do.
var w = $(document).width();
var d = $("#text").width();
var s = "";
do{
s+= "X";
$("#text").text(s)
d = $("#text").width();
}
while(d < w)
<div>
<span id="text"></span>
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function() {
var b=$( "<span padding=0 margin=0></span>").appendTo( $("#text") );
do {
$(b).append("M");
} while ($(b).width() < $(b).parent().width() )
});
});
</script>
</head>
<body>
<div id="text"></div>
<button>Click me</button>
</body>
</html>
You mean this?
$(function() {
var windowWidth = $(window).width();
var oneCharacterWidth = $("#text").width();
var total = windowWidth / oneCharacterWidth;
$("#text").html("");
for (i = 0; i < total; i++) {
$("#text").append("c");
}
})
#text {
display:inline;
font-size:12px;
}
body {
margin:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">c</div>
I'm using a word count textarea jquery script and I'm trying to work out how to update the word count onload to e.g. 2 from the preset text area "this example" to start with.
(it currently shows 0)
I can set the focus on it and move the cursor but I don't know how to update it initially, any ideas?
HTML
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="js/jQuery.textareaCounter.c.js"></script>
<textarea id="txtarea" name="text" rows="7" cols="120">this example</textarea>
<script type="text/javascript">
$("textarea").textareaCounter();
document.getElementById('txtarea').focus();
var val = document.getElementById('txtarea').value; //store the value of the element
document.getElementById('txtarea').value = ''; //clear the value of the element
document.getElementById('txtarea').value = val; //set that value back. so cursor is at end.
</script>
jquery.min.js contains:-
(function(a){a.fn.textareaCounter=function(b){var c={limit:10};var b=a.extend(c,b);return this.each(function(){var c,d,e,f;c=a(this);c.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+b.limit+" words</span>");c.keyup(function(){d=c.val();if(d===""){e=0}else{e=a.trim(d).split(" ").length}if(e>b.limit){a("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');f=a.trim(d).split(" ",b.limit);f=f.join(" ");a(this).val(f)}else{a("#counter-text").html(b.limit-e+" words left")}})})}})(jQuery)
jQuery.textareaCounter.c.js contains:-
(function(a) {
a.fn.textareaCounter = function(b) {
var c = {
limit: 10
};
var b = a.extend(c, b);
return this.each(function() {
var c, d, e, f;
c = a(this);
c.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">' + "0 words</span>");
c.keyup(function() {
d = c.val();
if (d === "") {
e = 0
} else {
e = d.replace(/^[\s,.;]+/, "").replace(/[\s,.;]+$/, "").split(/[\s,.;]+/).length;
}
if (e > b.limit) {
// a("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
// f=a.trim(d).split(" ",b.limit);
// f=f.join(" ");
// a(this).val(f)
a("#counter-text").html(e + " words ")
document.myform.numwords.value = e;
} else {
a("#counter-text").html(e + " words ")
document.myform.numwords.value = e;
}
});
});
}
})
(jQuery)
This is what I changed in jQuery.textareaCounter.c.js:
var initCount = c.text().split(" ").length;
if(initCount < 2){initCount=0;}
c.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">' + initCount +" words</span>");
Here is the JSFiddle demo
You can fire a keyup event during initialization to trigger the update:
<script type="text/javascript">
$("textarea").textareaCounter();
document.getElementById('txtarea').focus();
var val = document.getElementById('txtarea').value; //store the value of the element
document.getElementById('txtarea').value = ''; //clear the value of the element
document.getElementById('txtarea').value = val; //set that value back. so cursor is at end.
// init word count
$("textarea")[0].dispatchEvent(new Event('keyup'));
</script>
//Function to show maxlength of Textarea
document.getElementById("textArea").addEventListener("keyup",function(){
var textAreaValue = document.getElementById("textArea").value;
var show = (250 - (textAreaValue.length));
document.getElementById('count').innerHTML = show + " characters remaining";
});
Nice code, just wondered if it is possible to query and get the ellipsis text (i.e. with the dots in and not the original text)?
If I add the text
This is a long sentence
and (using the relevant css for ellipsis) it gets shortened to
This is a long sen ...
Is there a way to get the text
"This is a long sen ..."
from the $("p") DOM object rather than the original text?
Try that:
function getEllipsis(command, characters) {
for (var i = command.length; i >= 0; i--) {
if (command.substring(0, i).length < characters) {
if (i < command.length) {
command = command.substring(0, i) + "...";
}
return command;
}
}
}
console.log(getEllipsis("I am a long sentence",16))
console.log(getEllipsis("But I am even longer",20))
I have a rough draft that needs some browser-specific tweaking.
JavaScript:
jQuery.fn.getShowingText = function () {
// Add temporary element for measuring character widths
$('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div>');
var longString = $(this).text();
var eleWidth = $(this).innerWidth();
var totalWidth = 0;
var totalString = '';
var finished = false;
var ellipWidth = $('#Test').html('…').innerWidth();
var offset = 7; // seems to differ based on browser (6 for Chrome and 7 for Firefox?)
for (var i = 0;
(i < longString.length) && ((totalWidth) < (eleWidth-offset)); i++) {
$('#Test').text(longString.charAt(i));
totalWidth += $('#Test').innerWidth();
totalString += longString.charAt(i);
if(i+1 === longString.length)
{
finished = true;
}
}
$('body').remove('#Test'); // Clean up temporary element
if(finished === false)
{
return totalString.substring(0,totalString.length-3)+"…";
}
else
{
return longString;
}
}
console.log($('#ellDiv').getShowingText());
CSS:
#Test {
padding:0;
border:0;
height: auto;
width: auto;
position:absolute;
white-space: pre;
}
div {
width: 100px;
white-space: nowrap;
border: 1px solid #000;
overflow:hidden;
text-overflow:ellipsis;
padding:0;
}
With the caveat that the offset needs to change depending on the browser, unless someone can figure out what is causing it.
I suspect letter-spacing or similar?