highlighting each email in input tag - javascript

So, what I am going to do with the input tag is to insert as many as email address inside it.
<input type="text" name="email-tags"/>
To make it more user-friendly, I want to highlight each-email which is typed inside it with blue color, it looks similar like a tag in SO question which also has x button to delete the tag.
Can anybody please help me how to do this with javascript?
Thanks in advance.

This block of code actually does what you need. It's pretty advanced. I hope it suits your needs. document.getElementById("test").value contains the email addresses in an array in this example.
function setInputEmailToExtendedInput()
{
var inputs = document.querySelectorAll("input[data-type='email']");
Array.prototype.slice.call(inputs).forEach(function(element){
var node = new emailInput();
if (element.id)
{
node.container.id = element.id;
}
if (element.className)
{
node.container.className = element.className;
}
element.parentElement.replaceChild(node.container, element);
});
}
function emailInput() {
this.container = document.createElement("div");
this.container.input = document.createElement("input");
this.container.input.type = "text";
this.container.style.overflowY = "auto";
this.container.input.className = "email_input";
this.container.appendChild(this.container.input);
this.container.input.addEventListener("keydown", checkKeyUpOnEmailInputDisable(this), false);
this.evaluateTag = evaluateEmailFunction;
this.deleteTag = deleteEmailFunction;
this.container.input.addEventListener("paste", emailEvaluateOnChange(this), false);
Object.defineProperty(this, "value", {
value: [],
enumerable: false
});
Object.defineProperty(this, "placeholder", {
get: function() {
this.container.input.placeholder;
},
set: function(value) {
this.container.input.placeholder = value;
},
enumerable: false
});
}
function emailEvaluateOnChange(obj, e) {
return function(e) {
obj.evaluateTag(e.target.value);
}
}
function checkKeyUpOnEmailInputDisable(obj, e) {
return function(e) {
if (e.keyCode == 13 || e.keyCode == 32) //either enter or space
{
obj.evaluateTag(e.target.value);
return false;
} else if (e.keyCode == 8) //backspace
{
if (e.target.value.length == 0 && obj.value.length > 0) //length of the input is zero.
{
//delete tag.
obj.deleteTag();
return true;
}
} else if (e.keyCode == 27) //escape
{
//hide the input helper and blur the input.
e.target.blur();
e.preventDefault();
return false;
}
};
}
function deleteEmailFunction(tag) {
if (!tag) {
//delete the last tag
var tag = this.value.length - 1;
}
this.container.removeChild(this.container.querySelectorAll(".email_element")[tag]);
this.value.splice(tag, 1);
if (this.value.length > 0) {
var marginNode = parseInt(getComputedStyle(this.container.children[0]).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
} else {
this.container.input.style.width = "100%";
}
this.container.input.focus();
}
function createEmail(value) {
var node = document.createElement("span");
node.className = "email_element";
node.innerHTML = value;
return node;
}
function evaluateEmailFunction(tagValue) {
if (tagValue.match(/[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/ig)) {
//email is valid add
var node = createEmail(tagValue.trim());
this.container.insertBefore(node, this.container.input);
this.value.push(tagValue);
var marginNode = parseInt(getComputedStyle(node).getPropertyValue("margin-right"));
var width = parseInt(this.container.children[0].offsetLeft) * 2; //default padding
for (var i = 0; i < this.value.length; ++i) {
//calculate the width of all tags.
width += parseInt(this.container.children[i].offsetWidth) + marginNode;
}
//set the width of the tag input accordingly.
this.container.input.style.width = (this.container.offsetWidth - width) - 20 + "px";
this.container.input.value = "";
this.container.input.focus();
}
}
RegExp.escape = function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
window.addEventListener("load", function(){setInputEmailToExtendedInput()}, false);
div.email_builder {
width: 500px;
height: 36px;
background-color: #ffffff;
border: 1px solid #777777;
box-sizing: border-box;
}
input.email_input {
padding: 8px 8px 8px 8px;
border: 0px solid transparent;
width: 100%;
box-sizing: border-box;
font-size: 11pt;
}
span.email_element {
display: inline-block;
padding: 6px 2px 6px 2px;
margin-right: 4px;
color: #0059B3;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
box-sizing: border-box;
}
span.email_element > span.email_remove_button {
color: #000000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
span.email_element > span.email_remove_button:hover {
color: #660000;
font-size: 10pt;
white-space: nowrap;
cursor: pointer;
padding-left: 12px;
font-size: 14px;
font-weight: bold;
}
<input type="text" class="email_builder" id="test" data-type="email" />

how about this:
<from id="form" action="">
<span id="emailInput">
<input type="text" name="email-tags"/>
</span>
<span id="test"></span>
</form>
function isValidEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(function(){
$('input').keydown(function(event){
$input = $(this);
$emailInput = $("#emailInput");
$("#test").html(event.which);
switch(event.which){
//stop for "," ";" and " "
case 188:
case 186:
case 32:
currentEmail = $.trim($input.val());
if(isValidEmail(currentEmail)){
$address = $("<span>");
$address.addClass("emailAddress");
$address.text(currentEmail);
$close=$('<span>');
$close.addClass("close").text("x");
$address.append($close);
$input.val("");
$input.before($address);
}
}
});
$("#emailInput").on("click",".close",function(){
$(this).parent().remove();
});
});
see here:
http://fiddle.jshell.net/wryjde3z/

Related

How to make a reset button appear after certain requirements?

So, i want a reset button to appear on my page when the score of the player reaches 5. But i can't seem to make it appear.
if (Score == 5) {
btnQuestion.disabled = true;
txtQuestionFeedback.innerText = "Correct! \n Congratulations, you've got 5 stars!";
imgScore5.src = "Images/StarOn.gif";
document.getElementById(btnReset).innerHTML = btnReset;
}
Try the following:
1) Insert your button element inside a DIV like this for easier reading
<div id="resetButtonDiv">
<button id="resetButton"></button> <!-- here goes your button config -->
</div>
2) Change the style like this using JS
<script>
function showResetButton() {
document.getElementById("resetButton").style.display = "none";
if (Score == 5) {
// Replace "Score" with your variable or element
document.getElementById("resetButton").style.display = "show";
}
}
showResetButton()
</script>
This was my way to do it:
ScoreBoard = function(sId, sIntoNode = '', fnOnChange = null) {
this.m_sId = sId != '' ? sId : 'scoreboard';
this.m_iScore = 0;
this.m_fnOnChange = fnOnChange;
if(sIntoNode != '') {
let TargetNode = document.getElementById(sIntoNode);
if(TargetNode) {
TargetNode.innerHTML = TargetNode.innerHTML + '<div class="scoreboard-score" id="' + this.m_sId + '">0</div>';
}
}
}
ScoreBoard.prototype.SetScore = function(iNewScore) {
this.m_iScore = iNewScore;
let scoreBoard = document.getElementById(this.m_sId);
if(scoreBoard) {
scoreBoard.innerHTML = this.m_iScore;
}
if(this.m_fnOnChange && typeof this.m_fnOnChange == 'function') {
this.m_fnOnChange(this);
}
}
ScoreBoard.prototype.AddScore = function(iAmount) {
this.SetScore(this.m_iScore + iAmount);
}
ScoreBoard.prototype.Reset = function() {
this.SetScore(0);
}
ScoreBoard.prototype.GetScore = function() {
return this.m_iScore;
}
function OnScoreChange(target) {
let resetBtn = document.getElementById('myScore-reset');
if(resetBtn) {
if(target.GetScore() >= 5) {
resetBtn.style.display = "block";
} else {
resetBtn.style.display = "none";
}
}
}
var myScore = new ScoreBoard('myScore', 'score', OnScoreChange);
var i = 0;
function test() {
myScore.AddScore(1);
i++;
if(i < 20) setTimeout(test, 1000);
}
test();
div#score {
padding: 12px;
background-color: darkgrey;
font-family: Arial;
border-radius: 12px;
box-shadow: 0 0 12px 3px black;
}
div.score-head {
background-color: black;
color: white;
padding: 6px;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
}
div.scoreboard-score {
background-color: #EAEAEA;
padding: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
div#score button {
display: none;
}
<div id="score">
<button onClick="myScore.Reset();" id="myScore-reset">Reset Score</button>
<div class="score-head">Score:</div>
</div>
I've sorted it guys!
Instead, i just used a visibility attribute on the button to hide it on page startup. And then called on that attribute in a Function for HideButton().
```
function ShowResetButton() {
document.getElementById("btnReset").style.visibility = "visible";
}
```
But thank you all for your input! i really appreciate it!
Take it easy,
Happy coding!

