How to change style of each character of input text - javascript

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.

Related

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>

Two div with same class name overlapping each other

On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
When i create a new dynamic div it is overlapping with previously created div.
Below is the CSS i've used
.dynamictextbox{
width:50%;
position:relative;
padding:10;
}
.dynamictextbox .mytxt{
position:absolute;
left:0px;
right:50%;
}
.dynamictextbox .mytext{
position:absolute;
left:51%;
right:100%;
}
Below is the HTML code
<div id="Enter your name" class="dynamictextbox">
<label class="mytxt">Enter your name</label>
<input type="text" name="Enter your name_name" id="Enter your name_id" class="mytext">
</div>
<br />
<div id="bigData" class="dynamictextbox">
<label class="mytxt">Now this is a long text which will overlap the next div.Need solution for this. Please give me a solution for this</label>
<input type="text" name="bigData_name" id="bigDate_id" class="mytext">
</div>
<br />
<div id="div_temp" class="dynamictextbox">
<label id="txtlb" class="mytxt">Dynamic Label</label>
<input type="text" name="tb" id="tb" class="mytext">
</div>
<br />
What you need here, is to expand the element according to the content height. Unfortunately you cannot do this using CSS. So we'll have to move along with javascript.
Here goes the script
<script>
var max = 0;
function setHeight() {
var elements = document.getElementsByClassName('mytxt');
var height = 0;
for (var i = 0; i < elements.length; i++) {
height = elements[i].scrollHeight;
if (height > max) {
max = height;
}
}
elements = document.getElementsByClassName('dynamictextbox');
for (var i = 0; i < elements.length; i++) {
elements[i].style = "min-height: " + max + "px";
}
}
</script>
At the end of all the divs call the funtion setHeight().
<script>setHeight()</script>
So the output will look like this
P.S. I've added borders to the class dynamictextbox for testing purposes.
This may be helpful - JSFIDDLE
Just remove the .mytxt class from your CSS and increase the left attribute of .mytext class
.dynamictextbox .mytext{
position:absolute;
left:60%;
right:100%;
}
Update the code below. Is this what you where going after?
$("#add").on("click", function(){
// just a helper function for some random content
function dynamicText(){
var min = 1;
var max = 50;
var random = Math.floor(Math.random() * max) + min;
var text = "";
for(var i = 0; i < random; i++){
text += "text ";
}
return text;
}
// add to the container
var addMe = "\
<div class='dynamictextbox'>\
<label class='mytxt'>"+dynamicText()+"</label>\
<textarea class='mytext'>"+dynamicText()+"</textarea>\
</div>\
";
var container = $("#container");
container.append(addMe);
});
.dynamictextbox{
width:50%;
padding:10;
margin-top: 10px;
background: #CCC;
overflow: auto;
}
.dynamictextbox .mytxt{
position: relative;
float: left;
width: calc(50% - 10px);
}
.dynamictextbox .mytext{
float: right;
width: calc(50% - 10px);
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
<br><hr><br>
<button id="add">ADD</button><br><br>
<div id="container"></div>

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

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/);

Letter Shadows from User Input

