Get increment value from input area in a for-loop - javascript

I have done this working fiddle:
HTML
<div id="container">
<div id="input_container">
<label for="increment_t">Set t-increment value (default 0.1):</label>
<input id="increment_t" type="number" min="0" max="1" step="0.1" value="0.1" />
</div>
<br />
<div id="generator_container">
<a id="downloadlink" download="outfile.txt">Download</a>
<button id="create_link">Export output</button>
</div>
</div>
CSS
#container {
position: absolute;
display: block;
left: 0;
top: 0;
padding: 10px 10px; /* (top-bottom) (left-right) */
z-index: 1;
}
#input_container {
display: block;
float: left;
margin-bottom: 10px;
}
#increment_t {
max-width: 50px;
}
#generator_container {
display: block;
float: right;
}
#downloadlink {
display: none;
margin-right: 10px;
}
#create_link {
float: right;
}
JavaScript
(function () {
var t_values;
var t_values_list = [];
for ( var t=0; t<=1; t+=0.1 ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but I want to set the increment value for the "t" variable (i.e. 0.1, in the for-loop) taking it from the input area. I tried in this way:
JavaScript
(function () {
var t_values;
var t_values_list = [];
alert(document.getElementById("increment_t").value); // test to get the t value, to use it in the following loop for
for ( var t=0, increment_t=document.getElementById("increment_t").value; t<=1; t+=increment_t ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but It doesn't work. Thanks for your help

If you getting numbers from somewhere else in javascript...always parse them. parseInt(..., 10) or in your example: parseFloat

Related

JavaScript Todo List - When I click 'edit' button, it doesn't show input to be able to change a todo

I'm building a todo list in vanilla JavaScript as a part of the exercise. I'm trying to get the 'edit' option to function properly. When I click the 'edit' button, the corresponding text input should be enabled, and auto-selected, then the user should be able to press 'enter' to submit changes.
The problem is that I cannot make Edit functional. Two of the other buttons are working well.
I know that there is similar question allready, and I have tried what was in that question, and still cannot get it done. Please help guys.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>To-do List</h1>
</header>
<input type="text" id="addTodoTextInput" onkeyup="todoButtons.addTodo()" placeholder="Add new todo" maxlength="80" autofocus>
<div>
<button onclick="todoButtons.toggleAll()">Toggle All</button>
<button onclick="todoButtons.deleteAll()">Delete All</button>
</div>
<ol>
</ol>
<script src="script.js"></script>
</body>
</html>
css
body {
display: flex;
flex-direction: column;
align-items: center;
background-color: #eee; /* Lightblue */
font-family: tahoma, sans-serif;
}
h1 {
font-weight: 100;
color: brown;
}
ol {
list-style-type: none;
padding-left: 0;
min-width: 30%;
}
li {
padding: 10px;
border-radius: 8px;
background-color: white;
box-shadow: 0 10px 50px black;
margin-top: 10px;
transition: all .3s ease;
overflow: hidden;
}
li:hover {
box-shadow: 0 10px 50px 3px black;
}
li button {
float: right;
}
button {
background-color: #bbb; /* Darkgrey */
font-weight: bold;
border-radius: 5px;
padding: 5px;
transition: all .3s ease;
cursor: pointer;
}
button:hover {
background-color: #d8d2d2; /* Grey */
color: brown;
}
/* Input for adding new todos */
#addTodoTextInput {
width: 30%;
margin-bottom: 20px;
}
js
var todoButtons = {
todos: [],
addTodo: function(e) {
// When Enter is pressed, new todo is made
if (e.keyCode === 13) {
var addTodoTextInput = document.getElementById('addTodoTextInput');
this.todos.push({
todoText: addTodoTextInput.value,
completed: false
});
// Reseting value after user input
addTodoTextInput.value = '';
todoView.displayTodos();
}
},
changeTodo: function(position, newTodoText) {
this.todos[position].todoText = newTodoText;
todoView.displayTodos();
},
deleteTodo: function(position) {
this.todos.splice(position, 1);
todoView.displayTodos();
},
toggleCompleted: function (position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
todoView.displayTodos();
},
toggleAll: function() {
var totalTodos = this.todos.length;
var completedTodos = 0;
// Checks for a number of completed todos
this.todos.forEach(function(todo) {
if (todo.completed === true) {
completedTodos++;
}
});
this.todos.forEach(function(todo) {
// If all todos are true, they will be changed to false
if (completedTodos === totalTodos) {
todo.completed = false;
}
// Otherwise, they will be changed to true
else {
todo.completed = true;
}
});
todoView.displayTodos();
},
deleteAll: function() {
this.todos.splice(0, this.todos.length);
todoView.displayTodos();
}
};
// Function for displaying todos on the webpage
var todoView = {
displayTodos: function() {
var todosUl = document.querySelector('ol');
todosUl.innerHTML = '';
// Creating list element for every new todo
for (var i = 0; i < todoButtons.todos.length; i++) {
var todoLi = document.createElement('li');
var todoLiText = document.createElement('input');
todoLiText.type = "text";
todoLiText.disabled = true;
todoLiText.id = 'textInput';
var todoTextWithCompletion = todoButtons.todos[i].todoText;
if (todoButtons.todos[i].completed === true) {
todoLi.style.textDecoration = "line-through";
todoLi.style.opacity = "0.4";
todoLi.textContent = todoButtons.todoText + ' ';
}
else {
todoLi.textContent = todoButtons.todoText + ' ';
}
todoLi.id = i;
todoLiText.value = todoTextWithCompletion;
todoLi.appendChild(this.createDeleteButton());
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createEditButton());
todoLi.appendChild(todoLiText);
todosUl.appendChild(todoLi);
};
},
// Method for creating Delete button for each todo
createDeleteButton: function() {
var deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'deleteButton';
return deleteButton;
},
// Method for creating Toggle button for each todo
createToggleButton: function() {
var toggleButton = document.createElement('button');
toggleButton.textContent = 'Toggle';
toggleButton.className = 'toggleButton';
return toggleButton;
},
// Method for creating Edit button for each todo
createEditButton: function() {
var editButton = document.createElement('button');
editButton.textContent = 'Edit';
editButton.className = 'editButton';
return editButton;
},
// Event listeners gor the Delete, Edit and Toggle buttons
setUpEventListeners: function() {
var todosUl = document.querySelector('ol');
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'deleteButton') {
// Path to the ID of each created todo
todoButtons.deleteTodo(parseInt(position));
}
});
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'toggleButton') {
todoButtons.toggleCompleted(parseInt(position));
}
});
todosUl.addEventListener('click', function(event) {
var position = event.target.parentNode.id;
var elementClicked = event.target.className;
if (elementClicked === 'edit') {
var input = document.getElementById(position).childNodes[0];
input.disabled = false;
input.className = "activeTextInput";
input.focus();
input.select();
input.addEventListener('keyup', function(event) {
if(event.keyCode === 13) {
var textInput = input.value;
input.disabled = true;
input.classList.remove("activeTextInput");
todoButtons.changeTodo(position, textInput);
};
});
};
});
}
};
// Starting event listeners when the app starts
todoView.setUpEventListeners();
So, I looked at the code. The first problem is the condition:
if (elementClicked === 'edit') {
It should be:
if (elementClicked === 'editButton') {
The second problem was:
if (elementClicked === 'edit') {
var input = document.getElementById(position).childNodes[0]; //this line
input.disabled = false;
input.className = "activeTextInput";
It should be var input = document.getElementById(position).querySelector('input'); to get the correct element.
https://jsfiddle.net/nh9j6yw3/1/
Reason for "undefined" :
on line todoLi.textContent = todoButtons.todoText + ' ';
todoButtons.todoText is undefined.

Getting blob image back to file

I am having problem converting image to blob and back to file, I mean when I convert image to blob and display on the page, chose which I want to keep and which I want to remove and after try to convert back to file and append to form data, nothing gets appended to formData and file type and size on new files from blob images are different, how can I change that? Thank you
$(document).on('click', '#addProduct', function(e) {
e.preventDefault();
var arr = [];
for(var q=0; q<$('.image-buttons').length; q++) {
var blob = $('.image-buttons').children('img').attr('src');
var fileOfBlob = new File([blob], 'image'+q);
arr.push(fileOfBlob);
}
if(arr.length < 4 && arr.length > 0){
var formData = new FormData();
$.each(arr, function(i, file) {
formData.append('images', file);
console.log(file);
});
console.log(formData);
return false;
}
});
$(document).on('change', '#images', function() {
var reg = /\.(gif|jpg|png|GIF|JPG|PNG|jpeg|JPEG)$/i;
var imageNameArray = [];
for(var j = 0; j<$("#images")[0].files.length; j++) {
if(!$("#images")[0].files[j].name.match(reg)){
imageNameArray.push($("#images")[0].files[j].name);
}
}
if(imageNameArray.length === 0 && $("#images")[0].size<2097152){
for(var e=0; e<$("#images")[0].files.length; e++) {
$('.img-button-holder').append('<div class="image-buttons"><img src="'+window.URL.createObjectURL($("#images")[0].files[e])+'"><div class="img-tools"><i class="fa fa-angle-double-left" aria-hidden="true"></i><i class="fa fa-angle-double-right" aria-hidden="true"></i><i class="fa fa-times removeImg" aria-hidden="true"></i></div></div>');
}
$('.image-display').append('<img src="'+window.URL.createObjectURL($("#images")[0].files[0])+'">');
}
});
$(document).on('click', '.image-buttons', function() {
var this_img = $(this).children('img').attr('src');
$('.image-buttons').css('border','1px solid #e0e0e0');
$(this).css('border','2px solid red');
$('.image-display').children('img').attr('src', this_img);
});
$(document).on('click', '.img-tools > .fa', function() {
var this_el = $(this).parent().parent();
if($(this).hasClass('removeImg')){
$(this_el).remove();
}else if($(this).hasClass('fa-angle-double-left')) {
var prev = $(this_el).prev();
$(this_el).insertBefore(prev);
}else if($(this).hasClass('fa-angle-double-right')) {
var next = $(this_el).next();
$(this_el).insertAfter(next);
}
});
.addNew {
width: 100%;
height: auto;
float: left;
}
.addNew > form {
width: 40%;
float: left;
height: auto;
margin-right: 5%;
}
.addNew > .image-display {
width: 55%;
float: right;
min-height: 300px;
height: auto;
border: 1px solid #e0e0e0;
position: relative;
}
.addNew .image-buttons {
width: 30%;
height: 80px;
margin: 10px 1.5%;
border: 1px solid #e0e0e0;
float: left;
overflow: hidden;
position: relative;
}
.img-button-holder {
width: 55%;
float: right;
}
.image-buttons > img, .image-display > img {
width: 100%;
height: 100%;
min-height: 100%;
min-width: 100%;
}
.image-display > img {
width: 100%;
height: auto;
min-height: auto;
min-width: 100%;
position: absolute;
bottom: 0; left: 0;
}
.img-tools {
color: red;
font-size: 2rem;
position: absolute;
width: 100%;
height: auto;
top: 0; left: 0;
}
.img-tools > i {
float: left;
width: 30%;
margin: 5px 1.5%;
cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addNew">
<form>
<input type="file" name="images" id="images" multiple>
<button id="addProduct">Add</button>
</form>
<div class="image-display"></div>
<div class="img-button-holder"></div>
</div>
A blobURI (that you miscalled blob in your code) is just a string.
The File object you create is just that string in a text/plain file.
You don't have to convert from a File to a blobURI to a File.
Just keep the initial Files, store them in a good ol' Array, manage them from there.
Create the blobURI only to display these Files (it's really just a pointer in the memory so your document (here <img>) knows how to access the file on the user disk, and hence can't be shared).
When you need to send the files, simoly take them from the Array you did the management with.
ps: Note that depending on your back-end, you might have to append a [] at the name of your formData key.
function sendToServer() {
var formData = new FormData(),
files = fileHandler.list; // grab them directly from our manager
// it's an Array, so use Array methods
files.forEach(function(file) {
// since you are on php, to be able to append multiple items in the same field,
// you need to append '[]' at the end of your fieldName
formData.append('images[]', file);
});
// send it to your server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'your_php_script');
// xhr.send(formData);
// but from SO we will just show what's inside
if (typeof formData.getAll === 'function') {
console.log(formData.getAll('images[]'));
}
}
// A basic file manager which will expose its selected files in an Array
function FileHandler(options) {
if (!options || typeof options !== 'object')
options = {};
this.options = options;
// this is really the only important part: we use an Array to store all our files
this.list = [];
this.addButton = isValidElement(options.addButton) || $('<button>', {
text: 'Add new Files'
});
// also, we use a single file input
this.input = $('<input>', $.extend(options.input || {}, {
type: 'file',
class: 'fh-input',
multiple: true,
}));
this.items_container = isValidElement(options.items_container) || $('<div>', {
class: 'fh-item-container'
});
this.preview = this.initPreview();
this.addButton.on('click', function() {
this.input.click()
}.bind(this));
this.input.on('change', this.onchange.bind(this));
this.items_container.on('click', '.fh-item .fh-remove', this.remove.bind(this));
this.items_container.on('click', '.fh-item :not(.fh-remove)', this.handleItemClick.bind(this));
this.items_container.on('load', 'img', revokeURL);
// We don't need blobURIs for anything else than loading <img> elements,
// so we can revoke them directly at load
function revokeURL(evt) {
var url = evt.currentTarget.src;
URL.revokeObjectURL(url);
}
function isValidElement(obj) {
var $obj = $(obj);
return $obj[0] && $obj[0] instanceof Element && $obj.eq(0);
}
}
FileHandler.prototype = Object.create({
add: function addFile(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $item = this.generateItem(file);
this.items_container.append($item);
// store it in our Array
this.list.push(file);
this.preview.show(file);
return $item;
},
remove: function removeFile(event) {
var $target = $(event.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file'),
index = this.list.indexOf(file);
$item.remove();
if (index > -1) {
// remove it from our Array
this.list.splice(index, 1);
}
if (this.preview.current === file) {
if (this.list.length) {
var next = index <= (this.list.length - 1) ? index : 0;
this.preview.show(this.list[next]);
} else this.preview.hide();
}
},
generateItem: function generateItem(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $cont = $('<div>', {
class: 'fh-item'
}),
$title = $('<span>', {
text: file.name || 'unknown-file (' + file.type + ')',
class: 'fh-file_name'
}),
$btn = $('<button>', {
class: 'fh-remove',
text: 'x',
title: 'remove',
name: 'remove item'
}),
$thumb = $('<div>', {
class: 'fh-thumb'
})
// a single time blobURI
.append($('<img>', {
src: URL.createObjectURL(file)
}));
$cont.data('fh.file', file);
return $cont.append(
$title,
$btn,
$thumb
);
},
onchange: function oninputchange(evt) {
// retrieve the Files contained in our single input
var fileList = this.input[0].files;
for (var i = 0; i < fileList.length; i++) {
this.add(fileList[i]);
}
},
handleItemClick: function handleItemClick(evt) {
var $target = $(evt.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file');
this.preview.show(file);
},
initPreview: function() {
var $cont = $('<div>', {
class: 'fh-preview'
}),
img = new Image();
return {
container: $cont.append(img),
update: function updatePreview(url) {},
show: function show(file) {
if (!(file instanceof Blob)) {
console.warn('Not a Blob', file);
throw new TypeError('Argument 1 must be Blob or a File');
}
if (this.current !== file) {
this.current = file;
img.src = URL.createObjectURL(file);
}
$cont.show();
},
hide: function hide() {
img.src = '#';
$cont.hide();
}
};
}
});
var fileHandler = new FileHandler({
input: {
accept: 'image/*'
}
});
$('body').append(
fileHandler.addButton,
$('<button>', {
text: 'send to server'
})
.on('click', sendToServer),
fileHandler.items_container,
fileHandler.preview.container,
);
.fh-item {
border: 1px solid;
display: inline-block;
min-width: 130px;
min-height: 130px;
vertical-align: middle;
}
.fh-file_name {
display: inline-block;
width: 100px;
overflow: hidden;
text-overflow: ellipsis;
margin: 2px 4px;
vertical-align: top;
}
.fh-remove {
box-shadow: none;
border: none;
float: right;
cursor: pointer;
}
.fh-remove:hover {
color: #CC0000;
}
.fh-thumb {
text-align: center;
width: 100%;
height: 100px;
}
.fh-thumb>img {
max-width: 100px;
max-height: 100px;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript file download with Joomla

I am coding in Joomla in which I have self synchronized three audio tracks i.e when one of them starts on the web page the other stop and below is the JS code for the same;
<script type="text/javascript">
function _(id) {
return document.getElementById(id);
}
//function Download(url) {
//document.getElementById('my_iframe').src = url;
//};
function audioApp() {
var audio = new Audio();
var audio_folder = "/images/audios/how-to-meditate/relaxation/";
var audio_ext = ".mp3";
var audio_index = 1;
var is_playing = false;
var playingtrack;
var trackbox = _("trackbox");
var tracks = {
"track1": ["Relaxation in the Forest", "relaxation-in-the-forest"],
"track2": ["Relaxation of the Muscles", "relaxation-of-the-muscles"],
"track3": ["Relaxation with the Breath", "relaxation-with-the-breath"]
};
for (var track in tracks) {
var tb = document.createElement("div");
var pb = document.createElement("button");
//var dn = document.createElement("button");
var tn = document.createElement("div");
tb.className = "trackbar";
pb.className = "playbutton";
//dn.className = "download";
tn.className = "trackname";
tn.innerHTML = tracks[track][0];
pb.id = tracks[track][1];
tb.appendChild(pb);
pb.addEventListener("click", switchTrack);
tb.appendChild(tn);
trackbox.appendChild(tb);
audio_index++;
}
audio.addEventListener("ended", function() {
_(playingtrack).style.background = "url(images/icons/play.JPG)";
playingtrack = "";
is_playing = false;
});
function switchTrack(event) {
if (is_playing) {
if (playingtrack != event.target.id) {
is_playing = true;
_(playingtrack).style.background = "url(images/icons/play.JPG)";
event.target.style.background = "url(images/icons/pause.JPG)";
audio.src = audio_folder + event.target.id + audio_ext;
audio.play();
} else {
audio.pause();
is_playing = false;
event.target.style.background = "url(images/icons/play.JPG)";
}
} else {
is_playing = true;
event.target.style.background = "url(images/icons/pause.JPG)";
if (playingtrack != event.target.id) {
audio.src = audio_folder + event.target.id + audio_ext;
}
audio.play();
}
playingtrack = event.target.id;
}
}
window.addEventListener("load", audioApp);
</script>
Below is the Styling;
<style scoped="scoped" type="text/css">
.trackbar {
background: #FFF;
height: 50px;
font-family: "Arial";
}
.trackbar:nth-child(even) {
background: #FFF;
}
.playbutton {
opacity: .8;
display: block;
float: left;
width: 40px;
height: 40px;
margin: 0px 50px 0px 50px;
background: url(images/icons/play.JPG) no-repeat;
border: none;
cursor: pointer;
outline: none;
}
.playbutton:hover {
opacity: 1;
}
.trackname {
float: left;
color: #000;
margin: 12px 400px 0px 14px;
font-size: 20px;
}
And the html code is;
<div id="trackbox"> </div>
Having achieved this I want to place a download icon besides every mp3 which allows me to download the track, I have the link to download the file and it is placed in the media (Content) of Joomla and also I want a icon to be placed which will trigger the download onClick.
Is there a JS script code available with which I can implement the same.
This is what solved the issue;
<input alt="Submit" src="images/icons/download.jpg" type="image" onclick="document.getElementById('anything').click()" />

Calculate the word amount from an <input>?

The following code converts text into equal paragraphs, based on the users input character amount.
Is it possible for the input box to calculate the amount of words for each paragraph instead of being based on the character amount?
JSFiddle
If an updated fiddle could please be provided, would be much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content');
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
custom = parseInt(document.getElementById("custom").value);
chunkSize = (custom>0)?custom:chunkSize;
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" id="custom" placeholder="Custom Characters per box">
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
How about this? It uses jQuery, but as you used the library in your original submission, I hope that won't be an issue:
HTML
<textarea id="input"></textarea>
<br/>
<button id='divide'>Divide</button>
<div id="paras"></div>
CSS
#input {
resize: none;
height: 200px;
width: 100%;
}
JS
$(function() {
$("#divide").click(function() {
var text = $("#input").val();
var wpp = 10 // words per paragraph
var words = text.split(" ");
var paras = [];
for (i = 0; i < words.length; i += wpp) {
paras.push(words.slice(i, i + wpp).join(" "));
}
$.each(paras, function(i, para) {
$("#paras").append("<p>" + para + "</p>");
});
});
})
JSFiddle

How to Change JQuery Value Through <Input> Dynamically?

The following fiddle converts texts into paragraphs and the problem is the JQuery function attribute chunkSize = 100; currently defines the amount of characters for each divided paragraph to contain.
Is it possible for the user to be able to change this dynamically through the use of an <input> and <button> where the user would be able to type their desired characters for each dynamic paragraph and apply it?
Fiddle
If a new fiddle could please be provided, it would be very much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content'),
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" placeholder="Custom Characters per box">
<button>
Go
</button>
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
Give an id for your input.
<input id="custom" placeholder="Custom Characters per box" style="width:200px;">
Add below code into initialDistribute function.
custom = parseInt(document.getElementById("custom").value); //Get value of the input.
chunkSize = (custom>0)?custom:100; //If Custom value is more than `0`, take that as `chunkSize` value else `100`
See Fiddle
You can use input type="number" element, button element; set chunkSize to input type="number" valueAsNumber property at click of button
html
<label>chunkSize:<input class="chunkSize" type="number" /></label>
<button class="chunkSize">
Set chunkSize
</button>
javascript
$("button.chunkSize").click(function(e) {
var _chunkSize = $("input.chunkSize")[0].valueAsNumber;
chunkSize = _chunkSize;
})
jsfiddle https://jsfiddle.net/csz0ggsw/11/

Categories