I am working on a ticker that loops text within the body of a div. I can get it to move the text at a specified rate but I am having trouble figuring out how to get JQuery to loop the text. Once the contents in the div have reached the end, how do I loop it back while still showing rest of the contents from the tail?
Code:
var left = -500;
$(document).ready(function(e){
function tick() {
left++;
$(".ticker-text").css("margin-left", -left + "px");
setTimeout(tick, 16);
}
tick();
});
html:
<div class = "ticker-container">
<div class = "ticker-text">
start text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text end
</div>
</div>
http://jsfiddle.net/mxu4v/1/
Just reset the margin when it gets too far left:
var width = $('.ticker-text').width(),
containerwidth = $('.ticker-container').width(),
left = containerwidth;
$(document).ready(function(e){
function tick() {
if(--left < -width){
left = containerwidth;
}
$(".ticker-text").css("margin-left", left + "px");
setTimeout(tick, 16);
}
tick();
});
Note that the CSS must be changed so that .ticker-text assumes the width of its contents, and not 1000% as you specified:
.ticker-text {
height: 150%;
white-space:nowrap;
display:inline-block;
}
Here is a demonstration: http://jsfiddle.net/fHd4Z/
Just to flesh my comment out into an answer:
As above, I believe you'd be best of using one of the pre existing frameworks designed for this. In terms of a quick knock up of the feature, you could start with something like this: http://jsfiddle.net/B9ruA/
JS:
var tickerId="#tickerText";
function tickify(e) {
var text=$(e).text().split("");
var newText="";
for (var i=0;i<text.length;i++) {
newText+="<span class='tickerChar'>" + text[i] + "</span>";
}
$(e).html(newText);
}
tickify(tickerId);
function tick(){
$(tickerId + " span.tickerChar:first").hide("slide",{direction:"left"},50,function(){$(this).appendTo($(tickerId)).show("slide",{direction:"right"},50);});
}
setInterval(function(){tick()},200);
HTML:
<div id="tickerText"> woo, here is some text for ticking, text that ticks, ticky text to test with </div>
CSS:
div.ui-effects-wrapper {
display:inline;
}
notes:
I had to add some css to stop the animated characters being displayed as block (and thus on their own line). You would probably make the selector more specific to not screw with other animations on the page (if you have any).
Obviously this could do with some timing readjustments for smoothness sake - I couldn't be bothered doing the niggly trial and error work behind that but have fun (another reason to use a framework).
in my comment I mentioned the methods slideLeft and slideRight - they don't exist. my bad.
Related
----------------------------------------------------
| This is my text inside a div and I want the overf|low of the text to be cut
----------------------------------------------------
Please note that I want the overflow to be removed, so the CSS ellipsis property would not work for me. So basically, I want that the text above to appear like this:
----------------------------------------------------
| This is my text inside a div and I want the overf|
----------------------------------------------------
How is this possible with pure JavaScript?
EDIT
I need a JavaScript function to crop the text because I need to count the characters of the visible text.
Okay, I didn't see the addendum to the question. Although I had previously said it wasn't possible to do this using JavaScript and a font that isn't fixed-width... it actually is possible!
You can wrap each individual character in a <span>, and find the first <span> that is outside the bounds of the parent. Something like:
function countVisibleCharacters(element) {
var text = element.firstChild.nodeValue;
var r = 0;
element.removeChild(element.firstChild);
for(var i = 0; i < text.length; i++) {
var newNode = document.createElement('span');
newNode.appendChild(document.createTextNode(text.charAt(i)));
element.appendChild(newNode);
if(newNode.offsetLeft < element.offsetWidth) {
r++;
}
}
return r;
}
Here's a demo.
You can do this with Javascript. Here is a function that counts the number of visible characters in an element, regardless of external css sheets and inline styles applied to the element. I've only tested it in Chrome, but I think it is cross browser friendly:
function count_visible(el){
var padding, em, numc;
var text = el.firstChild.data;
var max = el.clientWidth;
var tmp = document.createElement('span');
var node = document.createTextNode();
tmp.appendChild(node);
document.body.appendChild(tmp);
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(el, null).cssText;
else if(el.currentStyle)
tmp.style.cssText = el.currentStyle.cssText;
tmp.style.position = 'absolute';
tmp.style.overflow = 'visible';
tmp.style.width = 'auto';
// Estimate number of characters that can fit.
padding = tmp.style.padding;
tmp.style.padding = '0';
tmp.innerHTML = 'M';
el.parentNode.appendChild(tmp);
em = tmp.clientWidth;
tmp.style.padding = padding;
numc = Math.floor(max/em);
var width = tmp.clientWidth;
// Only one of the following loops will iterate more than one time
// Depending on if we overestimated or underestimated.
// Add characters until we reach overflow width
while(width < max && numc <= text.length){
node.nodeValue = text.substring(0, ++numc);
width = tmp.clientWidth;
}
// Remove characters until we no longer have overflow
while(width > max && numc){
node.nodeValue = text.substring(0, --numc);
width = tmp.clientWidth;
}
// Remove temporary div
document.body.removeChild(tmp);
return numc;
}
JSFiddle Example
You're trying to force a CSS problem into JavaScript. Put the hammer away and get out a screwdriver. http://en.wiktionary.org/wiki/if_all_you_have_is_a_hammer,_everything_looks_like_a_nail
Solving the answer of character count is probably irrelevant if you take a step back. The last character could be only partially visible, and character count is drastically different given font size changes, the difference of width between W an i, etc. Probably the div's width is more important than the character count in the true problem.
If you're still stuck on figuring out the characters visible, put a span inside the div around the text, use the css provided in other answers to this question, and then in JavaScript trim one character at a time off the string until the span's width is less than the div's width. And then watch as your browser freezes for a few seconds every time you do that to a big paragraph.
try this, it requires a fixed width if that is ok with you: http://jsfiddle.net/timrpeterson/qvZKw/20/
HTML:
<div class="col">This is my text inside a div and I want the overf|low of the text to be cut</div>
CSS:
.col {
width:120px;
overflow: hidden;
white-space:nowrap;
}
.col { width:40px; overflow: hidden; white-space:nowrap; }
White-space: nowrap; is needed when the content has spaces.
Either way, long words in single lines do not appear. http://jsfiddle.net/h6Bhb/
I want to know how to change the background color or may be color of the text that was modified in a textarea.
Like suppose, consider a textarea with a pre-defined value as "Hello World".
Now if you try to change the text inside the textarea to "Hello Universe", it should show Universe highlighted (may be background color change, or color change or make it bold, anything.
I just want to get the modified text to be highlighted so it is visible what was changed.
Highlighting is possible if you make the textarea partially transparent and then had a div behind it where you can clone the content and put span tags around the changed values. The hard part is in figuring out how to diff the string. For an example of highlight certain parts of text "in the text area" see this fiddle:
https://jsfiddle.net/mcgraphix/tn0ahcfx/
<div class="container">
<div id="highlighter"></div>
<textarea id="editor" onkeyup="updateHighlight()"
value="This is some text in the editor"></textarea>
</div>
JS
function updateHighlight() {
//calculate index of changes
//assume chars 1-10 are different //see my comment for how to calculate what to highlight
var content = document.getElementById('editor').value;
var highlighted = '';
var i = 0;
while (i < content.length) {
if (i === 1) {
highlighted += '<span class="highlighted">';
} else if (i > 10) {
highlighted += '</span>'
}
highlighted += content.charAt(i);
i++;
}
document.getElementById('highlighter').innerHTML = highlighted;
}
Basically, as you type the text in the text area is parsed and as text is identified as being in need of highlight, a span tag is wrapped around it. After parsing the text, the copy with the spans is put inside the div that is behind the textarea. With the right css you can hide the text in that div and just put a background color such that it looks highlighted. The fiddle gives you the basic idea but you would have to account for the user resizing the text area as you need to make sure the text area and the "highlighter" behind it are aligned.
The hard part is figuring out what to highlight. such that you don't highlight every character after the first change. Take a look at Levenshtein distance algorithm for determining which characters you need to highlight when comparing two strings.
Keep old value in variable.
Split the value using delimiter as space
Check indexOf new value after spitting by space
Use Array#indexOf to listen the change in value!
Most important point, you can not apply style over characters in textarea. Example given below has a demonstration in div element considering value from textarea
var input = $('textarea');
var div = $('div');
var oldVal = input.val();
var oldArr = oldVal.split(' ');
input.on('input', function() {
var newVal = this.value;
var html = [];
newVal.split(' ').forEach(function(el) {
if (oldArr.indexOf(el) === -1) {
html.push('<span style="color:green">' + el + '</span>');
} else {
html.push('<span>' + el + '</span>');
}
});
div.html(html.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea>Hello World</textarea>
<div></div>
Need some help/pointers....
When the user will click on a p element i want it content to be displayed in an text area so it would be possible to modify the text and etc...
The text area will be of a fixed width.Thus when the last character will be at the right border it will go automatically on a lower row. In this case, in order to make a new row, should i count how many characters fit in the text area fixed width and each time this number is met to add a new row?
Also in the case that the user will break the line before it reaches the right border, should i search for a \n RegExp?(with .match()?)
I think that those 2 cases need to be is a timeInterval(setTimeout perhaps?) to check on a milliseconds basis the all typing that happens. I'm trying to do it with pure Javascript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="p1">text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.
</p>
<div id="holder"></div>
<script type="text/javascript">
var text_to_copy = document.getElementById('p1').textContent;
//every row with a fixed text area width fits 62 characters
var input = document.createElement("textarea");
var holder = document.getElementById("holder");
document.getElementById('p1').onclick = function(){
holder.appendChild(input);
input.id = "textarea_id";
input.style.width = "412px";
input.value = text_to_copy.replace(/\s{1,}/g, ' ');
if(text_to_copy.match('\n')){
input.rows +=1;
}
/*setTimeout(function(){
if ((text_to_copy.length % 62) == 0){
input.rows += 1;
}
},300);*/
}
</script>
</body>
</html>
You can adapt the textarea height to match the scroll height using the clientHeight vs scrollHeight
Here is a working copy of your code
var text_to_copy = document.getElementById('p1').textContent;
var input = document.createElement("textarea");
var holder = document.getElementById("holder");
document.getElementById('p1').onclick = function(){
holder.appendChild(input);
input.id = "textarea_id";
input.style.width = "412px";
input.value = text_to_copy.replace(/\s{1,}/g, ' ');
//This function reset the textarea height base on his content. (when text is added/removed)
var setTextAreaHeight = function(){
input.style.height = '5px'; // Set to minimum height possible to create vertical scroll bars
input.style.height = input.scrollHeight + 'px'; // remove the scroll bars
}
//call it once
setTextAreaHeight();
//attach to changes/key pressing.
input.onkeydown = setTextAreaHeight;
input.onkeyup = setTextAreaHeight;
input.onchange = setTextAreaHeight;
};
<p id="p1">text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text,
text text text text text text text text text text text.
</p>
<div id="holder"></div>
I need to select text from different paragraphs and make a span for showing this text. See this example:
<p> this is a text </p>
<p>hello ever one </p>
Now what I want is that if I select text from the web view in my iPhone app it highlights it in a different color. For this I am making a span and setting its style. It works fine for the same paragraph but not for different paragraphs. See this:
<p> this <span class="blue">is a </span> text </p>
Class blue declares its style and it works fine, but the following does not work:
<span class="blue">
<p> this is a text </p>
<p>hello ever </span> one </p>
For solving this problem I need two spans for both paragraphs. So how can I check where the new paragraph starts? The correct HTML code is:
<span class="blue">
<p> this is a text </p></span>
<p> <span class="blue"> hello ever </span> one </p>
I need to get this HTML string but I get the wrong one. I have written a JavaScript function that gets the selection and makes a span according to selection. But on selecting text from two paragraphs it does not work because it gives the wrong section of HTML code. See my JavaScript code:
function highlightsText()
{
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var div;
var newDate = new Date;
var randomnumber= newDate.getTime();
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
div = document.createElement("span");
div.style.backgroundColor = "yellow";
div.id=randomnumber;
linkTxt.appendChild(imageTag);
div.appendChild(selectionContents);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
Please provide a solution that can resolve this problem.
You could do something along the lines of:
Get highlighted section of text.
Insert span tag at the first point.
For every tag that you come accross within the highlighted text:
If it's an opening tag, check if it's corresponding closing tag is in the highlighted text.
If both opening and closing tags are within the text ignore them and move to the next point after the corresponding closing tag.
If only the opening tag or only the closing tag is present, then insert before the tag and after the tag.
Insert span closing tag at the end of the highlighted text.
Possible problem:
span is intented to group inline elements and not block elements so if your highlighted text includes block elements you could have problems. You could use div instead of span to solve this or you could add some checks to distinguish between inline and block tags.
To look at tag matching:
http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx
To find if the matching closing tag of an element is in the higlighted text (not tested):
function checkClosingTag(position)
{
//Find position of next opening or closing tag along the
//string of highlighted text.
//Return 0 if no more tags.
var nextTag = findNextTag(position);
if(nextTag == 0)
{
return 0;
}
if(!isOpeningTag(nextTag))
{
return nextTag;
}
var nextTagClose = checkClosingTag(nextTag);
if(nextTagClose == 0)
{
return 0;
}
return checkClosingTag(nextTagClose);
}
This looks like a fairly involved problem though - I don't have time to write the code for you but you should be able to work out a way of doing it from here.
some change in your code can work
see this line of codes
function highlightsText()
{
var range, sel;
if (window.getSelection)
{
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
if ( !document.execCommand("HiliteColor", false, "yellow") ) {
document.execCommand("BackColor", false, "yellow");
}
document.designMode = "off";
}
else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.execCommand("BackColor", false, "yellow");
}
var newDate = new Date;
var randomnumber= newDate.getTime();
var nodeList = document.querySelectorAll(".Apple-style-span");
for (var i = 0, length = nodeList.length; i < length; i++) {
nodeList[i].id = randomnumber;
}
var div = document.getElementById(randomnumber);
var imageTag = document.createElement("img");
imageTag.id=randomnumber;
imageTag.setAttribute("src","notes.png");
var linkTxt = document.createElement("a");
linkTxt.id=randomnumber;
linkTxt.setAttribute("href","highlight:"+randomnumber);
div.appendChild(linkTxt);
range.insertNode(div);
return document.body.innerHTML+"<noteseparator>"+randomnumber+"<noteseparator>"+range.toString();
}
You need make some adjustments in this code.
Since your goal (based on what you stated in your question) is to highlight selected text with a different color, here is a solution to that goal.
The HTML5BoilerPlate project includes styles to control the selection color (line 52 in the style.css file)
Here's the CSS for it:
/* Remove text-shadow in selection highlight: h5bp.com/i
*
* These selection declarations have to be separate
*
* Also: hot pink! (or customize the background color to match your design)
*/
::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }
I have a paragragh of user entered text in a textarea.
line1
line2
line3
intially all text would be black
when a button is pressed
each line's color changes to red gradually (2 sec each line)
can this be done with only jquery?
EDIT: Sorry again mate didn't realize you said TEXTAREA this time.
No it cannot be done. However you could do this:
When the button is pressed hide the textarea and display a div in it's place with the content from the textarea. Perform the animation on that instead. Of course it wouldn't be editable anymore but as I don't know what you are trying to achieve this could be a work-around.
Here's an example of above.
<textarea id="ta"></textarea>
<div id="ta_div" style="display:none;"></div>
<br/><input type="button" id="go" value="Go"/>
<script>
$("#go").click(function()
{
var text = document.getElementById("ta").value;
text = "<p>" + text.replace( /\n/g, "</p><p>" ) + "</p>";
$("#ta_div").html( text );
$("#ta").hide();
$("#ta_div").show();
var i = -1;
var arr = $("#ta_div p");
(function(){
if(arr[++i])
$(arr[i]).animate({ color: "#ff0000" }, 2000, "linear", arguments.callee)
})();
});
</script>