Create text outline for a text input - javascript

I've got a text box that the user inputs a hex value for a colour. The text box will change colour to the hex value entered, however the problem is that if the input is a shade of black, or any dark colour, it is very difficult, or impossible to see what hex value has been entered. So I want the inputted text to have a different coloured outline, for example white so the user is clearly able to see what they have entered.
This is a part of my code:
<head>
<style>
#ColourInput { /* apply this style to element id="ColourInput" */
left: 240px;
top: 60px;
width: 100px;
}
input[type=text]:focus {
border: 3px solid #555;
</style>
<script>
function fnCustomColour() {
var sHexValue = document.getElementById("ColourInput").value;
var ValueValid = 0
fnDebugMessage(sHexValue);
if (/[0-9A-F]{6}$/i.test(sHexValue)) {
if (sHexValue.indexOf("#") === 0) {
} else {
sHexValue = "#"+sHexValue
}
ValueValid = 1
} else {
alert("Value not allowed");
ValueValid = 0
}
if (ValueValid = 1) {
ColourInput.style.backgroundColor = sHexValue;
fnSetFillColour(sHexValue);
fnDebugMessage(sHexValue);
}
}
</script>
</head>
<div id="CustomColour">
Custom Colour Input: #<input type="text" id="ColourInput" name="CustomColour" placeholder="Enter Hex Value" pattern="[a-fA-F0-9]{8}$/i"><br>
<input type="submit" onclick="fnCustomColour();" id="ColourSubmit" value="Submit">
</div>
Any help will be appreciated

Related

Text input's border changes color only when the second wrong character is typed - Javascript

I am building a tip calculator and I want the text input to turn red if a "non-number" is typed, and green if a number is typed.
Works good with the number. Once I type a number the border turns green, but if I type a letter, for the first letter it turns green, then only when the second letter is typed it turns red.
It happens both if the page just loaded and if there were values typed before.
I tried to change the trigger with onkeyup and onkeydown, but didn't work, and I'm pretty sure that would not be the solution anyways.
The Snippet
function checking() {
let hey = document.querySelector('.checkInput')
let hello = document.querySelector('.howMuch')
if(isNaN(hey.value)) {
hey.style.border = '1px solid red'
}
else {
hey.style.border = '1px solid green'
}
}
.red {
color: red;
}
input:focus::placeholder {
color: transparent;
}
input {
outline: none;
}
<div class="container">
<label for="checkInput">How much is the check?</label>
<input class="checkInput" onkeypress="checking()" id="checkInput" type="text"><br>
</div>
You need to use the keyup event, because the text is not actually inserted yet on 'keypress':
function checking(e) {
const input = document.querySelector('.checkInput')
if(isNaN(input.value)) {
input.style.border = '1px solid red'
}
else {
input.style.border = '1px solid green'
}
}
.red {
color: red;
}
input:focus::placeholder {
color: transparent;
}
input {
outline: none;
}
<div class="container">
<label for="checkInput">Input: </label>
<input class="checkInput" onkeyup="checking()" id="checkInput" type="text"><br>
</div>
Keypress lifecycle demo:
const inp = document.querySelector('#test');
inp.addEventListener("keyup", log);
inp.addEventListener("keypress", log);
inp.addEventListener("keydown", log);
function log(event){
console.log(event.type, inp.value);
}
<input id="test">

Get and put paramter to url based on slected data using jQuery

I have a following <div> structure:
<div class="color-class" data-color="red">
<div class="inside-color">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color">Blue</div>
</div>
So, when people click on any color class then the page is redirected with corresponding color in the url with the following:
var color=urlObj.searchParams.get("color");
$(".color-class").on("click",function(){
if( $(this).find(".inside-color").hasClass("selected")){
location.href=location.href.replace(/&?color=([^&]$|[^&]*)/i, "");
}
else {
var se_val=$(this).data("color");
$(this).find(".inside-color").addClass("selected");
if ( !color ){
if(url.indexOf("?") >= 0){
url =url+"&color="+se_val;
}
else {
url =url+"?color="+se_val;
}
window.location.href=url;
return;
}
if ( color){
urlObj.searchParams.set("color", color+","+se_val);
window.location.href=urlObj;
return;
}
}
});
So using this code i can redirect so after my redirection i get url like example.com/?color=red
Then I have to add class name called selected to the corresponding inside-color.
So I write the following code:
if ( color ){
$(".color-class[data-color='"+color+"']").find(".inside-color").addClass("selected");
}
But if my url is http://www.example.com/?color=red%2Cgreen how i can add selected class to both… ie add selected class to both red and green,
If my url is http://www.example.com/?color=red%2Cgreen and some one again click on green color then how can i remove green from the url and add selected to red color only.
Any Help will be appreciated.
Consider if this was a form, you might have something like:
<form action="example.com" method="get">
<input type="checkbox" class="inside-color" name="inside-color[]" value="red" /><label>Red</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="green" /><label>Green</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="blue" /><label>Blue</label>
<button type="submit">Go</button>
</form>
This will create an encoded URL like:
example.com?inside-color%5B%5D=red&inside-color%5B%5D=green
This is the method for passing an Array via GET. one option would be to pass the details in this method and parse it. Doing this will result in a small array and you can then iterate the array set selected on each of the specific colors.
In your example, you are passing a single string in one variable, and using a delimiter. Sp you'd need to first get the string and then split it. Again, this will result in an array that can be iterated.
if the user unchecked one of the options, removing selected, you could then remove that element from the array.
My suggestions:
function setSelections(c) {
$.each(c, function(k, v) {
if (v) {
$(".color-class[data-color=" + k + "]").addClass("selected");
}
});
}
$(function() {
var colors = {
red: 0,
green: 0,
blue: 0
};
$(".color-class").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
colors[$(this).attr("data-color")] = 0;
} else {
$(this).addClass("selected");
colors[$(this).attr("data-color")] = 1;
}
});
$("#save-selection").click(function(e) {
e.preventDefault();
var url = "http://example.com/?" + $.param(colors);
console.log("URL: " + url);
})
});
.color-class {
width: 40px;
height: 40px;
border: 2px solid #ccc;
border-radius: 4px;
margin: 2px;
}
.color-class:hover {
border-color: #a0a0a0;
}
.color-class.selected {
border-color: #202020;
}
.color-class .inside-color {
border-radius: 3px;
width: 100%;
height: 70%;
color: white;
font-size: 75%;
text-align: center;
padding-top: 30%;
}
.color-class .inside-color.red {
background: red;
}
.color-class .inside-color.green {
background: green;
}
.color-class .inside-color.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-class" data-color="red">
<div class="inside-color red">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color green">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color blue">Blue</div>
</div>
<button id="save-selection">Save</button>
The console shows: URL: http://example.com/?red=1&green=1&blue=0 This will be easier to parse back into an object that can be used with setSelections() function.
Hope that helps.
ok try something like this i am just posting some part of your code
var color=urlObj.searchParams.get("color");
if ( color ){
var splitColors = color.split('%2C');
for(var i=0;i<splitColors.length;++i)
{
$(".color-class[data-color='"+splitColors[i]+"']").find(".inside-color").toggleClass("selected");
}
}

