Change css property in chain - JavaScript - javascript

I'm using MooTools 1.4.5 and I want to change cursor before calling function that takes some time and after finished same function set cursor to default. I was not successful.
After that I made simple example to change background color via plain JavaScript (no jQuery or MooTools plugin) and again I was not successful.
Here is my code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
<script type="text/javascript">
<!--
document.body.style.background = 'red';
setTimeout(function () { }, 1250);
document.body.style.background = 'yellow';
//-->
</script>
</html>
First at all I set background color to red, and after delay to yellow. I assumed that the background color will bi set to red and after delay to yellow. It doesn't work. When page is loaded background color is yellow (last line). If I insert alert function in a middle of lines where sets background color everything works fine (background color is red, click to message box, background color is yellow).
Why it works so? Only last changing style is affected. I need something like that to change pointer before calling function that takes 10 seconds and setting cursor to default value after function is done.

setTimeout doesn't mean "wait". It calls the function you give it sometime later. The flow of execution continues immediately:
document.body.style.background = 'red';
setTimeout(function () {
document.body.style.background = 'yellow';
}, 1250);
As such, this works too:
setTimeout(function () {
document.body.style.background = 'yellow';
}, 1250);
document.body.style.background = 'red';
For the case of a cursor, just replace .background = 'red' with .cursor = 'wait' and .background = 'yellow' with .cursor = 'default'.
document.body.style.cursor = 'wait';
setTimeout(function() {
doSomethingExpensive();
document.body.style.cursor = 'default';
}, 10);

