How to format a text in a div with jQuery/Css - javascript

I would like to display a text copied from a site, for example Wikipedia, in a div. This text has to be strictly without the tags that the computer copies with the text from wikipedia.
I think that the solution is to set a sort of formatting of the text but I don't know.
This is how it should be (Press OK). But I don't want to paste the text in the code, I have to paste the text in the textarea.
In fact if you try to paste something from Wikipedia in the textarea of this Jsfiddle you will see that the result is horrible and with all the html tags.
HTML:
<div id="faketxt" contenteditable></div>
<button id='btn'>OK</button>
<button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
</button>
<button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
</button> <br>
<div id='boxes'>
</div>
CSS:
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
display:inline-block;
float: left;
}
#boxes{
display : flex;
display:inline-block;
}
jQuery:
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 130;
var words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
var bold = false;
words.forEach(function(word) {
if (++count > wordLimit) {
count = 1;
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
if (word.indexOf('<b>') != -1) {
bold = true;
}
if (bold) {
$(div).html($(div).html() + '<b>' +
word + '</b>');
} else {
$(div).html($(div).html() +
word);
}
if (word.indexOf('</b>') != -1) {
bold = false;
}
});
}
});
function createDiv() {
div = document.createElement('div');
div.className = 'fakes';
document.getElementById('boxes').append(div);
return div;
}

innerHTML or jquery's $.html() will pull the content (including HTML) of an element. But textContent or jquery's $.text() will just get the text.
Instead of var words = primo.innerHTML have you tried using var words = primo.textContent or var words = $(primo).text()?

try using
words = primo.textContent.replace(/(<^>]+)>)/ig,"").split(/\s/);
instead of
words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);

Rather than getting the innerHTML of the source, simply get the text content using either the javascript or JQuery text() functions.
So, given you are using jQuery, change your words variable to initialise as follows.
var words = $(primo).text().split(/\s/);

Related

Toggle button : Hide counter numbers with background Color