How to split a sentence by clicking on de space

I want to split the sentence when i click on the space. He has to make 2 parts of the sentence. I want that i click another time on a space and then to make 3 parts of the sentence.
I've tried to search on google, stackoverflow, etc. But i don't see my answer.
So this is my code.
$(function() {
$(document).data("text", $("#editor").text())
.on("mousedown", function() {
$("#editor")
.html($(this)
.data("text"))
})
.on("mouseup", function() {
that = $("#editor");
var sel = window.getSelection ? window.getSelection() : document.selection();
var o = that.text();
var before = sel.baseOffset;
var after = o.length - before;
var a = o.slice(0, before);
var b = after === 0 ? "" : o.slice(-after);
var n = "<data>||</data>";
var html = (after === "" ? a + n : a + n + b);
that.html(html);
});
})
#editor {
font-family: Sans;
font-size: 28px;
letter-spacing: 8px;
white-space: pre;
}
#editor > data {
color: red;
max-width: .1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor">Hello! I am a Text!</div>
So i hope i've i have the sentence: Hello this is a test. And then click between 'is' and 'a':
Hello this is a test.
$(function() {
jQuery.fn.reverse = [].reverse;
// Add element around all characters
var text = $("#editor").text();
var newText = "";
for (var i = 0; i < text.length; i++) {
newText += `<span>${text[i]}</span>`;
}
$("#editor").html(newText);
// If you click on a space
$("#editor").on("click", "span", function() {
if ($(this).text() == " ") {
var before = $(this).prevAll().reverse();
var after = $(this).nextAll()
$("#editor").html("");
before.each(function() {
if (!$(this).hasClass("white")) {
$("#editor").append(`<span class="yellow">${$(this).text()}</span>`);
} else {
$("#editor").append(`<span class="white">${$(this).text()}</span>`);
}
});
$("#editor").append(`<span class="white"> </span>`);
after.each(function() {
if (!$(this).hasClass("white")) {
$("#editor").append(`<span class="yellow">${$(this).text()}</span>`);
} else {
$("#editor").append(`<span class="white">${$(this).text()}</span>`);
}
});
}
});
})
#editor {
font-family: Sans;
font-size: 28px;
letter-spacing: 8px;
white-space: pre;
}
#editor .br {
color: red;
max-width: .1em;
}
#editor .yellow {
background-color: yellow;
}
#editor .white {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor">Hello! I am a Text</div>
--- Old answer below
This should be a good start. You can do whatever you want with the variables before and after - so that is suits your case.
$(function() {
jQuery.fn.reverse = [].reverse;
// Add element around all characters
var text = $("#editor").text();
var newText = "";
for (var i = 0; i < text.length; i++) {
newText += `<span>${text[i]}</span>`;
}
$("#editor").html(newText);
// If you click on a space
$("#editor").on("click", "span", function() {
if ($(this).text() == " ") {
var before = $(this).prevAll().reverse();
var after = $(this).nextAll()
$("#editor").html("");
before.each(function() {
$("#editor").append(`<span>${$(this).text()}</span>`);
});
$("#editor").append(`<span class="br">|</span>`);
after.each(function() {
$("#editor").append(`<span>${$(this).text()}</span>`);
});
}
});
})
#editor {
font-family: Sans;
font-size: 28px;
letter-spacing: 8px;
white-space: pre;
}
#editor .br {
color: red;
max-width: .1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor">Hello! I am a Text</div>

