replacing signs with colored spans - javascript

I want to colorize my text and I'm using these signs to do it
() and || and ++
if a text is between | signs then it will be blue and etc...
Here is the code in action:
const text = "|Working on the| ideas |above|, and if you're working " +
"with a form, you can define a hidden input and assign it a " +
"value |of the last| focused input Working on the ideas above, " +
"and if you're working with a form, you can define a hidden |input " +
"and assign| it a value of the last focused input Working " +
"on the ideas above, and if you're working with a |form,| " +
"you can define a hidden input and assign it |a| value of the " +
"last |focused input|";
const contentArea = document.getElementById('contentArea')
let render = '';
render += getColored(text);
contentArea.innerHTML = render;
function getColored(text) {
let result = text;
result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
result = result.replace(/\(([^|]+)\)/g, '<span class="red-string">$1</span>');
result = result.replace(/\+([^|]+)\+/g, '<span class="orange-string">$1</span>');
return result;
}
.blank {
display: inline-block;
border-bottom: 4px dotted red;
width: 150px;
}
.blue-string {
font-family: "Vazir";
color: #7e7cff;
display: inline-block;
text-shadow: 0px 0px 1px #010076;
}
.red-string {
font-family: "Vazir";
color: #ff005e;
display: inline-block;
text-shadow: 0px 0.5px 1px #e40053;
}
.orange-string {
font-family: "Vazir";
color: #ffb000;
display: inline-block;
text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>
As you see everything works fine with | sign highlights But for () and ++ signs if I have more than one occurrence of using them distortions occur have a look at this:
const text = "|Working on the| ideas |above|, and if you're working " +
"with a form, you can define a hidden input and assign it a " +
"value |of the last| focused input Working on the ideas above, " +
"and if you're working with a form, you can define a hidden |input " +
"and assign| it a value of the last focused input Working " +
"on the ideas above, and if you're working with a |form,| " +
"you can define a hidden input and assign it |a| value of the " +
"last |focused input|";
const contentArea = document.getElementById('contentArea')
let render = '';
render += getColored(text);
contentArea.innerHTML = render;
function getColored(text) {
let result = text;
result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
result = result.replace(/\(([^|]+)\)/g, '<span class="red-string">$1</span>');
result = result.replace(/\+([^|]+)\+/g, '<span class="orange-string">$1</span>');
return result;
}
.blank {
display: inline-block;
border-bottom: 4px dotted red;
width: 150px;
}
.blue-string {
font-family: "Vazir";
color: #7e7cff;
display: inline-block;
text-shadow: 0px 0px 1px #010076;
}
.red-string {
font-family: "Vazir";
color: #ff005e;
display: inline-block;
text-shadow: 0px 0.5px 1px #e40053;
}
.orange-string {
font-family: "Vazir";
color: #ffb000;
display: inline-block;
text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>
Note that I used two occurrences of using () signs...
As I did both this in a same approach for | and () and ++, why I get this unexpected behavior and how to fix this?
NOTE: for + sign the same distortion occurs.

Typo in your regex. For |...| delimiters, you set \|([^|]+)\| (all non-pipe between pipes), which is correct.
For +...+ delimiters, you set \+([^|]+)\+ (all non-pipe between pluses), which is incorrect. Should be \+([^+]+)\+.
For (...) delimiters, you set \(([^|]+)\) (all non-pipe between parenthesis), which is incorrect. Should be \(([^)]+)\).
const text = "(Working on the ideas above), and |if| you're +working+ with a form, you can define a hidden input and assign it a value of the last focused input Working on the ideas above, and if you're working with a form, you can define a hidden input and assign it a value of the last (focused) input Working on the ideas above, and if you're working with a form, you can define a hidden input and assign it a value of the last focused input";
const contentArea = document.getElementById('contentArea')
let render = '';
render += getColored(text);
contentArea.innerHTML = render;
function getColored(text) {
let result = text;
result = result.replace(/\|([^|]+)\|/g, '<span class="blue-string">$1</span>');
result = result.replace(/\(([^)]+)\)/g, '<span class="red-string">$1</span>');
result = result.replace(/\+([^+]+)\+/g, '<span class="orange-string">$1</span>');
return result;
}
.blank {
display: inline-block;
border-bottom: 4px dotted red;
width: 150px;
}
.blue-string {
font-family: "Vazir";
color: #7e7cff;
display: inline-block;
text-shadow: 0px 0px 1px #010076;
}
.red-string {
font-family: "Vazir";
color: #ff005e;
display: inline-block;
text-shadow: 0px 0.5px 1px #e40053;
}
.orange-string {
font-family: "Vazir";
color: #ffb000;
display: inline-block;
text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>

You can use a lazy quantifier ? to match as little characters as needed. So the regex can match the next symbol pair
const text = "(Working on the ideas above), and if you're |working| with a form, you can define a hidden input and assign it a value of the last focused input Working on the ideas +above+, and if you're working with a form, you can define a hidden +input+ and____ assign it a value of the last (focused) input +Working on the ideas above+, and if you're working with a form, you can define a |hidden input and assign| it a value of the last focused input";
const contentArea = document.getElementById('contentArea');
const getColored = text => text.replace(/\|(.+?)\|/g, '<span class="blue-string">$1</span>')
.replace(/\((.+?)\)/g, '<span class="red-string">$1</span>')
.replace(/\+(.+?)\+/g, '<span class="orange-string">$1</span>')
.replace(/_+/g, " <span class='blank'></span> ");
contentArea.innerHTML = getColored(text);
.blank {
display: inline-block;
border-bottom: 4px dotted red;
width: 150px;
}
.blue-string {
font-family: "Vazir";
color: #7e7cff;
display: inline-block;
text-shadow: 0px 0px 1px #010076;
}
.red-string {
font-family: "Vazir";
color: #ff005e;
display: inline-block;
text-shadow: 0px 0.5px 1px #e40053;
}
.orange-string {
font-family: "Vazir";
color: #ffb000;
display: inline-block;
text-shadow: 1px 1px 1px #b46a00;
}
<div id="contentArea"></div>

Related

How to set textarea height using min-height?

I am trying to create a message input field, using textarea. The reason I am using textarea is to be able to dynamically change the height.
To be able to dynamically change the height of the textarea and the parent divs, I have implemented this code.
The code works, just fine. To be able to use this JavaScript code I have to use min-height on the textarea. The problem is that I want to set the height of the textarea to 10px but it simply doesn't want to work, when using min-height. I does somehow work when I use height, but then the JavaScript won't work.
UPDATE:
I am just trying to create a field where the user can write a message and then post it.
Currently the textarea is too tall in my opinion, there is no reason for it to be taller than needed. So i want the height to initially be 20px, and then be able to expand as the user types.
UPDATE UPDATE:
I want to know how to set the height of the textarea to 10px or 20px, but still be able to dynamically change the height when the user types, using the javascript code i have provided
Any ideas on how to solve this? Btw, I'm not very well versed in CSS.
var areaName = "finder__input";
var textarea = document.getElementById(areaName);
textarea.addEventListener("input", function() {
const textarea = document.querySelector("textarea");
const textareaHeight = textarea.clientHeight;
textarea.style.height = "auto";
textarea.style.height = textarea.scrollHeight + "px";
});
body {
color: #292929;
background-color: #616f91
}
.container {
display: flex;
flex-direction: row;
justify-content: center;
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding-bottom: 100px;
}
.finder {
border: 1px solid #fff;
background-color: #f6f5f0;
border-radius: 5px;
/* width: 722px; */
padding: 3px;
box-shadow: 2px 2px 1px black, -1px -1px 1px white;
}
.finder__outer {
position: relative;
/* width: 700px; */
border-radius: 5px;
min-height: 1px;
padding: 8px;
background-color: transparent;
box-shadow: inset 2px 2px 5px -2px black, inset -10px -10px 5px -7px white;
}
.finder__input {
border: none;
resize: none;
background-color: red;
outline: none;
font-size: 15px;
letter-spacing: 1px;
width: 100%;
font-weight: bold;
min-height: 10px;
max-height: 90px;
}
<div class="container">
<div class="finder">
<div class="finder__outer" id="finder__outer">
<textarea id="finder__input" class="finder__input" type="text" name="q" placeholder="Write a message..."></textarea>
</div>
</div>
</div>
Resize textarea height on input
This is basically similar to this jQuery related question: Resize Textarea on Input.
Here's a rewrite in vanilla JavaScript
const textareaResize = (elTextarea) => {
elTextarea.style.height = "auto";
const h = elTextarea.scrollHeight;
elTextarea.style.height = `${h}px`;
};
document.querySelectorAll(".flexheight").forEach((elTextarea) => {
elTextarea.addEventListener("input", textareaResize); // on input
textareaResize(elTextarea); // on init
});
textarea.flexheight {
resize: none;
width: 100%;
box-sizing: border-box;
font: inherit;
height: 1rem;
}
Starts small and increment height as user types: <br>
<textarea class="flexheight" placeholder="Write a message..."></textarea>
<br>
<textarea class="flexheight" placeholder="Write about yourself..."></textarea>
var areaName = "finder__input";
var textarea = document.getElementById(areaName);
textarea.addEventListener("input", function() {
const textarea = document.querySelector("textarea");
const textareaHeight = textarea.clientHeight;
//textarea.style.height = "10px";
textarea.style.minHeight = textarea.scrollHeight + "px";
});
try using minHeight

Comments disappear after refreshing site

I'm trying to make a simple comment system. It display comments, but when I refresh the page , all comments disappear, only to re-appear again when I add a new comment. I would like to see the comments even after refreshing the page. And preferably with time stamp and in reverse order: so latest on top.
const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');
// array to store the comments
var comments_arr = [];
if(!localStorage.commentData){localStorage.commentData = [];}
else{
comments_arr = JSON.parse(localStorage.commentData);
}
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.push(content);
localStorage.commentData = JSON.stringify(comments_arr);
// re-genrate the comment html list
display_comments();
// reset the textArea content
field.value = '';
}
}
html {
font-size: 14px;
font-family: "Open Sans", sans-serif;
background-color: rgb(239, 239, 238);
}
/*Comment section*/
textarea {
margin: 40px 0px 10px 0px;
background-color: rgb(255, 255, 255);
width: 800px;
padding: 10px;
line-height: 1.5;
border-radius: 5px;
border: 1px solid #7097d1;
box-shadow: 1px 1px 1px #999;
}
#submit {
border-radius: 5px;
border: 1px solid #7097d1;
background-color: #e2e9ea;
}
#submit:hover {
background-color: #7097d1;
}
li {
list-style-type: none;
width: 770px;
margin: 10px 0px 10px -20px;
padding: 5px;
border-radius: 5px;
border: 1px solid #7097d1;
box-shadow: 1px 1px 1px #999;
background-color: #e2e9ea;
}
<link href="comment.css" rel="stylesheet">
<form>
<textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
<h4>Responses</h4>
<div id="comment-box"></div>
<script src="comment.js"></script>
Adding window.addEventListener('load', display_comments) will fix
This will run the display_comments function on every refresh
You call display_comments after submitting a comment, but you don't call it anywhere else - it needs to be called when the page loads as well.

