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.
Related
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.
I have a site with navigation like:
<ul>
<li>
Link 1
</li>
<li>
Link 2
</li>
<li>
Link 3
</li>
<li>
Link 4
</li>
</ul>
When a user clicks on any of the links, the main content from each of the urls will be loaded onto one page, and the page scrolls down to the relevant section. I've tried something like below but it doesn't seem like the best solution. Is there a better way of doing this? Thanks. Should also point out that the code below doesn't work correctly, it loads the content more than once and in a random order.
$( "ul > li > a" ).each(function(index) {
var newhref = $(this).attr('href');
$.get(newhref).done(function (html) {
$(".main-copy").append($(html).find(".main-copy"));
});
});
To begin with I would suggest that each link should be inside it's own -li- like this:
<ul>
<li>
Link 1
</li>
<li>
Link 2
</li>
<li>
Link 3
</li>
<li>
Link 4
</li>
</ul>
As for the JQuery, something like this should do the trick:
$( "ul > li > a" ).click(function(){
$(".main-copy").load($(this).attr('href'));
});
I hope that sets you on the right path
Are these links hard-coded or dynamically generated?
In either case, get all these links into a JavaScript Array:var links=['link1','link2'...]
Since you want to dump all the content by navigating through each of these links, you can loop-through links and append content
for(i=0;i<links.length;i++) {
var link = links[i];
$.ajax(link).done(function(htmlContent){
//set contents to some section or div
});
}
Now the links themselves can be a #href tags with-in the page.
My suggestion would be not to navigate using Jquery on UL -> LI path to get the list of links.
If the load thing is working, are you simply looking at the scrolling thing? Try something like this:
// Creating a dummy namespace, as I don't have content to actually load via ajax.
var myNameSpace = {
"link1": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link2": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link3": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>",
"link4": " <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.</p><p>Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur aliquet quam id dui posuere blandit. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Nulla porttitor accumsan tincidunt. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Curabitur aliquet quam id dui posuere blandit.</p><p>Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Cras ultricies ligula sed magna dictum porta. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Curabitur aliquet quam id dui posuere blandit.</p>"
};
// Take each of the navigation elements, and use them to create the content sections
$("nav a").each(function() {
/***
* This would be where you'd first want to load
* your HTML content, rather than using the namespace.
***/
// Get the actual text of the anchor, we'll use that later
var target = $(this).attr("href").substring(1);
// create the section tag...
var myTargetEl = document.createElement("section");
// set the id for the link to use as a target
$(myTargetEl).attr("id", target).append("<h2>" + target + "</h2>").append(myNameSpace[target]);
// Add the section we've created to the content pane
$(".content-pane").append(myTargetEl);
// AND CHANGE THE ACTUAL LINK -- I don't want to reload
// this content every time!
$(this).attr("href", "#" + target);
});
$("nav a").click(function() {
var target = $($(this).attr("href"));
if (target.length) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
})
nav {
position: fixed;
left: 10px;
top: 10px;
float: left;
width: 100px;
background-color: #ccc;
}
.content-pane {
position: relative;
left: 120px;
width: 400px;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
Content 1
Content 2
Content 3
Content 4
</nav>
<div class="content-pane">
</div>
As far as the load thing goes, simply load each link into its own section tag. In fact, use the link list to create the section blocks, so that if you add more navigation elements, they'll load dynamically.
Modified the code so that there are no sections being inserted manually, they're created by the link tags themselves. As to how you'd load them, you seem to be doing that all right -- all you're missing is the changing the link's HREF to point to the appropriate section each time.
This question already has answers here:
How to set file input value when dropping file on page? [duplicate]
(1 answer)
How to set File objects and length property at FileList object where the files are also reflected at FormData object?
(1 answer)
Closed 5 years ago.
I have a form page that has a file upload field and I am trying to set the value of that field programmatically and although I know that it isn't possible due to security reasons, I would like to know if we still can? If there is a plugin or something that I could use to perform the upload. I have the Base64 value of the file field that is required to set that field, all I need to know is if there is a way to set it.
Any suggestions or help would be great in this regard.
Thanks.
Update:
Added a JsFiddle to demonstrate what I'm trying out.
Please visit this website to create a text file using the example in the js fiddle and convert it using this link.
var str = `text`;
http://www.motobit.com/util/base64-decoder-encoder.asp
JsFiddle
Note:
The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.
See the answer in this question for details as well as a demo:How to set file input value programatically (i.e.: when drag-dropping files)?
You can convert the base64 string to a blob and then add it to the formData before submitting it with an ajax request:
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob("base64 string");
formData.append("yourfile", blob);
$.ajax({
url: "whatever.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("Form has been submitted with file");
}
});
dataURLtoBlob is a function that converts the base64 string to the binary file (blob) source: Blob from DataURL?
Update: Added a JsFiddle to demonstrate what I'm trying out.
#seahorsepip Answer, minimally adjusted to substitute success for done which is not a defined $.ajax() setting, and removing trailing ; following done:function(){}, which logs a syntax error, should return expected result. Where convertedvalue at linked jsfiddle at updated Question is also adjusted to a valid data URI. That is, after converting string to base64, use the "data" URL scheme to convert base64 string to valid data URI; e.g.,
"data:text/plain;base64," + convertedvalue
Note, File object created at FormData is requested with GET and returned at success at stacksnippets and jsfiddle to demonstrate file within FormData POSTed by $.ajax()
var convertedvalue = btoa(str); // where `str` is string
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
// pass valid `data URI` to `dataURItoBlob`
// note `base64` extension
var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
formData.append("yourfile", blob);
$.ajax({
url: "/path/to/server",
type: "POST",
data: formData,
contentType: false,
cache: true,
processData: false,
// substitute `success` for `done`
success: function(data) {
//alert("Form has been submitted with file");
} // remove trailing `;`
});
})
var str = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Images:
1) Copy and replace the following files in the /images folder
i. 1icon.png
ii. 2icon.png
iii. 3icon.png
iv. mobil-app.png
v. mobil-app-this.png
vi. properties-icon.svgz
vii. setupLogo.svgz
viii. web-app.png
ix. web-app-this.png`;
var convertedvalue = btoa(str);
console.log(convertedvalue);
$("#b64text").html(convertedvalue);
$("input[type=submit]").prop("disabled", false);
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {
type: mimeString
});
return blob;
// Old code
// var bb = new BlobBuilder();
// bb.append(ab);
// return bb.getBlob(mimeString);
}
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
// pass valid `data URI` to `dataURItoBlob`
var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
formData.append("yourfile", blob);
$.ajax({
url: URL.createObjectURL(formData.get("yourfile")),
type: "GET",
// data: formData,
contentType: false,
cache: true,
processData: false,
success: function(data) {
console.log(data);
$("#b64text").html(data);
//alert("Form has been submitted with file");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form id="form">
<input type="submit" disabled/>
</form>
<div id="b64text" style=" word-wrap: break-word;">
</div>
jsfiddle https://jsfiddle.net/rccfymrz/17/
The easiest way is to do an AJAX POST request to the form's action field on the <form> tag. This is what the normal HTML does on its own anyways, but in our case you can specify the data programmatically, in this case a multipart file.
For an example, see this question.
It is that simple: file type input accepts the path to file, that would be sent on form submit, not the file itself.
UPD: Well, currently it's a little bit more complex (File API), however this is just meant to give you access to the data the user wants to give you.
You don't actually need to mess with file input to send the file.
If you are the one that owns server, you always can accept base64 string from regular text input field as a valid file (as an alternative to regular file field).
Otherwise you can always use ajax (with text or blob) to send your form.
Simple fileupload without submit form.
HTML
<input id="inputfileUpload" onchange="fileChanged(this);" type="file" accept="*/*" />
JAVACRIPT
function fileChanged(element) {
if (element.files[0]) {
var file = element.files[0];
var reader = new FileReader();
reader.onload = function (e) {
//file.name
//file.size
//Filedata: e.target.result
//You can convert to base64
//Angular sample:
//$base64.encode(e.target.result);
};
reader.readAsBinaryString(file);
}
}
I have the Base64 value of the file field [...] I need to know is if there is a way to set it.
Wouldn't be possible to have an hidden input ?
You set the base64 to that field, as the maximum size of an input type="hidden" is the same as type="file"
This way, you avoid the security reasons preventing you to load the local file, and still let you send the base64 representation.
The only problem is, we don't know how you have this base64 string. Is it loaded from a request ? Already populated from php ? ...
Use jquery:
$('#file_id_here').attr({'value':'file_path_here'})
If you just want to set what file is going to be the value of your file input field, you cannot. But you can set the field to blank for form validation reasons try using JavaScript:
document.getElementById("your-file-form-field-id").value = "";
I'm building a website that is heavily built on ajax. Some of my JS comes as part of the pages that I load through ajax. The functions from the JS cannot be called from other JS scripts that has been loaded earlier. As I have understand it, it has to with the code not being really declared and that I could use eval() on the code. But that feels like waste of resources since the code runs and works aslong it don't need to work with code that is already declared.
My little short ajax page loader.
$(document).ready(function(){
var old = "home"
$("#topMenu a").on("click",function(){
if(typeof edit_menu !== 'undefined' && edit_menu){
return;
}
var link = $(this).attr("data-link");
//Load Ajax
LoadPage(link, old);
});
});
function LoadPage(link, old){
$.ajax({
url: "pages/" + link + ".php",
}).done(function(data){
$("#content").html(data);
});
Hide();
history.pushState(old,null,"?page=" + link);
}
If I login as admin I will then also have an admin JS file loaded as part of the DOM. The script calls a function in another JS file thats is loaded dynamically. The function doesn't run because the admin JS file is not aware of the new funciton.
The dynamically added JS file is a script tag part of other HTML code.
Example of dynamically added code.
<script src="/javascript/projects.js"></script>
<header>Projects</header>
<article>
<h1>First project</h1>
<section class="summary">
Lorem ipsum is da shit
</section>
<section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p> <p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
</section>
<span>Update text</span> <input type="checkbox" class="update_projects" data-id="First project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="1" /><br /><input type="text" name="tag" class="tag" value="php" />
</article><article>
<h1>Secons project</h1>
<section class="summary">
And I'm not lying
</section>
<section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p>
<p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
</section>
<span>Update text</span> <input type="checkbox" class="update_projects" data-id="Secons project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="2" /><br /><input type="text" name="tag" class="tag" value="" />
</article></section>
UPDATE
After some more testing I have found the JS can't find any of my added HTML while the js added on the same time can.
I am trying to understand the question but as i can't comment for the moment some parts of it are not enugh clear, i work with jsfiddle if it can help, is it possible to make a little example not all the code to help me understand what's going on. Starting with
this function for example :
function LoadPage(link, old){
$.ajax({
url: "pages/" + link + ".php",
}).done(function(data){
$("#content").html(data);
});
Hide();
history.pushState(old,null,"?page=" + link);
}
https://jsfiddle.net/3z62n8c2/
Try the following script, this will remove the script from the loaded HTML and load them on to the page before adding the content. Also it makes sure that the same javascript file does not get added multiple times.
function LoadPage(link, old){
$.ajax({
url: "pages/" + link + ".php",
}).done(function(data){
$loadedData = $("<div>"+data+"</div>");
$loadedData.find('script[src]').each(function(i,v){
var jsPath = $(this).attr('src');
if($('[src="'+jsPath+'"]').length == 0){
var tag = document.createElement('script');
tag.src = jsPath;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
});
$loadedData.find('script[src]').remove();
$("#content").html($loadedData.html());
});
Hide();
history.pushState(old,null,"?page=" + link);
}
To load the script you must append it as an HTML element, like this :
}).done(function(data) {
var el = $(document.createElement('div')).html(data);
var scripts = el.find('script');
for(var i = 0; i < scripts.length; i++) {
window.eval(scripts[i].innerHTML);
scripts[i].remove();
}
$('#content').html(el.html());
});
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.