Get localStorage value on page load

I've searched the internet but I can't seem to find anything that works for me.
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Heating System Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
strLED1 = "";
strLED2 = "";
strText1 = "";
strText2 = "";
var LED1_state = 0;
var LED2_state = 0;
function GetArduinoIO()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null)
{
// XML file received - contains analog values, switch values and LED states
document.getElementById("input1").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
document.getElementById("input2").innerHTML =
this.responseXML.getElementsByTagName('analog')[1].childNodes[0].nodeValue;
// LED 1
if (this.responseXML.getElementsByTagName('LED')[0].childNodes[0].nodeValue === "on") {
document.getElementById("LED1").innerHTML = "ON";
document.getElementById("LED1").style.backgroundColor = "green";
document.getElementById("LED1").style.color = "white";
LED1_state = 1;
}
else {
document.getElementById("LED1").innerHTML = "OFF";
document.getElementById("LED1").style.backgroundColor = "red";
document.getElementById("LED1").style.color = "white";
LED1_state = 0;
}
// LED 2
if (this.responseXML.getElementsByTagName('LED')[1].childNodes[0].nodeValue === "on") {
document.getElementById("LED2").innerHTML = "ON";
document.getElementById("LED2").style.backgroundColor = "green";
document.getElementById("LED2").style.color = "white";
LED2_state = 1;
}
else {
document.getElementById("LED2").innerHTML = "OFF";
document.getElementById("LED2").style.backgroundColor = "red";
document.getElementById("LED2").style.color = "white";
LED2_state = 0;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs" + strLED1 + strLED2 + nocache, true);
request.send(null);
setTimeout('GetArduinoIO()', 1000);
strLED1 = "";
strLED2 = "";
}
function GetButton1()
{
if (LED1_state === 1)
{
LED1_state = 0;
strLED1 = "&LED1=0";
}
else
{
LED1_state = 1;
strLED1 = "&LED1=1";
}
}
function GetButton2()
{
if (LED2_state === 1)
{
LED2_state = 0;
strLED2 = "&LED2=0";
}
else
{
LED2_state = 1;
strLED2 = "&LED2=1";
}
}
function SendText1()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText2 = "&txt2=" + document.getElementById("txt_form1").form_text1.value + "&end2=end";
request.open("GET", "ajax_inputs" + strText2 + nocache, true);
request.send(null);
}
function SendText2()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
strText1 = "&txt1=" + document.getElementById("txt_form2").form_text2.value + "&end1=end";
request.open("GET", "ajax_inputs" + strText1 + nocache, true);
request.send(null);
}
function clsTxt1()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form1").form_text1.value = "";
}, 500)
}
function clsTxt2()
{
setTimeout(
function clearTxt()
{
document.getElementById("txt_form2").form_text2.value = "";
}, 500)
}
function Threshold1()
{
var thr1 = document.getElementById("txt_form1").form_text1.value;
document.getElementById("thresh1").innerHTML = thr1;
}
function Threshold2()
{
var thr2 = document.getElementById("txt_form2").form_text2.value;
document.getElementById("thresh2").innerHTML = thr2;
}
</script>
<style>
.IO_box
{
float: left;
margin: 0 20px 20px 0;
border: 1px solid black;
padding: 0 5px 0 5px;
width: 100px;
height: 196px;
text-align: center;
}
h1
{
font-family: Helvetica;
font-size: 120%;
color: blue;
margin: 5px 0 10px 0;
text-align: center;
}
h2
{
font-family: Helvetica;
font-size: 85%;
color: black;
margin: 10px 0 5px 0;
text-align: center;
}
p, form
{
font-family: Helvetica;
font-size: 80%;
color: #252525;
text-align: center;
}
button
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
input
{
font-family: Helvetica;
font-size: 80%;
max-width: 100px;
width: 90px;
height: 25px;
margin: 0 auto;
text-align: center;
border: none;
}
.small_text
{
font-family: Helvetica;
font-size: 70%;
color: #737373;
text-align: center;
}
textarea
{
resize: none;
max-width: 90px;
margin-bottom: 1px;
text-align: center;
}
</style>
</head>
<body onload="GetArduinoIO(); Threshold1()">
<h1>Heating System Control</h1>
<div class="IO_box">
<h2>Room One</h2>
<p>Temp1 is: <span id="input1">...</span></p>
<button type="button" id="LED1" onclick="GetButton1()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form1" name="frmText">
<textarea name="form_text1" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText1(); clsTxt1(); Threshold1();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh1">...</span></p>
</div>
<div class="IO_box">
<h2>Room Two</h2>
<p>Temp2 is: <span id="input2">...</span></p>
<button type="button" id="LED2" onclick="GetButton2()" color="white" backgroundColor="red" style="border: none;">OFF</button><br /><br />
<form id="txt_form2" name="frmText">
<textarea name="form_text2" rows="1" cols="10"></textarea>
</form>
<input type="submit" value="Set Temp" onclick="SendText2(); clsTxt2(); Threshold2();" style ="background-color:#5F9EA0" />
<p>Threshold: <span id="thresh2">...</span></p>
</div>
</body>
</html>
So my question is, How can I keep the value inserted in the text area even after I reload the page (from the "Threshold1()" function)? I found a few examples with "localStorage" and JQuery, but I have no idea how to call the saved value when I reload the page.
Any help would be appreciated.
Thanks in advance,
Stefan.
Local Storage Explained
The localStorage object likes to store strings, so how would one store large objects, let's say some complex data structure? - Simple, JavaScript has a neat function built in, look up JSON.stringify(object). So all you would need to do is something like below to store some complex object is something like the code I've provided below. Then to retrieve an object from the localStorage you'll want to use JSON.parse(object);.
To look into localStorage, I strongly suggest you take a look at the likes of MDN and if you want to look into the JSON.parse and JSON.stringify functions, you can also find them both here:
JSON.parse() link
JSON.stringify() link
// vanilla js version of $(document).ready(function(){/*code here*/});
window.ready = function(fnc) {
if (typeof fnc != "function") {
return console.error("You need to pass a function as a param.");
}
try { // try time out for some old IE bugs
setTimeout(function () {
document.addEventListener("DOMContentLoaded", fnc());
}, 10)
} catch (e) {
try { // sometimes timeout won't work
document.addEventListener("DOMContentLoaded", fnc());
} catch (ex) {
console.log(ex);
}
}
};
// shorter than $(document).ready();
ready(function() {
var object = {
name: "Jack",
age: 30,
location: "U.S.A.",
get_pay: function() {
console.log("test");
}
},
test;
console.log(object);
var obj_string = JSON.stringify(object);
// run a test
var run_test = function() {
// output the stored object
test = localStorage.getItem("test");
console.log(test);
// to make js turn it into an object again
test = JSON.parse(localStorage.getItem("test"));
console.log(test);
};
// demo of trying to store an actual object
try {
localStorage.setItem("test", object);
run_test();
} catch (e) {
console.log(e);
}
// demo of trying to store the string
try {
localStorage.setItem("test", obj_string);
run_test();
} catch (e) {
console.log(e);
}
});
You can use this JSFiddle : http://jsfiddle.net/xpvt214o/45115/
here we are using Cookie concept and jquery.cookie.js to accomplish what you are trying to do.
to properly check the fiddle you need to press "Run" every time, you can open the same fiddle in 2 tabs write something in the first fiddle then just press run in the 2nd fiddle tab the value should automatically update, here the
$(function(){}); replicates your pageload
My question isn't exactly answered, but I completely avoided storing info on a device. Now I'm just reading the value straight from the arduino and it works. But thanks to everyone that provided some help.

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