In my code I have two canvases where I can input text. When I write text, it fits into the canvas (the font-size is decreasing) and also I can change the color and font-family.
So when I write into the first input text it appears on the first canvas. But when I try to write on the second input text it doesn't show up on the second canvas (if I press the blue button for changing the color, only then shows up). Here is the JSFiddle code: https://jsfiddle.net/noytmwu7/24/ .I would really appreciate your help!
var canvas4 = document.getElementById("canvas4");
var ctx4 = canvas4.getContext("2d");
var clubNameFontFamily = "Arial Black";
var clubNameFontSize = "20px";
var clubNameFontStyle = "bold";
var clubNameFontColor = "#000000";
$('#clubNameTag').bind('change keyup input', redrawTextsCan4);
$('#clubNameLine1').bind('click', redrawTextsCan4);
function redrawTextsCan4() {
ctx4.clearRect(0, 0, canvas4.width, canvas4.height);
ctx4.textAlign = "center";
ctx4.fillStyle = clubNameFontColor;
clubNameFontSize = fitClubNameOnCanvas(ctx4, $('#clubNameLine1').val().toUpperCase(), clubNameFontFamily);
ctx4.font = clubNameFontStyle + " " + clubNameFontSize + "px " + clubNameFontFamily;
ctx4.fillText($('#clubNameLine1').val().toUpperCase(), canvas4.width * 0.5, 30);
}
function fitClubNameOnCanvas(ctx, text, fontface) {
var size = clubNameMeasureTextBinMethod(ctx, text, fontface, 0, 80, canvas4.width);
if (size > 18) return 18;
return size;
}
function clubNameMeasureTextBinMethod(ctx, text, fontface, min, max, desiredWidth) {
if (max - min < 1) {
return min;
}
var test = min + ((max - min) / 2); //Find half interval
ctx.font = test + "px " + fontface;
measureTest = ctx.measureText(text).width;
if (measureTest > desiredWidth) {
var found = clubNameMeasureTextBinMethod(ctx, text, fontface, min, test, desiredWidth)
} else {
var found = clubNameMeasureTextBinMethod(ctx, text, fontface, test, max, desiredWidth)
}
return found;
}
function clubNameColor(v4) {
v4 = v4.dataset.id;
switch (v4) {
case "littleblue":
clubNameFontColor = "#33ccff";
break;
case "orange":
clubNameFontColor = "#ff9900";
break;
}
redrawTextsCan4();
}
function changeClubNameFontFamily(v5) {
switch (v5) {
case "franklin":
clubNameFontFamily = "Franklin Gothic";
break;
case "impact":
clubNameFontFamily = "Impact";
break;
}
redrawTextsCan4();
}
//the second one
var canvas11 = document.getElementById("canvas11");
var ctx11 = canvas11.getContext("2d");
var selectedTextFont = "Arial Black";
var selectedFontSize1 = "20px";
var selectedFontStyle = "bold";
var selectedFontColor = "#000000";
var selectedFontSize2 = "20px";
$('#nametag2').bind('change keyup input', redrawTextsCan11);
$('#line4').bind('click', redrawTextsCan11);
function redrawTextsCan11() {
ctx11.clearRect(0, 0, canvas11.width, canvas11.height);
ctx11.textAlign = "center";
ctx11.fillStyle = selectedFontColor;
selectedFontSize1 = fitTextOnCanvas(ctx11, $('#line4').val().toUpperCase(), selectedTextFont);
ctx11.font = selectedFontStyle + " " + selectedFontSize1 + "px " + selectedTextFont;
ctx11.fillText($('#line4').val().toUpperCase(), canvas11.width * 0.5, 30);
}
function fitTextOnCanvas(ctx, text, fontface) {
var size = measureTextBinaryMethod(ctx, text, fontface, 0, 80, canvas11.width);
if (size > 18) return 18;
return size;
}
function measureTextBinaryMethod(ctx, text, fontface, min, max, desiredWidth) {
if (max - min < 1) {
return min;
}
var test = min + ((max - min) / 2); //Find half interval
ctx.font = test + "px " + fontface;
measureTest = ctx.measureText(text).width;
if (measureTest > desiredWidth) {
var found = measureTextBinaryMethod(ctx, text, fontface, min, test, desiredWidth)
} else {
var found = measureTextBinaryMethod(ctx, text, fontface, test, max, desiredWidth)
}
return found;
}
function color11(v11) {
v11 = v11.dataset.id;
switch (v11) {
case "littleblue":
selectedFontColor = "#33ccff";
break;
case "orange":
selectedFontColor = "#ff9900";
break;
}
redrawTextsCan11();
}
function chfont5(v5) {
switch (v5) {
case "franklin":
selectedTextFont = "Franklin Gothic";
break;
case "impact":
selectedTextFont = "Impact";
break;
}
redrawTextsCan11();
}
#canvas4 {
border: 2px dotted red;
border-radius: 5px;
}
#canvas11 {
border: 2px dotted red;
border-radius: 5px;
}
.littleblue {
border: 0.1px solid #CCC;
margin: 1px;
zoom: 3;
vertical-align: middle;
display: inline-block;
cursor: pointer;
overflow: hidden;
width: 22.5px;
height: 20px;
background-color: #33ccff;
}
.littleblue:hover,
.littleblue:active,
.littleblue:focus {
border: 1px solid black;
box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
opacity: 0.7;
text-decoration: none;
text-shadow: -1px -1px 0 #136a65;
-webkit-transition: all 250ms linear;
transition: all 250ms linear;
}
.orange {
border: 0.1px solid #CCC;
margin: 1px;
zoom: 3;
vertical-align: middle;
display: inline-block;
cursor: pointer;
overflow: hidden;
width: 22.5px;
height: 20px;
background-color: orange;
}
.orange:hover,
.orange:active,
.orange:focus {
border: 1px solid black;
box-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
opacity: 0.7;
text-decoration: none;
text-shadow: -1px -1px 0 #136a65;
-webkit-transition: all 250ms linear;
transition: all 250ms linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 style="font-size: 15px;padding-top: 10px">Text Colour</h3>
<button type="button" class="littleblue" data-id="littleblue" onclick="clubNameColor(this)"></button>
<button type="button" class="orange" data-id="orange" onclick="clubNameColor(this)"></button>
<h3 style="font-size: 15px;padding-top: 10px">Choose Font</h3>
<select name="Font" onchange="changeClubNameFontFamily(this.value)">
<option value="franklin" style="font-family: Franklin Gothic">FRANKLIN GOTHIC</option>
<option value="impact" style="font-family: Impact">IMPACT</option>
</select>
<h3 style="font-size: 15px;padding-top: 10px">Write text</h3>
<form action="" method="POST" id="clubNameTag" class="nametag">
Line1:
<input type="text" id="clubNameLine1" maxlength="12" name="line1" style="width:220px; height: 30px" />
<br>
<canvas id="canvas4" width=110 height=30 style=" position: absolute; top: 20px; left: 134px; z-index: 10; "></canvas>
<!-- second one -->
<h3 style="font-size: 15px;padding-top: 10px">Text Colour</h3>
<button type="button" class="littleblue" data-id="littleblue" onclick="color11(this)"></button>
<button type="button" class="orange" data-id="orange" onclick="color11(this)"></button>
<h3 style="font-size: 15px;padding-top: 10px">Choose Font</h3>
<select name="Font" onchange="chfont5(this.value)">
<option value="franklin" style="font-family: Franklin Gothic">FRANKLIN GOTHIC</option>
<option value="impact" style="font-family: Impact">IMPACT</option>
</select>
<h3 style="font-size: 15px;padding-top: 10px">Write text</h3>
<form action="" method="POST" id="nametag2" class="nametag">
Line1:
<input type="text" id="line4" maxlength="12" name="line1" style="width:220px; height: 30px" />
<canvas id="canvas11" width=110 height=30 style=" position: absolute; top: 60px; left: 134px; z-index: 10; "></canvas>
In your HTML the closing form tags are missing, so the second form is inside the first. When I added the closing form tags on the jsFiddle things worked as expected.
The reason it was not working was because the eventHandler below to draw "Can4" was also being triggered by changes to the input on the second form (add an alert in the redrawTextsCan4 function before adding the missing form tags and you will see it appears when a character is typed in the lower input field).
$('#clubNameTag').bind('change keyup input', redrawTextsCan4);
So to summarise, the answer is to add the missing closing form tags.
Related
here's what happened. i was trying to develop a clicker game using html and css and js but the setInterval was not working while my console is going blank as if there were no errors.
first, i tried putting the function on top because last time when i put the var like this
setInterval(gg, cps)
let cps=0;
function upgrade2() {
removec(cpctwo*2)
newlv2()
cps-=99000;
}
function gg() {
document.getElementById("coins").innerHTML ++;
}
the console errored last time when i was using that so then i changes the var from the bottom to the top.
this is my current code html:
<div id="coin">
<h2> <code>$</code><code id="coins">0</code>
</h2>
<img src="https://st3.depositphotos.com/3027583/16082/v/950/depositphotos_160820424-stock-illustration-pixel-art-golden-coin-retro.jpg?forcejpeg=true" width="50" height="50" onclick="addc(cpc)">
</div>
<div id="upgrade">
<div id="morecoins"> Coins Lv
<span id="level">1</span>
<br> Cost:<span id="cost">0.5</span><br>
<button class="upgbtn" onclick="upgrade()">Upgrade
</button>
</s>
</div>
<div id="cps"> Income Lv
<span id="level2">1</span>
<br> Cost:<span id="cost2">2</span><br>
<button class="upgbtn" onclick="upgrade2()">Upgrade
</button>
</div>
</div>
<br>
<script src="scripts.js"></script>
<hr>
moreinfo:
<br><br>
New Update:<br>
1. turned "coins:" into "$"
<br>
2. new upgrade income/coins per second gui
<br>3. removed "title" <br>
fixed income upgrade cost and lv
<br><br>
engine version: V1.6
<br><br>
Heping Yang/Gleacc Corp
css:
#coin {
text-align: center;
}
.upgbtn {
padding: 4px 16px;
border: solid black 3px;
background: green;
border-radius: 12px;
}
#morecoins {
padding: 8px 12px;
border: solid black 3px;
background: yellowgreen;
border-radius: 12px;
}
#cps {
padding: 8px 12px;
border: solid black 3px;
background: yellowgreen;
border-radius: 12px;
}
js:
var coins = 0;
var cpc = 1;
var cpctwo = 1;
var lv = 1;
var cps = 100000;
function upgrade2() {
removec(cpctwo*2)
newlv2()
cps-=99000;
}
function gg() {
document.getElementById("coins").innerHTML ++;
}
setInterval(gg, cps);
function addc(x) {
coins += x;
var coinshtml = (document.getElementById("coins").innerHTML = `${coins}`);
}
function removec(x) {
coins -= x;
var coinsnewnew = (document.getElementById("coins").innerHTML = `${coins}`);
}
function newlv() {
lv += 1;
cpc +=24;
document.getElementById("cost").innerHTML = `${cpc/2}`;
document.getElementById("level").innerHTML = `${lv}`;
}
function upgrade() {
removec(cpc/2)
newlv()
}
let lv2 = 1;
function newlv2() {
lv2 += 1;
cpctwo +=8;
cps;
document.getElementById("cost2").innerHTML = `${cpctwo*2}`;
document.getElementById("level2").innerHTML = `${lv2}`;
}
Instead of .innerHTML method, add .textContent method so when you add a new coin the cast doesn't read the html so it won't output NaN. Instead, with .textContent method it will only get the text, for example, '5', and it will cast it without problems.
There's a little program, that dynamically stretches words to any screen height. It is based on innerHTML. How to make it fade in and out, when the word is changing?
let text = document.getElementById("text");
let input = document.getElementById("input");
let svg = document.querySelector("svg");
function changeWord() {
text.innerHTML = input.value;
svg.setAttributeNS(null, "viewBox", `-4 0 16 ${text.getComputedTextLength()}`);
}
* {
padding: 0;
margin: 0;
}
svg {
height: 100vh;
font-family: roboto, sans-serif;
font-size:16px;
border:1px solid;
}
input {
position: fixed;
top: 0;
right: 0;
border: 2px solid red;
}
<svg viewBox="-4 0 16 75">
<g transform="rotate(90 0 0)">
<text id="text">Skibpidi</text>
</g>
</svg>
<input value="Skibidi" oninput="changeWord()" id="input" type="text">
I am wrapping the added characters in a <tspan> element. The tspan is animated in css from fill-opacity:0 to fill-opacity:1 for a fade in effect. Please read the comments in the code.
const SVG_NS = "http://www.w3.org/2000/svg";
let text = document.getElementById("text");
let input = document.getElementById("input");
let svg = document.querySelector("svg");
let L; //the number of letters of the input value
function setWord() {
let vals = input.value.trim().split(""); //trim for the empty spaces at the begining and the end of the string and split into an array
L = vals.length; //the length of the array == the number of letters
text.innerHTML = ""; //clear the content of the text element
// set a variable for the text content
let textcontent = "";
vals.forEach((v) => {
//add each value to the textcontent
textcontent += v;
});
text.textContent = textcontent;
//reset the viewBox value
svg.setAttributeNS(
null,
"viewBox",
`-4 0 16 ${text.getComputedTextLength()}`
);
}
setWord();
function changeWord(e) {
let vals = input.value.trim().split("");
if (vals.length == L + 1) {
// if the user is adding chars to the input
//create a new element tspan to wrap the new character in
let tspan = document.createElementNS(SVG_NS, "tspan");
//set the text content of the tspan element
tspan.textContent = vals[vals.length - 1];
//append the tspan to the text element
text.appendChild(tspan);
// reset the value of the L
L += 1;
} else {
//if the user is deleting letters
setWord();
}
//reset the viewBox value
svg.setAttributeNS(
null,
"viewBox",
`-4 0 16 ${text.getComputedTextLength()}`
);
}
input.addEventListener("input", changeWord);
* {
padding: 0;
margin: 0;
}
svg {
height: 100vh;
font-family: roboto, sans-serif;
font-size:16px;
border:1px solid;
}
input {
position: fixed;
top: 0;
right: 0;
border: 2px solid red;
}
tspan{
fill-opacity:0;
animation: fo 2s forwards;
}
#keyframes fo{
to{fill-opacity:1;}
}
<svg viewBox="-4 0 16 75">
<g transform="rotate(90 0 0)">
<text id="text">Skibpidi</text>
</g>
</svg>
<input value="Skibidi" id="input" type="text">
Is it necessary to use svg? Only you could do something along the lines of this:
let text = document.getElementById("text");
let input = document.getElementById("input");
function changeWord(event) {
let letter = document.createElement('div');
letter.className = 'letter'
// Handle delete key
if (event.key === 'Backspace' && text.childElementCount > 0) {
text.removeChild(text.lastChild);
} else {
// Assign last letter of the input to created div
letter.innerHTML = input.value.slice(input.value.length - 1,
input.value.length);
text.appendChild(letter);
}
}
* {
padding: 0;
margin: 0;
}
#text {
display: flex;
height: 100vh;
font-family: roboto, sans-serif;
font-size: 16px;
border: 1px solid;
}
.letter {
/* Allow spaces */
white-space: break-spaces;
transform: translateY(20px);
animation: slide 1s forwards cubic-bezier(0.4, 0.6, 0.8, 0.9);
}
#keyframes slide {
0% {
transform: translateY(20px);
}
100% {
transform: translateY(0px);
}
}
input {
position: fixed;
top: 0;
right: 0;
border: 2px solid red;
}
<div id="text">
<div class="letter">S</div>
<div class="letter">k</div>
<div class="letter">i</div>
<div class="letter">b</div>
<div class="letter">p</div>
<div class="letter">i</div>
<div class="letter">d</div>
<div class="letter">i</div>
</div>
<input value="Skibidi" onkeyup="changeWord(event)" id="input" type="text">
Bearing in mind you'd have to style it how you want.
I'm looking to create a random name picker with HTML, JS and CSS which has gone quite well as you can see here... http://clients.random.agency/namepicker/
However, the client has asked for it to have a similar animation to this with ...
https://www.dropbox.com/s/3likecb0ld30som/Jv0Gp4XkhQ.mp4?dl=0
I've search google but I can't seem to find any examples of what I'm looking for and would really appreciate if anyone could point me in the right direction.
This is a simple example, hope be helpful.
var names =['John', 'David', 'Joe', 'Sara'];
var nameCount= names.length;
var p = document.getElementById("container");
var randTimer = setInterval(function(){ p.innerHTML = names[Math.floor(Math.random() * nameCount)]; }, 200);
function stop(){
clearInterval(randTimer);
}
#container{
color: red;
font-size:2rem;
text-align:center;
cursor: pointer;
}
<p id="container" onClick="stop()"></p>
<p>click on random names to pick one!</P>
Here's a pretty similar example I was able to find. Using Javascript seems to be the most straightforward way to go about doing this. https://codepen.io/maerianne/pen/pRQbQr
var myScrollTop = function(elem, delay){
elem.animate({ scrollTop: 0 }, delay, function(){
myScrollBottom(elem, delay);
});
};
var myScrollBottom = function(elem, delay){
elem.animate({ scrollTop: elem.height() }, delay, function(){
myScrollTop(elem, delay);
});
};
var scrollUpDown = function(elem, delay) {
myScrollTop(elem, delay);
};
$(document).ready(function(){
scrollUpDown($(".scroll-up-down"), 5000);
});
As you can see, scrollUpDown()is the initial function which starts a loop switching between myScrollTop() and myScrollBottom(). You could pretty easily make the delay increase with each iteration to mimic the slowing down and eventual stop in the example animation you gave.
You could also refactor this to be a singular recursive function.
Best of luck!
It picks a random item from the array of labels. Then it goes into a loop, changing the label to the next item in the array until it gets to the chosen one, and using animation for the transitions
$('#search_btns button:nth-child(2)').hover(function() {
btnTimeID = setTimeout(function() {
// We are using the math object to randomly pick a number between 1 - 11, and then applying the formula (5n-3)5 to this number, which leaves us with a randomly selected number that is applied to the <ul> (i.e. -185) and corresponds to the position of a word (or <li> element, i.e. "I'm Feeling Curious").
var pos = -((Math.floor((Math.random() * 11) + 1)) * 5 - 3) * 5
if (pos === -135) {
console.log("position didn't change, let's force change")
pos = -35;
}
$('#search_btns button:nth-child(2) ul').animate({'bottom':pos + 'px'}, 300);
// Change the width of the button to fit the currently selected word.
if (pos === -35 || pos === -110 || pos === -185 || pos === -10 || pos === -60 || pos === -160) {
console.log(pos + ' = -35, -110, -185, -10, -60, -160');
$('#search_btns button:nth-child(2)').css('width', '149px');
} else if (pos === -85) {
console.log(pos + ' = -85');
$('#search_btns button:nth-child(2)').css('width', '160px');
} else if (pos === -210) {
console.log(pos + ' = -210');
$('#search_btns button:nth-child(2)').css('width', '165px');
} else {
console.log(pos + ' = -260, -235');
$('#search_btns button:nth-child(2)').css('width', '144px');
}
},200);
}, function() {
clearTimeout(btnTimeID);
setTimeout(function() {
console.log('setTimeout function');
$('#search_btns button:nth-child(2) ul').css('bottom', '-135px'); // this is the original position
$('#search_btns button:nth-child(2)').css('width', '144px'); // reset the original width of the button
},200);
});
body, html {
margin: 0;
box-sizing: border-box;
font-family: arial;
}
*, *:before, *:after {
box-sizing: inherit;
}
#search_btns {
width: 400px;
margin: 30px auto;
padding-left: 60px;
}
#search_btns button:nth-child(2) {
width: 144px;
}
#search_btns button:nth-child(1) {
bottom: 12px;
}
#search_btns button {
position: relative;
height: 34px;
margin: 3px;
font-weight: bold;
color: gray;
background: #f1f1f1;
border: 1px solid #f1f1f1;
border-radius: 2px;
padding: 0 15px;
overflow: hidden;
}
#search_btns button:hover {
color: black;
border: 1px solid #bdbdbd;
box-shadow: 0px 0.5px 0px 0px #d3d3d3;
}
#search_btns button:active {
border: 1px solid #7f7fff;
}
#search_btns button:focus {
outline: 0;
}
#search_btns button ul li {
list-style-type: none;
padding: 5px 0;
text-align: left;
}
#search_btns button ul {
padding-left: 0;
position: absolute;
bottom: -135px;
width: 144px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="search_btns">
<button>This might be the effect you looking for</button>
<button>
<ul>
<li>item0/li>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
<li>item9</li>
</ul>
</button>
</div>
</body>
</html>
I'm trying to add font size increment+decrement functionality to my website and yeah, I did it.
Now the fact is when user click on increase button, the font size increasing continuously and the same thing happens to decrease button.
But I don't want this. I want when someone click on increase button, the font size will increase only once... and same for the decrease button.
JSFiddle link here
And heere is the code I'm working with.
This is the markup
<div id="settings">
<button class="resetFont clean-gray">Reset Font Size</button>
<button class="increaseFont clean-gray">Increase Font Size</button>
<button class="decreaseFont clean-gray">Decrease Font Size</button>
</div>
<br>
<br>
<div>
<h2>
This is a test heading
</h2>
<p>
This is a test paragraph
</p>
</div>
And this is the script
var defaultFontSize = $('html').css('font-size');
$(".resetFont").click(function () {
$('html').css('font-size', defaultFontSize);
});
$(".increaseFont").click(function () {
var fontSize = getFontSize();
var newFontSize = fontSize + 1;
setFontSize(newFontSize);
return false;
});
$(".decreaseFont").click(function () {
var fontSize = getFontSize();
var newFontSize = fontSize - 1;
setFontSize(newFontSize);
return false;
});
function getFontSize() {
var currentSize = $("html").css("font-size");
var currentSizeNumber = parseFloat(currentSize, 12);
if (currentSizeNumber > 24) {
currentSizeNumber = 24;
}
if (currentSizeNumber < 10) {
currentSizeNumber = 10;
}
return currentSizeNumber;
}
function setFontSize(size) {
$("html").css("font-size", size);
$(".actualSize").html(size);
}
You can update the increase/decrease button code like below
$(".increaseFont").click(function () {
var newFontSize = parseFloat(defaultFontSize) + 1;
setFontSize(newFontSize);
return false;
});
$(".decreaseFont").click(function () {
var newFontSize = parseFloat(defaultFontSize) - 1;
setFontSize(newFontSize);
return false;
});
js fiddle link
Hope it will help you.
Cache the minimum and maximum size you want to the text to go:
const minSize = parseFloat(defaultFontSize, 12) - 1;
const maxSize = parseFloat(defaultFontSize, 12) + 1;
And then check to see if the new decreased/increased size stays within those bounds:
// in the increasefont click handler
if (newFontSize <= maxSize) setFontSize(newFontSize);
// in the decreasefont click handler
if (newFontSize >= minSize) setFontSize(newFontSize);
Demo
You can disable the buttons when max or min font size is reached. Just ensure to reset them when the font size is reset.
const defaultFontSize = 12;
let actualFontSize = defaultFontSize;
setFontSize(defaultFontSize);
$(".resetFont").click(function() {
setFontSize(defaultFontSize);
$(".decreaseFont").removeAttr('disabled');
$(".increaseFont").removeAttr('disabled');
});
$(".increaseFont").click(function() {
actualFontSize += 1;
setFontSize(actualFontSize);
if (actualFontSize > defaultFontSize) {
$(this).attr('disabled','disabled');
$(".decreaseFont").removeAttr('disabled');
}
return false;
});
$(".decreaseFont").click(function() {
actualFontSize -= 1;
setFontSize(actualFontSize);
if (actualFontSize < defaultFontSize) {
$(this).attr('disabled','disabled');
$(".increaseFont").removeAttr('disabled');
}
return false;
});
function setFontSize(size) {
$("html").css("font-size", size + "px");
$(".actualSize").html(size);
}
body {
width: 80%;
margin: 0 auto;
}
#settings {
padding-right: 1.250em;
padding-top: 0.750em;
}
button.clean-gray {
background-color: #eeeeee;
border: #ccc solid 1px;
border-bottom: 1px solid #bbb;
border-radius: 3px;
color: #333;
font-family: 'Segoe UI', arial, helvetica, sans-serif;
font-weight: bold;
font-size: 0.875em;
text-align: center;
text-shadow: 0 1px 0 #eee;
}
button.clean-gray:hover {
background-color: #dddddd;
border: #bbb solid 1px;
border-bottom: 1px solid #999;
cursor: pointer;
text-shadow: 0 1px 0 #ddd;
}
button.clean-gray:active {
border: #aaa solid 1px;
border-bottom: 1px solid #888;
box-shadow: 0 0 5px 2px #aaaaaa inset, 0 1px 0 0 #eeeeee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="settings">
<button class="resetFont clean-gray">Reset Font Size</button>
<button class="increaseFont clean-gray">Increase Font Size</button>
<button class="decreaseFont clean-gray">Decrease Font Size</button>
</div>
<br>
<br>
<div>
<h2>
This is a test heading
</h2>
<p>
This is a test paragraph
</p>
</div>
I have text-field and button. When the button is clicked, it should generate the text-field with emoji picker enabled. I can see the button but the emoji picker is not getting enabled.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/jquery.emojiFace.js"></script>
</head>
<body>
<form class="col-sm-12">
<div id="textfields">
<div id="entireText0">
<div class="form-row">
<div class="col-sm-10">
<div class="form-group">
<label for="textarea0">Question 1</label>
<!--<textarea class="form-control" id="textarea0" rows="2"></textarea>-->
<div class="containers">
<textarea rows="3" id="textarea0" class="form-control faceText" spellcheck="false"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<br><br>
<button type="button" id="button0" class="btn btn-primary" onclick="addTextFields();">Add Questions</button>
</form>
<script>
$(function() {
$('.faceText').emojiInit({
fontSize: 20,
success: function(data) {},
error: function(data, msg) {}
});
});
textareaid = 0;
addButtonid = 0;
function addTextFields() {
textareaid++;
addButtonid++;
var objTo = document.getElementById('textfields');
var divtest = document.createElement("div");
divtest.innerHTML = "<div id='textfields'><div id='entireText" + addButtonid + "'> <div class='form-row'> <div class='col-sm-10'> <div class='form-group'> <label for='textarea" + addButtonid + "'>Question " + (addButtonid + 1) + "</label> <div class='containers'><textarea rows='3' id='textarea" + addButtonid + "' class='form-control faceText' spellcheck='false'></textarea></div></div></div></div></div></div>";
objTo.appendChild(divtest);
$('.faceText').emojiInit();
}
</script>
</body>
</html>
EmojiPicker code(jquery.emojiFace.js):
var option;
(function(c) {
var d = "ƒ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ υ φ χ ψ ω ϑ ϒ ϖ • … ′ ″ ‾ ⁄ ℘ ℑ ℜ ™ ℵ ← → ↓ ↔ ↵ ⇐ ⇑ ⇒ ⇓ ⇔ ∀ ∂ ∃ ∅ ∇ ∈ ∉ ∋ ∏ ∑ − ∗ √ ∝ ∞ ∠ ∧ ∨ ∩ ∪ ∫ ∴ ∼ ≅ ≈ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊄ ⊆ ⊇ ⊕ ⊗ ⊥ ⋅ ⌈ ⌉ ⌊ ⌋ 〈 〉 ◊ ♠ ♣ ♥ ♦".split(" ");
c.fn.emojiInit = function(b) {
option = c.extend({
targetId: "",
fontSize: 14,
faceList: d,
success: function(a) {},
error: function(a, b) {}
}, b);
option.targetId = c(this).attr("id");
b = c(this);
if (void 0 == b || 0 >= b.length) option.error(null, "target object is undefined");
else {
option.fontSize = 20 < option.fontSize ? 20 : option.fontSize;
option.fontSize = 14 > option.fontSize ? 14 : option.fontSize;
var a = "";
option.faceList.forEach(function(b) {
a += "<div onclick='insertAtCaret(\"" + option.targetId + '","' + b + "\",this)' style='font: normal normal normal 14px/1 FontAwesome;cursor: pointer;padding:3px;font-size:" + option.fontSize + "px;width: 20px;display: inline-block;text-align:center;'>" + b + "</div>";
});
b.css("width", "100%");
b.css("padding", "5px 30px 5px 5px");
b.css("box-sizing", "border-box");
b.css("resize", "vertical");
b.parent().css("position", "relative");
b.after("<div id='faceEnter' onclick='showFaceBlock()' style='padding: 5px;position: absolute;right: 0;top: 0;cursor: pointer;font: normal normal normal 14px/1 FontAwesome;'>+</div>");
b.after("<div id='faceBlock' style='background:rgb(216, 216, 216);border-radius: 12px;display: none;position: absolute;border: 1px solid #e2e2e2;padding: 5px;right: -150px;top: 25px;width: 300px;'>" + a + "</div>");
c(document).click(function() {
c("#faceBlock").hide();
});
c("#faceBlock").click(function(a) {
a.stopPropagation();
});
c("#faceEnter").click(function(a) {
a.stopPropagation();
})
}
}
})(jQuery);
function showFaceBlock() {
$("#faceBlock").show();
}
function insertAtCaret(c, d, b) {
try {
$("#faceBlock").hide();
var a = $("#" + c).get(0);
if (document.all && a.createTextRange && a.caretPos) {
var e = a.caretPos;
e.text = "" == e.text.charAt(e.text.length - 1) ? d + "" : d;
} else if (a.setSelectionRange) {
var f = a.selectionStart,
h = a.selectionEnd,
k = a.value.substring(0, f),
l = a.value.substring(h);
a.value = k + d + l;
a.focus();
var g = d.length;
a.setSelectionRange(f + g, f + g);
a.blur();
} else a.value += d;
option.success(b);
} catch (m) {
option.error(b, m);
}
};
I am using this emoji picker:
https://www.jqueryscript.net/text/Unicode-Emoji-Picker-jQuery-emojiFace.html
I can enable the emojipicker for first text-area. But, cannot do it when the text-area is dynamically generated. For instance, "Question 2" text-area is dynamically generated one.
Now, I can see something like this.
You have to loop through each html element with class faceText. Try this;
$('.faceText').each(function(i,v){
$(this).emojiInit({
fontSize: 20,
success: function(data) {},
error: function(data, msg) {}
});
});
Moved some scripts here and there, I didn't notice that addTextFields is being called when a button is clicked;
<script>
textareaid = 0;
addButtonid = 0;
function addTextFields() {
textareaid++;
addButtonid++;
var objTo = document.getElementById('textfields');
var divtest = document.createElement("div");
divtest.innerHTML = "<div id='textfields'><div id='entireText" + addButtonid + "'> <div class='form-row'> <div class='col-sm-10'> <div class='form-group'> <label for='textarea" + addButtonid + "'>Question " + (addButtonid + 1) + "</label> <div class='containers'><textarea rows='3' id='textarea" + addButtonid + "' class='form-control faceText' spellcheck='false'></textarea></div></div></div></div></div></div>";
objTo.appendChild(divtest);
$('.faceText').each(function(i,v){
if($(this).hasClass('done')){
$(this).emojiInit({
fontSize: 20,
success: function(data) {},
error: function(data, msg) {}
});
$(this).addClass('done');
}
});
}
</script>
Here is your own jquery based emoji picker
<div id="con">
<!-- Component -->
<div class="emojiPicker">
<div class="emojis">
<div class="emojiFrame"><span class="emoji">😜</span></div>
<div class="emojiFrame"><span class="emoji">😁</span></div>
</div>
</div>
<!-- Sample text input -->
<div id="text">
<textarea id="target"></textarea>
</div>
</div>
Script
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".emojiFrame").click(function(){
// target, where emoji will be placed
var target = $("#target");
//emoji will be placed always at end of textbox
target.text(target.text() + $(this).text());
})
})
</script>
Style
<style>
/* page */
body{
box-sizing: border-box;
min-height: 100vh;
margin: 0;
background-color: rgb(202, 193, 193);
}
#con{
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
textarea {
resize: none;
margin-top: 10px;
box-sizing: content-box;
width: calc(100% - 6px);
border: 1px solid black;
}
/* component */
.emojiPicker{
/* 5 emojis in row */
/* width: 212px; */
/* 6 emojis in row */
/* width: 254px; */
/* 7 emojis in row */
width: 296px;
border: 1px solid #0d8cfc;
background-color: aliceblue;
-webkit-box-shadow: 1px 1px 5px -1px rgba(0,0,0,0.75);
-moz-box-shadow: 1px 1px 5px -1px rgba(0,0,0,0.75);
box-shadow: 1px 1px 5px -1px rgba(0,0,0,0.75);
}.emojis{
width: 100%;
display: flex;
flex-wrap: wrap;
}.emojiFrame{
box-sizing: content-box;
user-select: none;
text-align: center;
cursor: pointer;
width: 30px;
font-size: 21px;
padding: 3px;
margin: 3px;
background-color: transparent;
transform: scale(0.9);
transition: background-color 0.2s, transform 0.1s;
}.emojiFrame:hover{
background-color: #0d8cfc;
}.emojiFrame:active{
background-color: #4babff;
transform: scale(0.95);
}
</style>