Dom Javascript how can I connect my html form with my Javascript code

I spent whole day and half (36 hours) fighting with this issues of connecting my html form with my Javascript codes but till now it is not working....
Right now the stuff I tried to fix then working on html form are button and paragraph (results) but there are two inputs which are remain non-working. Please check for me my code to see if you could help me to fix this issue.
My project link on codepen.io
https://codepen.io/key-joshua/pen/XQGJdz
<!DOCTYPE html>
<html>
<body>
<div class="header">
<h1>Scale Balancing</h1>
</div>
<div class="input-groups">
<div class="input-group">
<label>Weights</label>
<!-- <br> -->
<input type="text" name="weight" id="weights" />
<!-- <br><br> -->
<label>Weights_Lists</label>
<!-- <br> -->
<input type="text" name="weights_list" id="weights_lists" />
<!-- <br><br> -->
<button id="balance" class="btns">Balance</button>
<br><br><br><br>
<p id="results" >Results....</p>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
*
{
margin: 0px;
padding: 0px;
}
.header{
width: 30%;
margin: 50px auto 0px;
color: white;
background: #423107;
text-align: center;
border: 1px solid #B0C4DE;
border-bottom: none;;
border-radius: 10px 10px 0px 0px;
padding: 20px;
}
form{
width: 20.5%;
margin: 0px auto;
padding: 20px;
border: 1px solid #B0C4DE;
border-radius: 0px 0px 10px 10px;
}
.input-group{
margin: 15px 0px 15px 0px;
}
.input-groups{
width: 29.5%;
margin: 0px auto;
padding: 20px;
border: 1px solid #B0C4DE;
border-radius: 0px 0px 10px 10px;
}
.input-group label{
color: #423107;
display: block;
text-align: left;
margin: 3px;
}
.input-group input{
height: 30px;
width: 93%;
padding: 5px 14px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btns{
float: left;
padding: 10px;
font-size: 15px;
color: white;
background: #4c390c;
/*border: none;*/
border-radius: 5px;
}
<script type="text/javascript">
const btn= document.getElementById("balance");
const message = document.getElementById("results");
// let weights = [2,5];
//let weights = document.getElementById('weights').value.split(',');
let weights = document.getElementById("weights").value = [2,3];
const right = weights[0];
const left = weights[1];
// var weights_list = [1,3,2,40,7];
//let weights_list = document.getElementById('weights_list').value.split(',');
let weights_list = document.getElementById('weights_lists').value= [1,3,2,40,7];
function ScaleBalancing() {
for (x = 0; x <weights_list.length; x++ )
{
if ( right == left )
{
message.innerHTML=" Already This Scale Balanced ";
}
else if ( right+weights_list[x]===left
||
right===left+weights_list[x])
{
message.innerHTML=' You Will Use ' + '' + weights_list[x] +' To Balance This Scale ';
}
for ( y=x+1; y<weights_list.length; y++)
{
if
(
right+weights_list[x]+weights_list[y] === left
        ||
left + weights_list[x] + weights_list[y] === right
        ||
right +weights_list [x] === left +weights_list [y]
        ||
left + weights_list[x] === right + weights_list[y]
)
{
message.innerHTML= ' You Use ' +'' + weights_list[x] + ',' + weights_list[y]+' To Balance This Scale ';
}
}
}
return'Scale Imbalanced !! There is no Weights into weights _list To Balance This Scale ';
}
btn.addEventListener('click', function(){
console.log(ScaleBalancing());
})
</script>
//all those codes together
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
*
{
margin: 0px;
padding: 0px;
}
.header{
width: 30%;
margin: 50px auto 0px;
color: white;
background: #423107;
text-align: center;
border: 1px solid #B0C4DE;
border-bottom: none;;
border-radius: 10px 10px 0px 0px;
padding: 20px;
}
form{
width: 20.5%;
margin: 0px auto;
padding: 20px;
border: 1px solid #B0C4DE;
border-radius: 0px 0px 10px 10px;
}
.input-group{
margin: 15px 0px 15px 0px;
}
.input-groups{
width: 29.5%;
margin: 0px auto;
padding: 20px;
border: 1px solid #B0C4DE;
border-radius: 0px 0px 10px 10px;
}
.input-group label{
color: #423107;
display: block;
text-align: left;
margin: 3px;
}
.input-group input{
height: 30px;
width: 93%;
padding: 5px 14px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btns{
float: left;
padding: 10px;
font-size: 15px;
color: white;
background: #4c390c;
/*border: none;*/
border-radius: 5px;
}
</style>
</head>
<body>
<div class="header">
<h1>Scale Balancing</h1>
</div>
<div class="input-groups">
<div class="input-group">
<label>Weights</label>
<!-- <br> -->
<input type="text" name="weight" id="weights" />
<!-- <br><br> -->
<label>Weights_Lists</label>
<!-- <br> -->
<input type="text" name="weights_list" id="weights_lists" />
<!-- <br><br> -->
<button id="balance" class="btns">Balance</button>
<br><br><br><br>
<p id="results" >Results....</p>
</div><br>
&copy Joshua
</div>
<script type="text/javascript">
const btn= document.getElementById("balance");
const message = document.getElementById("results");
// let weights = [2,5];
//let weights = document.getElementById('weights').value.split(',');
let weights = document.getElementById("weights").value = [2,3];
const right = weights[0];
const left = weights[1];
// var weights_list = [1,3,2,40,7];
//let weights_list = document.getElementById('weights_list').value.split(',');
let weights_list = document.getElementById('weights_lists').value= [1,3,2,40,7];
function ScaleBalancing() {
for (x = 0; x <weights_list.length; x++ )
{
if ( right == left )
{
message.innerHTML=" Already This Scale Balanced ";
}
else if ( right+weights_list[x]===left
||
right===left+weights_list[x])
{
message.innerHTML=' You Will Use ' + '' + weights_list[x] +' To Balance This Scale ';
}
for ( y=x+1; y<weights_list.length; y++)
{
if
(
right+weights_list[x]+weights_list[y] === left
        ||
left + weights_list[x] + weights_list[y] === right
        ||
right +weights_list [x] === left +weights_list [y]
        ||
left + weights_list[x] === right + weights_list[y]
)
{
message.innerHTML= ' You Use ' +'' + weights_list[x] + ',' + weights_list[y]+' To Balance This Scale ';
}
}
}
return'Scale Imbalanced !! There is no Weights into weights _list To Balance This Scale ';
}
btn.addEventListener('click', function(){
console.log(ScaleBalancing());
})
</script>
</body>
</html>
Now my button and paragraph for displaying result are working fine but those two inputs are not working on UI.
A Scale contains two elements, the first being the two positive integer weights on
a balance scale (left and right sides) and the second element being a list of
available weights as positive integers. Your goal is to determine if you can
balance the scale by using the least amount of weights from the list, but using at
most only 2 weights
Task For example:
if a scale is ["[5, 9]", "[1, 2, 6, 7]"] then this means there is a balance
scale with a weight of 5 on the left side and 9 on the right side. It is, in fact,
possible to balance this scale by adding a 6 to the left side from the list of weights
and adding a 2 to the right side. Both scales will now equal 11 and they are
perfectly balanced. Your program should return a comma separated string of the
weights that were used from the list in ascending order, so for this example, your
program should return the string 2,6.
Conditions
The first element of the scale can only contain 2 weights
It is possible to add two weights to only one side of the scale to balance it
If it is not possible to balance the scale then your program should return
“Scale Imbalanced”
UI Design:
2 inputs to take the 2 elements of the Scale
A button to calculate the needed weight to balance
A div to display the result
1st of all you don't have any form element.
2nd when using a form you'll reload page when submit so you've to use a button instead an or disable default behavior who's to send and reload page to action attribute value.
The 2nd is correct(but not really because input field elements meant to be wrapped in a form element) but you define a constant as the value you retrieve out of event so it'll be loaded when page load and not when you need it(when the event is popped).
There's no reason to use constant and you've to get the value when you need it, so when input is filled , meaning in the function used at 2nd parameter in the
.addEventListener( 'click' , function(){/*there you go grab data if fields are corectly filled*/
Define it at a constant set at page creation mean the value will be empty(or default but it seems there is none some) and ever be the same. So don't use constant and get value when it'll needed to be:
when user has filled inputs with correct values.
Another flaw who disturb me is you name id of input as list or they're meant to an unique value...that's not fit to reccomandation of writing a clear and understanble script.
More important i thought weight and other input are numerics values but you write input as text. Still there's not typed value in JS that could be used anyway but won't prevent user to write a text in the input and any numeric will be treated as string.
You can easily change this by using HTML5 attribute type='number' and even max and min required values who'll block a real form input if values are in wrong range.
Meaning your inputs values can easily set to not matching values and the program won't work or will display stupid answers, as by setting a weight(if that an human) above a possible weight.
Surely it need also to check values in the calculate function as a test if != isNaN(valueToCheck) to ensure that numbers are used and not ineadaquate values such a string.
That's a disavantage of a language who has not strong typed values, hopefully there's also avantages in this like a flexible way to use data but will need checking them when using them to be sure that wrong data type and non-relevant data are used instead of matching ones.

Change HTML Button style when click not working in Javascript

I want to change a button color when click the button. This is the code that I used.
function abc() {
var color = document.getElementById("btn").style.background - color;
if (background - color === "#c1580b")
document.getElementById("btn").style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
else
document.getElementById("btn").style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
}
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>
But this is not working.
I did not quite understand that part of the background - color, but to check the background in hex, you have to go from hex to rgb.
Can see here more examples of how to pass hex to rgb - https://stackoverflow.com/a/4090628/8098173
Here's an example of what you want.
function abc() {
var bt = document.getElementById('btn');
var style = bt.currentStyle || window.getComputedStyle(bt);
var bcolor = rgb2hex(style.backgroundColor);
if (bcolor === '#c1580b') {
bt.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
} else {
bt.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
}
}
// pass rbg to hex
function rgb2hex(rgb) {
if ( rgb.search("rgb") == -1 ) {
return rgb;
} else {
rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
}
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>
Here you have a working code.
I would suggest you to avoid the inline onclick="abc()" and opt in favor of a fully-separated code using EventListener (that's good for maintainability).
With Window.getComputedStyle() you get the background color in RGBA; you can then convert it to the HEX code with a simple function that you can find everywhere on the Web, here I used one of them. So, the right way to get the background color is window.getComputedStyle(btn, null)["backgroundColor"] while, if you would like to set it, the correct form would be document.getElementById("btn").style.backgroundColor = "#0000".
/**
* The code inside the function is run only when the DOM is ready.
* This is the only jQuery function used, all the rest is in vanillaJS.
*/
$(document).ready(function() {
/**
* rgb2hex
* Convert RGB to HEX.
* Source: https://jsfiddle.net/Mottie/xcqpF/1/light/
*
* #param {string} rgb
*/
var rgb2hex = function(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
/**
* EventListener of btn click event
*/
document.getElementById("btn")
.addEventListener('click', function() {
// Save the btn into a var so you can use it later
var btn = document.getElementById("btn");
// Notice: getComputedStyle() to get the element background color
var color = window.getComputedStyle(btn, null)["backgroundColor"];
// Transform RGBa to HEX
var hex = rgb2hex(color);
// IF-ELSE with ternary operators
(hex === "#c1580b")
? btn.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c"
: btn.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
});
});
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" class="btn">Pause</button>
</body>
</html>
if always you use this color in HEX format (#c1580b), So:
function abc() {
var elm = document.getElementById( 'btn' );
var color = window.getComputedStyle( elm ).backgroundColor;
if ( color === 'rgb(193, 88, 11)' )
elm.style.cssText = 'box-shadow: 0 0 0 3px #173B0B; background-color: #173B0B; color: #459c5c'
else
elm.style.cssText = 'box-shadow: 0 0 0 3px #c1580b; background-color: #c1580b; color: #ffb734'
}
Your code contains some logical error. The if condition has no sense : background - color means «substract the value of color to the value of background (which seems to be undefined).
To get the background color of the button, you need the following
background = document.getElementById("btn").style.backgroundColor;
if (background === "#c1580b")

removing the input text in the text field that matches the removed tab

In this example I made, since it uses keyup event, each input text (separated by comma) entered is converted into a tab. I want the input text to be deleted from the text field according to the tab I remove; for example, I enter "Item 1" but I suddenly change my mind and decide to remove the "Item 1" tab, the input text in the text field that has a string that matches the textContent of the removed tab should be automatically deleted from the text field.
var query = document.querySelector.bind(document);
query('#textfield').addEventListener('keyup', addTag);
function addTag(e) {
var evt = e.target;
if(evt.value) {
var items = evt.value.split(',');
if(items.length <= 10) {
evt.nextElementSibling.innerHTML = null;
for(var i = 0; i < items.length; i++) {
if(items[i].length > 0) {
var label = document.createElement('label'),
span = document.createElement('span');
label.className = 'tag';
label.textContent = items[i];
span.className = 'remove';
span.title = 'Remove';
span.textContent = 'x';
label.insertAdjacentElement('beforeend', span);
evt.nextElementSibling.appendChild(label);
span.addEventListener('click', function() {
var currentElement = this;
currentElement.parentNode.parentNode.removeChild(currentElement.parentNode);
})
}
}
}
} else {
evt.nextElementSibling.innerHTML = null;
}
}
section {
width: 100%;
height: 100vh;
background: orange;
display: flex;
align-items: center;
justify-content: center;
}
.container {
width: 50%;
}
input[name] {
width: 100%;
border: none;
border-radius: 1rem 1rem 0 0;
font: 1rem 'Arial', sans-serif;
padding: 1rem;
background: #272727;
color: orange;
box-shadow: inset 0 0 5px 0 orange;
}
input[name]::placeholder {
font: 0.9rem 'Arial', sans-serif;
opacity: 0.9;
}
.tags {
width: 100%;
height: 250px;
padding: 1rem;
background: #dfdfdf;
border-radius: 0 0 1rem 1rem;
box-shadow: 0 5px 25px 0px rgba(0,0,0,0.4);
position: relative;
}
.tags > label {
width: auto;
display: inline-block;
background: #272727;
color: orange;
font: 1.1rem 'Arial', sans-serif;
padding: 0.4rem 0.6rem;
border-radius: .2rem;
margin: 5px;
}
.tags > label > span {
font-size: 0.7rem;
margin-left: 10px;
position: relative;
bottom: 2px;
color: #ff4d4d;
cursor: pointer;
}
<section id="tags-input">
<div class="container">
<input type="text" name="items" id="textfield" placeholder="Enter any item, separated by comma(','). Maximum of 10" autofocus>
<div class="tags"></div>
</div>
</section>
How can I make that feature possible?
Replace the 'x' button listener with this one:
span.addEventListener('click', function () {
var text_field = document.getElementById("textfield");
var evt = this.parentNode;
var tags = text_field.value;
this.parentNode.removeChild(this); // remove the 'x' span so you can get the pure tag text with .innerHTML
var evname = evt.innerHTML;
var tags_array = tags.split(",");
var tag_position = tags_array.indexOf(evname);
if(tag_position > -1)
tags_array.splice(tag_position,1);
text_field.value = tags_array.join(',');
evt.parentNode.removeChild(evt);
})
// Coding this complexity in pure javascript when there is jQuery is ... like eating soup with a fork. You will get the job done, but it is dammn hard!

Categories

Resources