Onclick button, I want to hide the numbers of this counter with background-color i.e.yellow). For example I want the yellow color in front of numbers, something like z-index 1.
If I click again I want to remove yellow color and show me the numbers of the counter again, something like z-index -1. Is it possible?
I have tried this.. Thanks
var countStep = 0;
function counter() {
document.getElementById("btnToggle").innerHTML = ++countStep;
}
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.style.backgroundColor = color;
property.className = 'toggled'
} else {
property.style.backgroundColor = "rgb(244,113,33)";
property.className = '';
}
}
#btnToggle {
background: #222;
color: lime;
}
<p id="btnToggle">OFF</p>
<button onClick="countNumbers = setInterval(counter, 1000)">Play</button>
<button onClick="clearInterval(countNumbers)">Stop</button>
<input type="button" id="btnToggle" value="Toggle" onclick="btnColor('btnToggle','rgb(255,242,0)');" />
This is to use rule z-index: -1 for the counter text relative to the tag p. It is necessary to wrap the counter in an additional span tag:
<p id="btnToggle"><span>OFF</span></p>
Using the querySelector():
var countContent = document.querySelector("#btnToggle span");
Further, in the very logic of js, inside the if { ... } condition, it is necessary to assign a negative value z-index:
countContent.style.zIndex = '-1';
Else, disable (default):
countContent.style.zIndex = '';
And most importantly, the span tag must be set absolute and #btnToggle relative. Add this to your css:
#btnToggle span {
position: absolute;
}
Also, your tag p and tag input have the same id. And this is incorrect, since the id is a unique attribute.
var countStep = 0;
var countContent = document.querySelector("#btnToggle span");
function counter() {
countContent.innerHTML = ++countStep;
}
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.className !== "toggled") {
property.style.backgroundColor = color;
property.className = "toggled";
countContent.style.zIndex = '-1';
} else {
property.style.backgroundColor = "rgb(244,113,33)";
property.className = "";
countContent.style.zIndex = '';
}
}
#btnToggle {
background: #222;
color: lime;
position: relative;
height: 18px;
}
#btnToggle span {
position: absolute;
}
<p id="btnToggle"><span>OFF</span></p>
<button onClick="countNumbers = setInterval(counter, 1000)">Play</button>
<button onClick="clearInterval(countNumbers)">Stop</button>
<input type="button" id="btnToggle_two" value="Toggle" onclick="btnColor('btnToggle','rgb(255,242,0)');" />
First you will need to change the id of the p tag or inputs selector so they are unique. Then use the psuedo element for the p tag selector in CSS. Style its position to absolute and set left, top, width and height and display: var(--display) => the variable set from the root element. Then you can set the :root style with a css variable that affects the display of your p tags style --display: none to start.
Check the computed style window.getComputedStyle(document.querySelector('#btnToggle'), ':before').getPropertyValue, ':before').getPropertyValue('display') === 'none' in a conditional to see if it is set to display:none, if it is, then set the document.documentElement.style.setProperty('--display', 'block') to display block else => document.documentElement.style.setProperty('--display', 'none')
let countStep = 0,
btn = document.getElementById('btn'),
btnToggle = document.getElementById('btnToggle')
function counter() {
document.getElementById("btnToggle").innerHTML = ++countStep;
}
btn.addEventListener('click', function() {
window.getComputedStyle(document.querySelector('#btnToggle'), ':before').getPropertyValue('display') === 'none' ? document.documentElement.style.setProperty('--display', 'block') :
document.documentElement.style.setProperty('--display', 'none')
})
:root {
--display: none;
}
#btnToggle {
background: #222;
color: lime;
}
#btnToggle:before {
position: absolute;
background: yellow;
content: '';
width: 98vw;
height: 1.2em;
display: var(--display);
}
<p id="btnToggle">OFF</p>
<button onClick="countNumbers = setInterval(counter, 1000)">Play</button>
<button onClick="clearInterval(countNumbers)">Stop</button>
<input type="button" id="btn" value="Toggle" />

How can I dynamically create span in javascript by class name (that already exist and styled in html, that called span class= "bullet")

Here is where I try to create span, inside my tables td
const oneTd = document.createElement('td');
if(result == 1){
var span = document.createElement('bullet');
oneTd.appendChild(span);
}
And here is my span class in html
<span class="bullet">
<div class="bra"></div>
<div class="crr"></div>
</span>
When I use querySelector, it works but only once, but I need to append it each time result ==1
const oneTd = document.createElement('td');
if(result == 1){
const bul = document.querySelector(".bullet");
oneTd.appendChild(bul);
}
Something like this
const oneTd = document.createElement('td');
function addEl() {
if(result === 1){
const span = document.createElement('span');
span.classList.add('bullet');
oneTd.appendChild(span);
}
}
and as a result you will have
<td><span class="span"></span></td>
Here is a simple example to add a span element with predefined styles to the body element using .innerHTML property each time the user presses the button
function addSpan() {
document.body.innerHTML += '<span class="bullet"></span> ';
}
button {
margin-bottom: 10px;
}
.bullet {
padding: 20px;
border-radius: 50%;
display: inline-block;
background-color: green;
}
<button onclick="addSpan()">Add Span</button><br>

Find html character throughout all of website and reduce size

Find html character and reduce size, not sure what the function is to do this?
jQuery("body").children().each(function () {
jQuery(this).html( jQuery(this).html().match("•").attr('style', "font-size:'9px'"));
});
As commented,
You will have to set style to element and not string.
To do this, you will have to fetch the string and then wrap matched string in an element with necessary style.
In your code jQuery(this).html().match("•").attr('style', "font-size:'9px'"), .match will return an array of matched values. They are still string and not HTML Element.
Sample
document.getElementById("btn").addEventListener("click", handleClick);
function handleClick(){
var input = document.getElementById("input").value;
if(!input) return;
var p = document.querySelector("p");
var parsed = p.innerHTML.replace(new RegExp(input, "gi"), function(t){
return "<span class='highlight'>" + t + "</span>"
});
p.innerHTML = parsed;
}
.highlight{
font-size: 12px;
border-bottom: 1px dashed gray;
}
span{
font-size: 16px;
}
<p> This is a sample Text</p>
<input type="text" id="input" />
<button id="btn">Update Style</button>