The first parameter of setTimeout() is a callback function, which will be called after the delay, you should use this kind of code :
document.body.style.background = 'red';
document.body.style.cursor = 'wait';
setTimeout(function(){
document.body.style.background = 'yellow';
document.body.style.cursor = 'default';
}, 1250);
body {
width: 100%;
height: 100%;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam nibh. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit. Lorem ipsum.
See more about setTimeout here

Related

How Save document.body to variable and load from that variable again

The $("body").load("myUrl") function in jQuery allows the html content of a file to be loaded into the body, in which case all the scripts in the html file in the body are loaded and executed correctly.
How to provide html content from a variable to body instead of loading it from a file. For example, consider that:
in index.html:
<script>
window.keeper = null;
function callForm2() {
window.keeper = window.document.body;
$("body").load(
"Form2.html"
);
}
function closeForm2() {
window.document.body = window.keeper;
}
</script>
in callForm2 Before the body content is called from a file, the current body content stored in a window.keeper variable.
in closeForm2() , I want to take the content from the window.keeper variable (old body content) and set to current body, in which case the content of the variable is not equal to the previously saved one, and I can not return the original content of the variable.
So how do I save the current body content of a variable for the next call?
What is the correct way to save and call in this case?
here is my code: (you can also see https://github.com/yarandish/Challenge2)
Consider the following.
window.keeper = {};
$(function() {
$("#psudo_body > p").click(function() {
window.keeper.html = $("#psudo_body").html();
window.keeper.text = $("#psudo_body").text();
console.log("Stored", window.keeper);
var form = $("<form>", {
id: "myForm"
});
$("<button>", {
type: "submit"
}).html("Done").appendTo(form);
$("#psudo_body").html(form);
});
$("body").on("submit", "#myForm", function(event) {
event.preventDefault();
$("#psudo_body").html(keeper.html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="psudo_body">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In condimentum elit sit amet mi molestie, ac commodo nibh blandit. Proin a tellus efficitur dui commodo varius. Nullam massa nunc, mollis in finibus ac, volutpat eu urna. Maecenas quis sodales
felis, non finibus lorem. Aliquam tristique, dolor vitae consequat commodo, augue sem porta ex, eu tincidunt lectus orci ut elit. Integer nec enim eu erat pulvinar pretium eu id lorem. Sed et dapibus ligula, a rhoncus augue. Fusce et purus in diam
aliquet accumsan. Curabitur mattis, ante quis tempor luctus, ante sapien dignissim metus, sit amet maximus ante lorem eu turpis. Praesent in sodales velit. Suspendisse varius ornare faucibus. Suspendisse maximus erat sodales, tincidunt nulla sit amet,
fermentum ligula. Donec sed sollicitudin nunc. Phasellus vitae mauris bibendum, fringilla orci id, sodales libero. Donec at ullamcorper lectus. Proin dui enim, venenatis quis euismod vulputate, blandit sit amet nibh.</p>
</div>
This would work for body element as well.
You can also use .data() in a similar way.
$(function() {
$("#psudo_body > p").click(function() {
$("#psudo_body").data("keeper", $("#psudo_body").html());
var form = $("<form>", {
id: "myForm"
});
$("<button>", {
type: "submit"
}).html("Done").appendTo(form);
$("#psudo_body").html(form);
});
$("body").on("submit", "#myForm", function(event) {
event.preventDefault();
$("#psudo_body").html($("#psudo_body").data("keeper"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="psudo_body">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In condimentum elit sit amet mi molestie, ac commodo nibh blandit. Proin a tellus efficitur dui commodo varius. Nullam massa nunc, mollis in finibus ac, volutpat eu urna. Maecenas quis sodales
felis, non finibus lorem. Aliquam tristique, dolor vitae consequat commodo, augue sem porta ex, eu tincidunt lectus orci ut elit. Integer nec enim eu erat pulvinar pretium eu id lorem. Sed et dapibus ligula, a rhoncus augue. Fusce et purus in diam
aliquet accumsan. Curabitur mattis, ante quis tempor luctus, ante sapien dignissim metus, sit amet maximus ante lorem eu turpis. Praesent in sodales velit. Suspendisse varius ornare faucibus. Suspendisse maximus erat sodales, tincidunt nulla sit amet,
fermentum ligula. Donec sed sollicitudin nunc. Phasellus vitae mauris bibendum, fringilla orci id, sodales libero. Donec at ullamcorper lectus. Proin dui enim, venenatis quis euismod vulputate, blandit sit amet nibh.</p>
</div>
See Also: Storing a variable in the JavaScript 'window' object is a proper way to use that object?
I Solved you problem and putting demo here.
Your Solution is here:
https://github.com/Master2V/FormCallSolution.git
In index.html put this script in head:
<script>
window.keeper = null;
function callForm2() {
var $body_page = $('body #Page');
window.keeper = $body_page;
$body_page.detach();
$.ajax({
type: "GET",
url: "Form2.html",
data: "",
dataType: "html",
success: function (response) {
$("body").html(response);
}
});
}
function closeForm2() {
var $body_page = $('body #Page');
$body_page.detach();
var $body = $('body');
$body.append(window.keeper);
}
</script>
And you must have a div tag with id="Page" in index.html and any other forms that you want to call.

Positioning style.left for DIV with javascript does not work

I just want to make a DIV jiggle on mouse stop. So I thought I'd set the style.left property using javascript and some timers. To simulate a mouse stop even, I created a timer that is set and cleared as long as the mouse is moving. When the mouse stops, the timer is no longer cleared, and the simulated event "fires." This sets up three more timers. First timer moves the DIV left by 5 pixels. Next timer moves the DIV right by 5 pixels. Final timer moves DIV back to original position.
Sounds easy, and the style.left property of the DIV gets written to the console, which reports the correct values.
But...I never see the DIV move. Why????
The complete code is:
var jLeft = document.getElementById('jiggle').style.left;
function myMoveFunction() {
//Keep clearing and setting the timeout event as long as the mouse is in motion.
//When the mouse stops, the timeout event will fire.
if (typeof touchTimeout == 'undefined') {
touchTimeout = setTimeout(myTimeOut, 50);
} else {
clearTimeout(touchTimeout);
touchTimeout = setTimeout(myTimeOut, 50);
}
//If the mouse is in motion, clear all jiggling events
if (typeof jigLeft !== 'undefined') clearTimeout(jigLeft);
if (typeof jigRight !== 'undefined') clearTimeout(jigRight);
if (typeof jigZero !== 'undefined') clearTimeout(jigZero);
console.clear();
}
function myTimeOut() {
//set up all jiggling events
setTimeout(jigLeft(), 1);
setTimeout(jigRight(), 50);
setTimeout(jigZero(), 99);
}
function jigLeft() {
jLeft = '45px';
console.log('Move Left: ' + jLeft);
}
function jigRight() {
jLeft = '55px';
console.log('Move Right: ' + jLeft);
}
function jigZero() {
jLeft = '50px';
console.log('Move Zero: ' + jLeft);
}
DIV#jiggle {
position: absolute;
left: 50px;
top: 10px;
width: 500px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id='jiggle' onmousemove="myMoveFunction()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id libero a enim semper bibendum. Suspendisse sodales vulputate posuere. Nulla ac blandit neque, ultricies molestie eros. Donec mauris dolor, rhoncus ac varius sit amet, condimentum sed libero.
Nunc pellentesque quam odio, sit amet vulputate justo blandit sit amet. Sed lorem eros, aliquet at ex quis, cursus gravida urna. Aliquam erat volutpat. Suspendisse rhoncus vulputate nisi non ornare. Proin tincidunt sollicitudin elit, eget aliquam
nisi bibendum at. Duis eget lectus nisi. Praesent nec purus efficitur, pharetra felis sit amet, varius magna. Donec eu justo pretium metus sagittis congue id et lacus. Fusce posuere lacinia nulla a elementum. Nulla consequat mauris orci, ullamcorper
viverra arcu tincidunt sed. Morbi a sem porta est tincidunt semper eu sit amet quam. Integer placerat non risus et elementum. Phasellus eu orci viverra, aliquet est id, condimentum leo. Nunc ac interdum nunc. Morbi at risus nunc. Morbi semper turpis
elit, vel lacinia elit congue id. Maecenas cursus, tellus condimentum pulvinar viverra, ante orci placerat erat, vitae pharetra urna neque quis sem. Nullam non sollicitudin ante, at iaculis sem. Mauris sagittis eros dolor, vitae tempus libero gravida
in. Suspendisse et placerat urna, sed tincidunt nulla. Nam tincidunt pulvinar nisi in condimentum. Sed sem ante, scelerisque eget nulla vitae, elementum mattis turpis. Vestibulum in imperdiet risus. Vestibulum aliquam augue nec tristique pretium.
Nullam vestibulum, felis ut iaculis interdum, ante enim suscipit justo, ac consequat lacus nulla vel turpis. Sed lacinia, leo vel hendrerit aliquet, elit lectus tempor augue, tincidunt condimentum turpis erat eget ipsum. Nam lectus nibh, laoreet sed
accumsan nec, ullamcorper suscipit lectus. Cras faucibus in elit vitae interdum. Morbi vulputate sapien lacus, vel aliquet erat posuere nec. Suspendisse non nibh sapien. Nullam pulvinar diam a aliquam placerat. Donec porttitor commodo nulla, vel egestas
libero facilisis sit amet. Donec eget justo pretium, sagittis ligula in, aliquam orci. Pellentesque ornare purus ut nisi accumsan vehicula. Sed imperdiet dictum odio, in tempor diam rhoncus ut. Mauris vel urna vel turpis cursus facilisis. Suspendisse
eget posuere dolor, eget vulputate massa. Mauris eget ante ac ante accumsan luctus. Curabitur imperdiet condimentum felis, eget faucibus nisl dapibus eu. Curabitur aliquet consectetur dolor, dapibus hendrerit lectus bibendum in. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Ut ligula nisl, malesuada at tortor at, faucibus maximus dolor. Vivamus condimentum mi at est lobortis, quis pulvinar justo consectetur. Cras eu nunc quis velit placerat consectetur. Quisque dui felis, placerat
id tempor eget, maximus ut lacus. In ante lacus, luctus vel turpis lobortis, dictum dictum massa. Curabitur rutrum dolor ut tincidunt venenatis. Vivamus aliquam ante quam, non cursus enim sollicitudin vitae. Sed rhoncus metus tempor scelerisque interdum.
Pellentesque metus mi, varius ac purus et, euismod commodo purus. Donec eu purus consequat, gravida ipsum quis, efficitur eros. Nulla ornare turpis et nulla consectetur feugiat.
</div>
</body>
</html>
In case you're looking for the fixed code, here it is
HTML
<div id='jiggle' onmousemove="myMoveFunction()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id libero a enim semper bibendum. Suspendisse sodales vulputate posuere. Nulla ac blandit neque, ultricies molestie eros. Donec mauris dolor, rhoncus ac varius sit amet, condimentum sed libero. Nunc pellentesque quam odio, sit amet vulputate justo blandit sit amet. Sed lorem eros, aliquet at ex quis, cursus gravida urna. Aliquam erat volutpat. Suspendisse rhoncus vulputate nisi non ornare. Proin tincidunt sollicitudin elit, eget aliquam nisi bibendum at. Duis eget lectus nisi. Praesent nec purus efficitur, pharetra felis sit amet, varius magna. Donec eu justo pretium metus sagittis congue id et lacus. Fusce posuere lacinia nulla a elementum. Nulla consequat mauris orci, ullamcorper viverra arcu tincidunt sed. Morbi a sem porta est tincidunt semper eu sit amet quam.
</div>
CSS
DIV#jiggle{
position:absolute;
left:50px;
top:10px;
width:500px;
}
JS
var jLeft = document.getElementById('jiggle').style.left;
function myMoveFunction(){
//Keep clearing and setting the timeout event as long as the mouse is in motion.
//When the mouse stops, the timeout event will fire.
if (typeof touchTimeout == 'undefined') {
touchTimeout = setTimeout(myTimeOut, 50);
} else {
clearTimeout(touchTimeout);
touchTimeout = setTimeout(myTimeOut, 50);
}
//If the mouse is in motion, clear all jiggling events
if (typeof jigLeft !== 'undefined') clearTimeout(jigLeft);
if (typeof jigRight !== 'undefined') clearTimeout(jigRight);
if (typeof jigZero !== 'undefined') clearTimeout(jigZero);
console.clear();
}
function myTimeOut(){
//set up all jiggling events
setTimeout(jigLeft, 1);
setTimeout(jigRight, 50);
setTimeout(jigZero, 99);
}
function jigLeft() {
document.getElementById('jiggle').style.left ='45px';
console.log('Move Left: ' + jLeft);
}
function jigRight() {
document.getElementById('jiggle').style.left = '55px';
console.log('Move Right: ' + jLeft);
}
function jigZero(){
document.getElementById('jiggle').style.left = '50px';
console.log('Move Zero: ' + jLeft);
}
As pointed out by #Quentin, there's a lot of things wrong with your code. This answer fixes most of them.
Here's a fiddle:
https://codepen.io/faisalrashid/pen/dybVvdQ
Problem 1
document.getElementById('jiggle')
This throws an exception. The element does not exist in the DOM at the time you run it.
Problem 2
var jLeft = document.getElementById('jiggle').style.left;
This copies the value. It does not create a reference.
Later, when you assign to jLeft you change only the value of the variable. Not the value of the property.
Problem 3
setTimeout(jigLeft(), 1);
You're calling jigLeft immediately and assigning the return value as the function to run later. It doesn't return a function.
Problem 4
(typeof jigLeft !== 'undefined')
This will never be undefined. It will always be a function.

simple javascript if statement not working

I have a simple script inside my html file that changes the opacity of a div depending on the result of the $(window).scrollTop() function. So if I scroll over a certain point the div appears and if I scroll back behind that point it should disappear again.
This works fine:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
});
The logic for changing the opactiy back to 0 is missing. So I simply changed the code to:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
if ($(window).scrollTop() < $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
All of the sudden the whole script won't work anymore! Why?
I don't see any mistakes. I also tried it with else like this:
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
} else {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
Won't work either. I am stuck. :(
It's a small thing, but your code currently re-hides the same element every time the window scrolls. You might want to consider modifying your if statement to be slightly more selective:
var toggleMe = $("#m-nav");
$(window).scroll(function() {
var myWindowTop = $(document).scrollTop();
var myContentTop = $(".content-pane").offset().top;
// I'm checking the scroll position AND
// the visibility of my toggled div.
// This way, the if statement only runs
// once rather than constantly stacking.
if (myWindowTop > myContentTop && toggleMe.css("opacity") == "0") {
console.log("showMe!");
toggleMe.animate({
opacity: "1"
}, 500);
} else
// I'm checking the scroll position AND
// the visibility of my toggled div.
// This way, the if statement only runs
// once rather than constantly stacking.
if (myWindowTop < myContentTop && toggleMe.css("opacity") == "1") {
console.log("hideMe!");
toggleMe.animate({
opacity: "0"
}, 500);
}
});
.content-pane {
border: 1px dotted red;
}
.content-pane p {} #m-nav {
position: fixed;
top: 20px;
left: 5px;
background-color: #ccc;
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus
convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<div class="content-pane">
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl
tempus convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<p>Donec rutrum congue leo eget malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie
malesuada. Nulla porttitor accumsan tincidunt.</p>
<p>Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit
amet dui. Quisque velit nisi, pretium ut lacinia in, elementum id enim.</p>
<p>Quisque velit nisi, pretium ut lacinia in, elementum id enim. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Proin eget tortor risus. Curabitur non nulla sit amet nisl
tempus convallis quis ac lectus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.</p>
<p>Donec rutrum congue leo eget malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vivamus suscipit tortor eget felis porttitor volutpat. Donec sollicitudin molestie
malesuada. Nulla porttitor accumsan tincidunt.</p>
<p>Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Pellentesque in ipsum id orci porta dapibus. Vestibulum ac diam sit amet quam vehicula elementum sed sit
amet dui. Quisque velit nisi, pretium ut lacinia in, elementum id enim.</p>
</div>
<div id="m-nav">
<h2>
FOO BAR FOO BAR
</h2>
</div>
I didn't look to deep into it yet but at first glance my instinct says it should be an if and else if.
$(window).scroll(function () {
if ($(window).scrollTop() > $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "1"}, 500);
};
else if ($(window).scrollTop() < $("#m-product-sweater").offset().top) {
$("#m-nav").animate({opacity: "0"}, 500);
};
});
You may also want to play choose something other than .offset().top for the second thing because then it may be trying to do both of them at the same spot since they're both referencing the top of the div I believe.
Edit: As some are commenting, changing the > & < may also correct it.

link for max characters in javascript not working

Ive got a js that runs to see if a maximum amount of characters is reached. Its got text along with href, but when the max amount of characters is reached, the link doesnt work and converts it to just text. When the limit of less then 580 characters, link works. When it does reach the limit, the read more link does work. Any advice or help please and thanks
$(document).ready(function () {
var stylistText = $('#stylistText');
var stylistText2 = document.getElementById("stylistText").innerHTML;
var countActualText = stylistText2.valueOf().length;
var maxLength = 580;
var aElement = document.createElement('a');
var linkText = document.createTextNode(" ...Read more");
aElement.appendChild(linkText);
aElement.href = "#";
if (countActualText > maxLength) {
stylistText.text(stylistText.text().substring(0, 580));
stylistText.append(aElement);
}
});
here is the html
<div class="stylistInfo">
<img id="stylistPhoto" src="images/Test.jpg" alt="peekaboo beans stylist" />
<p id="stylistText">
This is supposed to be a link Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.
</p>
</div>
Change stylistText.text(stylistText.text().substring(0, 580));
to stylistText.html(stylistText.html().substring(0, 580));
However, truncating a block of text that contains HTML may cause other problems, especially if the truncation occurs in the middle of an element. I would recommend rethinking your whole strategy on this.

resize textbox automatically according to the content

http://jsfiddle.net/h2vMN/1/
I have a text box text inside it already, in the actual application this will be filled dynamically, but for the sake of this question it has been pre filled.
<textarea id="textarea">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempor commodo ornare. Donec lobortis dui sed lectus egestas tristique. Vivamus vel metus turpis, faucibus varius risus. Aenean ante mauris, ultrices id facilisis vitae, dignissim eget sem. Quisque sed justo lectus, eget aliquet leo. Curabitur in mauris et diam fermentum venenatis. Proin ullamcorper, neque a vehicula euismod, odio enim aliquam ipsum, eu tristique urna sapien nec erat.
Aliquam erat volutpat. In in lacus cursus dolor pellentesque posuere. Cras eu metus urna, a rhoncus ligula. Ut hendrerit orci in arcu dignissim id fermentum orci vulputate. Sed ante ligula, volutpat eu convallis vel, auctor in metus. Mauris euismod, metus eget venenatis sodales, risus tellus volutpat elit, et aliquet massa tellus ut sapien. Mauris tempor posuere massa et consectetur. Duis dignissim enim a nulla ultricies vitae vulputate felis commodo. Phasellus mollis est eget odio porttitor consequat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ut nibh auctor libero sagittis semper vitae quis erat.
</textarea>​
When I run the above code, it shows a tiny text area with scroll bars all over it. In other words, completely useless in terms of being user friendly. How do I automatically resize the text box according to the amount of content their is and it has a set width of 600px.
#textarea{width:600px;}​
I would like a javascript/jquery solution.
I have tried the .autoresize solution unsuccessfully, which can be found here:
http://james.padolsey.com/demos/plugins/jQuery/autoresize.jquery.js/view
Note, the height should be resized automatically
Thy this:
$(document).ready(function(){
tx = $('#textarea')
tx.height(tx.prop('scrollHeight'));
})
DEMO
$(document).ready(function(){
var heightFudgeFactor = 10;
var id = 'tempid' + Date.now();
$('#textarea').after( $('<div>').css('font-family','monospace').css('white-space','pre-wrap').css('word-wrap','break-word').attr('id',id).css('width',$('#textarea').width()).text( $('#textarea').text() ) );
$('#textarea').css('height',$('#'+id).outerHeight() + heightFudgeFactor).next().remove();
});​
Here's one way of doing it, I'm creating a secondary div that's the height of the textarea, based on content, but you'll need to play with it a little more to get it to your actual liking
I once used this plugin: http://www.jacklmoore.com/autosize
It worked fine.

Categories

Resources