Goal: User types name into user input field, selects Animate button, and name is printed vertically with each letter containing a drop shadow of each letter. The Javascript library Raphael may be desirable.
Problem: So far what I have is the name being printed vertically twice side by side. Obviously the second column should be the letters as drop shadows, but I don't know how to change the style of them to look like shadows.
My manager gave me one hint: "I had to create a 2nd text line placed underneath the text...and I used the .blur() method on it. If I have to give you another hint I'll be hinting you to the door."
I'm in some real trouble here. If anyone has suggestions, solutions, anything it would be very much appreciated.
<html>
<head>
<script src="raphael-min.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function animate() {
var txt = document.getElementById("words").value;
var area = txt;
var splittxt = txt.split("");
document.getElementById("letters").innerHTML = "";
document.getElementById("letters2").innerHTML = "";
var i;
for (i = 0; i < splittxt.length; i++) {
document.getElementById("letters").innerHTML = document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
document.getElementById("letters2").innerHTML = document.getElementById("letters2").innerHTML + splittxt[i] + "<br>";
}
//displays how many symbols are in text box and what is in text box
document.getElementById("num").innerHTML= txt.length;
document.getElementById("msg").innerHTML = txt;
r.clear();
// Make our pink rectangle
ellipse = r.ellipse(40, 15, 30, 5).attr({"fill": "#969696", "stroke": "none"});
ellipse.glow({width:10});
}
</script>
<style type="text/css">
#letters
{
background-color:yellow;
width:25px;
float:left;
}
#letters2
{
letter-spacing:0px;
display:block;
-moz-transform: rotate(80deg);
margin-left:90px;
margin-top:80px;
width:25px;
color:#DEDEDE;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input type="button" value="Animate" onclick="animate()" />
<div id='msg'></div>
<div id='num'></div>
<div id='letters'></div>
<div id="letters2"></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px;">
</div>
<div id="elps" style="margin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
</script>
</body>
</html>
Live Long and Prosper.
Do you really need raphael? What I did was simply print out your words onto an element and get the shadow with css's text-shadow. To get the vertical text I added a </br> after each letter.
Take a look at the fiddle: http://jsfiddle.net/joplomacedo/wVGbF/
Here's the code in case you can't see the fiddle:
HTML
Text: <input type="text" id="words" value="" />
<input id="animateBtn" type="button" value="Animate" />
<div class="print"></div>
CSS
.print {
font: 44px/0.8em "Lobster", cursive;
color: gold;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
}​
JS
var join = Array.prototype.join;
$('#animateBtn').on('click', function() {
var txt = $('#words').val(),
spaced_txt = join.call(txt, "</br>");
$('.print').html(spaced_txt);
});​
Here is also the text output function with Raphael:
function draw_text() {
var txt = document.getElementById("words").value;
var posy = txt.length*10;
r.clear();
var attr = {font: "50px Helvetica", opacity: 0.5};
var text = r.text(40, 40+posy, txt).attr(attr).attr({fill: "#0f0"}); // underlayer or "shadow"
text.attr({transform: "r270"}); // rotate 270 degrees
var text2 = r.text(43, 43+posy, txt).attr(attr).attr({fill: "#aa0"}); // text above
text2.attr({transform: "r270"}); // rotate 270 degrees
r.safari();
}
var r = new Raphael("draw-here-raphael");
The full script, based on this example, is here.

Sorting and adding inputs like Google - Get directions

I'm trying to do dynamic sortable list with link "Add Destination" such as Google - Get directions screenshot below. Big problem is that in sorted inputs sequence IDs should be maintained and the contents changed after draging. Input is able to drag before "A" and last, remove by "x" right field. Adding additional waypoints, judging by this: directions-waypoints tutorial should be get as array in JavaScript, waypoints is always middle "A" and last fields, input point "A" always name eg. "from", last "goal". I would like to do latter fields filling by autosuggestion from Google places. I was looking everywhere for some solution but its is too different.
EDIT: I collected everything from different sources end I got in result not quite good code: jsfiddle.net/fasE5/5/
Here is a complete working example: http://jsfiddle.net/fasE5/19/
The HTML I came up with:
<div id="sortable" class="isOnlyTwo">
<div class="destination">
<span class="handle">A</span>
<input type="text" name="dest1" value="" />
×
</div>
<div class="destination">
<span class="handle">B</span>
<input type="text" name="dest2" value="" />
×
</div>
</div>
Add Destination
And the CSS, to make it look a little more pretty:
#add_input
{
text-decoration:none;
color:#15C;
margin-left:35px;
}
#add_input:hover
{
text-decoration:underline;
}
.placeholder
{
border:2px dashed #bfbfbf;
margin:5px;
width:240px;
}
.handle
{
background-color:#06B500;
border:2px solid #3D7311;
cursor:n-resize;
padding:0 3px;
border-radius:99px;
font-size:12px;
}
.destination
{
margin:5px 15px;
}
.destination input
{
border:1px solid #B9B9B9;
width:200px;
}
#sortable.isOnlyTwo .remove_input
{
display:none;
}
.remove_input
{
color:#999;
text-decoration:none;
font-weight:bold;
}
.remove_input:hover
{
color:#666;
}
.destination.ui-sortable-helper
{
opacity:0.8;
filter:alpha(opacity=80);
}
.destination.ui-sortable-helper .remove_input
{
display:none;
}
To keep the right order of the input's name attribute and the order letters (A, B, C...), we call to RecalculateOrder on sort update and when removing an destination.
To prevent from removing the last 2 destinations, we add an isOnlyTwo class to the #sortable div when there is only 2 destinaitons left. Which thanks to our CSS hides the remove_input.
For the autocomplete we need GoogleMaps API
<script src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
Which provides us an new google.maps.places.Autocomplete(input) to add google's autocomplete functionality.
$(function(){
$("#sortable").sortable({
containment: "document",
placeholder: 'placeholder',
handle: ".handle",
axis: "y",
update: RecalculateOrder,
forcePlaceholderSize: true
});
$("#add_input").click(function () {
var inputIndex = $("#sortable > .destination").length;
// Building the new field's HTML
var html = '<div class="destination">';
html += '<span class="handle">' + String.fromCharCode(inputIndex + 65) + '</span> ';
html += '<input type="text" name="dest' + (inputIndex + 1) + '" value="" /> ';
html += '×';
html += '</div>';
var newField = $(html);
newField .find(".remove_input").click(RemoveInput);
$("#sortable").append(newField ).removeClass("isOnlyTwo");
// Adding autocomplete to the new field
BindAutoComplete(newField.find("input")[0]);
return false;
});
$(".remove_input").click(RemoveInput);
// Adding autocomplete to the first two fields
$("#sortable input").each(function(){
BindAutoComplete(this);
});
function RemoveInput()
{
$(this).parent().remove();
RecalculateOrder();
var isOnlyTwo = $("#sortable > .destination").length == 2;
$("#sortable").toggleClass("isOnlyTwo", isOnlyTwo);
return false;
}
// Recalculating from scratch the fields order
function RecalculateOrder()
{
$("#sortable .handle").text(function(i) {
return String.fromCharCode(i + 65);
});
$("#sortable input").attr("name", function(i){
return "dest" + (i + 1);
});
}
function BindAutoComplete(input)
{
var autocomplete = new google.maps.places.Autocomplete(input);
}
});

Categories

Resources