Changing background color in one field when compared to another field using Javascript

I am creating a meal plan for a homework assignment in my JavaScript class and I have everything working except for this one part. Both of the input fields are numbers not text.
If the sum of the calories from the selected meals is greater than their targeted intake, the calories count box will display the calories sum in a red background with bold white letters, otherwise, a green background with black letter
function changeCount() {
var target = parseFloat( document.getElementById("target") ).value;
var count = parseFloat( document.getElementById("count") ).value;
if ( count.value < target.value ) {
count.classList.add("good");
} else {
count.classList.add("over");
}
}
You just needed to remove parseFloat and .value from the declaration and use it when comparing
function changeCount(){
var target = document.getElementById("target"),
count = document.getElementById("count");
if (count.value < target.value){
count.classList.add("good");
count.classList.remove("over");
} else {
count.classList.add("over");
count.classList.remove("good");
}
}
.good{
background-color: green;
color:white;
font-weight: bold;
}
.over{
background-color: red;
color:white;
font-weight: bold;
}
<input type="text" id="target" placeholder="target" />
<input type="text" id="count" placeholder="count" />
<input type="button" value="calculate" onclick="changeCount()" />

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.

Mask input for number - percent

How can create a mask input for number that have percent by jQuery? Do I make input just accept until three numbers and put percent sign after numbers while user finished typing(keyup)?
I don't use plugins.
Example:
1% Or 30% Or 99% Or 100% Or 200%
<input name="number" class="num_percent">
You're better off not using JavaScript for this. Besides the problems that come with using onkeyup for detecting text input, you also have the hassle of parsing the resulting string back to a number in your client/server scripts. If you want the percent sign to look integrated, you could do something like this:
<div class="percentInput">
<input type="text" name="number" class="num_percent">
<span>%</span>
</div>
.percentInput { position:relative; }
.percentInput span { position: absolute; right: 4px; top:2px; }
.num_percent { text-align: right; padding-right: 12px; }
http://jsfiddle.net/BvVq4/
I'm rushing slightly, so you may have to tweak the styles to get it to look right cross-browser. At least it gives you the general idea.
I've stayed with input number, moved the percentage char and then modified its position according to the length of the input (the amount of digits).
HTML
<input type="number" min="0" max="100" value="100"> //chose 100 only for the sake of the example
<span class="percentage-char">%</span>
CSS
input {
width: 55px;
height: 20px;
font-size:18px;
}
.percentage-char {
position: absolute;
left: 32px; // default position - in this case 100
top: 1px;
font-size: 18px;
}
.one-digit { //position of the '%' when input is 0-9
left: 13px;
}
.two-digits{ //position of the '%' when input is 10-99
left: 24px;
}
JS
$(":input").change(function() { //listening to changes on input
if ($(this).val() < 10) { //adding and removing the classes
$('.percentage-char').removeClass('two-digits');
$('.percentage-char').addClass('one-digit');
} else if ($(this).val() > 9 && $(this).val() < 100) {
$('.percentage-char').addClass('two-digits');
} else {
$('.percentage-char').removeClass('one-digit two-digits');
}
});
Check out this fiddle
function setPercentageMask() {
let input = $('.percent');
input.mask('##0,00', {reverse: true});
input.bind("change keyup", function() {
isBetweenPercentage($(this));
});
}
function isBetweenPercentage(input) {
let myNumber = (input.val()) ? parseFloat(input.val()) : 0;
(myNumber.isBetween(0, 100.00)) ? myNumber : input.val('100,00');
}
if (typeof(Number.prototype.isBetween) === "undefined") {
Number.prototype.isBetween = function(min, max, notBoundaries) {
var between = false;
if (notBoundaries) {
if ((this < max) && (this > min)) between = true;
} else {
if ((this <= max) && (this >= min)) between = true;
}
return between;
}
}
setPercentageMask();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<input name="text" class="percent">

Categories

Resources