How to change style of each character of input text

Here I want to randomly change the CSS of each character of text.
Like if I input Stack I will get S in red, t in blue, a in green... etc on the bottom of the input field.
var myModel = {
name: "Mayur",
};
var myViewModel = new Vue({
el: '#my_view',
data: myModel
});
span{
color:green;
font-weight:600;
font-size:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="my_view">
<label for="name">Enter name:</label>
<input type="text" v-model="name" id="name" name="name" />
<p>Welcome, <span>{{ name | uppercase }}</span></p>
</div>
I haven't worked with Vue and I'm not familiar with its internal events and processes, but here's a tiny prototype i made in plain JavaScript:
document.querySelector('button').onclick = function (){
let span = document.querySelector('span.letters'),
text = span.textContent;
span.innerHTML = '';
Array.from(text).map(function(l){
let color = document.createElement('span');
color.innerHTML = l;
color.style.color = 'rgb(' +
randInterval(0, 255) + ',' +
randInterval(0, 255) + ',' +
randInterval(0, 255) + ')';
span.appendChild(color);
});
}
function randInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
<div><span class="letters">STACK</span></div>
<button>Random colors</button>
I've purposefully placed the function that randomizes each value of rgb() in a function, so you can alter it easily (now the colors are trully random). If you want to make the darker, you need to lower the max values. If you want the colors lighter, you need to increase the mins.
Html:
<div>Type something here, then click on the white space beneave.</div>
<input type="hidden" id="hidden">
Javascript:
$("div").prop("contentEditable", true).blur(function(){
var chars = $(this).text().split("");
$("#hidden").val($(this).text());
this.innerHTML = "";
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16)
}).appendTo("div");
});
});
Css:
div{
border: 1px solid black;
width: 400px;
height: 20px;
padding: 2px 3px;
overflow: hidden;
}
You can visit http://jsfiddle.net/DerekL/Y8ySy/ for the implementation!
Both html and css codes are given in the link.
It gives the colour to the characters randomly but it can be manipulated easily or if you want them to run randomly, you can use it directly.

Tie children of one div to children of another div with jquery

I have two parent divs: .inputs and .infoBoxes. Each of them have an equal number of children. When the user clicks into the first .input in .inputs, the first .infoBox in .infoBoxes should slideDown(). Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}
This isn't working but I have tried replacing i with the indexes of each div.
$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...
This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.
First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
(function(ix) {
$($inputs[ix]).find('.input').focus(function() {
$($infoBoxes[ix]).slideDown();
})
$($inputs[ix]).find('.input').blur(function() {
$($infoBoxes[ix]).slideUp();
})
})(i);
}
slideDown is used for showing elements. I am guessing you want to hide elements, since you are clicking on them and you cant click an hidden element. Use hide or slideUp to hide elements.
$(".input, .infobox").on("click", function() {
var ind = $(this).index();
$(".infobox:eq(" + ind + "), .input:eq(" + ind + ")").hide(500);
});
.input,
.infobox {
widht: 100%;
height: 50px;
text-align: center;
margin: 5px 0;
color: white;
}
.input {
background: red;
}
.infobox {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<div class="input">1</div>
<div class="input">2</div>
<div class="input">3</div>
<div class="input">4</div>
<div class="input">5</div>
</div>
<div class="infoboxes">
<div class="infobox">1</div>
<div class="infobox">2</div>
<div class="infobox">3</div>
<div class="infobox">4</div>
<div class="infobox">5</div>
</div>

Categories

Resources