Changing CSS style of a class with Javascript - javascript

I'm new to javascript and I'm coding a temperiture converter. The program is basically done except im trying to make it so that the color of the text changes depending on the value of the temperiture. Eg: its 3 Degrees celcius so the text is blue to show that it's cold.
I added a class called temperiture to all of the I want the colour to change on. I've tried document.getElementByClassName aswell as document.QuerySelector.
The class 'temperature' has not been touched in the CSS file
This error is shown twice for the same line:
//Creating the funtion to convert celcius
function celciusConverter() {
const cTemp = parseFloat(celciusInput.value);
//Working out celcius to farenheight
const fTemp = (cTemp * (9/5) + 32);
//Working out celcius to kelvin
const kTemp = (cTemp + 273.15);
//Displaying the temperiture in all formats
farenheightInput.value = fTemp;
kelvinInput.value = kTemp;
if (cTemp < 15){
document.getElementsByClassName('#temperature')[0].style.color='black';
}
}
//Refreshing the screen when a number is put in
celciusInput.addEventListener('input', celciusConverter);
#import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background: black;
}
div{
height: 33.333vh;
}
#Farenheight{
border-top: 5px;
border-bottom: 5px;
}
input[type=number]{
outline: none;
width: 100%;
height 100%;
background: black;
color: white;
font-size: 6em;
text-align: centre;
border: 0;
font-family: Oswald, sans-serif;
}
<body>
<div id="celcius" class"temperature">
<input type="number" placeholder="Celcius. . .">
</div>
<div id="farenheight" class"temperature">
<input type="number" placeholder="Farenheight. . .">
</div>
<div id="kelvin" class"temperature">
<input type="number" placeholder="Kelvin. . .">
</div>
</body>
Uncaught TypeError: Cannot read property 'style' of undefined
at HTMLInputElement.celciusConverter

The reason why the color change was not working is because your temperature class was on the divs wrapping the inputs, and form items (inputs/textarea/etc) don't inherit font information from their parent by default. Using querySelectorAll, you can use the input[type=number] selector, just like you did in your css.
const celciusInput = document.querySelector("#celcius > input");
const farenheightInput = document.querySelector("#farenheight > input");
const kelvinInput = document.querySelector("#kelvin > input");
//Creating the funtion to convert celcius
function celciusConverter() {
const cTemp = parseFloat(celciusInput.value);
//Working out celcius to farenheight
const fTemp = (cTemp * (9/5) + 32);
//Working out celcius to kelvin
const kTemp = (cTemp + 273.15);
//Displaying the temperiture in all formats
farenheightInput.value = fTemp;
kelvinInput.value = kTemp;
document.querySelectorAll('input[type=number]').forEach(function (node) {
if (cTemp < 15) {
node.style.color = 'blue';
} else {
node.style.color = 'red';
}
})
}
//Refreshing the screen when a number is put in
celciusInput.addEventListener('input', celciusConverter);
#import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background: black;
}
div{
height: 33.333vh;
}
#Farenheight{
border-top: 5px;
border-bottom: 5px;
}
input[type=number]{
outline: none;
width: 100%;
height 100%;
background: black;
color: white;
font-size: 6em;
text-align: centre;
border: 0;
font-family: Oswald, sans-serif;
}
<body>
<div id="celcius" class"temperature">
<input type="number" placeholder="Celcius. . .">
</div>
<div id="farenheight" class"temperature">
<input type="number" placeholder="Farenheight. . .">
</div>
<div id="kelvin" class"temperature">
<input type="number" placeholder="Kelvin. . .">
</div>
</body>

The selector is incorrect. Don't put the # in front of the class name. getElementsByClassName just expects a string identical to the class name.
if (cTemp < 15){
document.getElementsByClassName('temperature')[0].style.color='black';
}
even better, I like to use querySelectorAll instead, which expects css like selectors.
I also assume you want to update the style of all of the .temperature elements. You can iterate over all of them instead of only updating the first one.
document.querySelectorAll('.temperature').forEach(function (node) {
if (cTemp < 15) {
node.style.color = 'blue';
} else {
node.style.color = 'red';
}
})

Related

Having issues with passing arguments through function (Javascript)

I'm creating a function using Javascript where the user puts in two integers, and the function will output the smaller of the two integers:
function minimum(num1, num2) {
var num1 = document.getElementById('input1').value;
var num2 = document.getElementById('input2').value;
if(num1 < num2){
document.getElementById('para').innerHTML = num1;
}
else if (num2 < num1){
document.getElementById('para').innerHTML = num2;
}
else {
document.getElementById('para').innerHTML = "There was something weird about your numbers. Please try again.";
}
}
body{
background-color: #A9927D ;
max-width: 900px;
min-width: 600px;
}
h1{
color: #F2F4F3;
text-align: center;
font-size: 45px;
}
h3 {
font-size: 20px;
color: #F2F4F3;
}
.container{
text-align: center;
}
.button-container {
padding: 50px;
}
.bttn{
height: 50px;
border-radius: 40px;
font-size: 20px;
font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
padding: 30px;
background-color: #5E503F;
box-shadow: 2px 2px 2px 2px #312A21;
color: #F2F4F3;
}
.bttn:hover {
background-color: #251F18;
}
.bttn:active {
box-shadow: 0 1px 0px #251F18;
}
.npt {
height: 40px;
width: 100px;
}
#para{
text-align: center;
margin: auto;
width: 40%;
height: 100px;
border: 1px solid #6E5E49;
background-color: #9C8568;
font-size: 20px;
color:#F2F4F3;
}
<div class="container">
<h1>Find the Minimum</h1>
<h3>by Solange Wright</h2>
<div class = "button-container">
<input class = "npt" type="number" id = "input1"><br><br>
<input class = "npt" type="number" id = "input2"><br><br><br><br>
<span class = bttn onclick = "minimum(num1, num2)">Find</span>
</div>
<p id="para"></p>
</div>
For some reason, I'm getting an error like this:
How do I define num1? Is it an issue with data types? Does the .value method in Javascript do type coercion, or is there another additional step to make sure the two values are integers?
You need to pass the id of the input.
Replace
<span class="bttn" onclick="minimum(num1, num2)">Find</span>
with
<span class"bttn" onclick="minimum('input1', 'input2')">Find</span>
It's generally not a good idea to use inline event handlers. You can use one handler for the document and use a generic handler (event delegation). Doing so gives you the possibility to use everything you need within the handler function.
Furthermore, the submitted values have to be checked (do both input have values?) and converted to Number (retrieved input values are always strings).
Finally you can use Math to determine the smallest number in an array of numbers.
This brings us to (removed stuff to present a minimum reproducable example):
document.addEventListener("click", getMinimalValue);
// ^ add a click listener method document wide
function getMinimalValue(evt) {
if (evt.target.id === "findSmallest") {
const numbers = [
document.querySelector("#input1").value || NaN,
document.querySelector("#input2").value || NaN
]
// ^ aggregate values into array (assign NaN if no value)
.map(Number)
// ^ convert values to Number (NaN will remain NaN)
.filter(n => !isNaN(n));
// ^ filter numbers only
document.querySelector("#para").textContent =
numbers.length < 2 ?
// ^ if not both entered values are numbers
// [numbers] array length is < 2
"You did not enter two numeric values" :
`Minimum of ${numbers.join(' and ')}: ${Math.min.apply(null, numbers)}`;
}
}
.npt {
width: 50px;
margin-bottom: 5px;
}
<input class="npt" type="number" id="input1">
<input class="npt" type="number" id="input2">
<span id="para"></span>
<br><button id="findSmallest">Find Minimum</button>
Remove the minimum parameters in the JS code (and also check if num1 and num2 are numbers)
function minimum() {
var num1 = document.getElementById('input1').value;
var num2 = document.getElementById('input2').value;
if (Number.isNaN(num1) || Number.isNaN(num2)){
document.getElementById('para').innerHTML = "please insert valid numbers";
return;
}
if(num1 < num2){
document.getElementById('para').innerHTML = num1;
}
else if (num2 < num1){
document.getElementById('para').innerHTML = num2;
}
else {
document.getElementById('para').innerHTML = "There was something weird about your numbers. Please try again.";
}
}
Refactor the button onclick not to pass paramters.
<div class="container">
<h1>Find the Minimum</h1>
<h3>by Solange Wright</h2>
<div class = "button-container">
<input class = "npt" type="number" id = "input1"><br><br>
<input class = "npt" type="number" id = "input2"><br><br><br><br>
<span class = "bttn" onclick = "minimum()">Find</span>
</div>
<p id="para"></p>
</div>

How to show/hide menu based on checkbox(s) value with JavaScript?

Update 10/4/18: I've updated the Snippet to reflected changes for anyone who may stumble upon this thread in seek of help. Existing check-boxes and newly added check-boxes will open/close the menu.
var statusChangeMenu, activeList, itemCheckBox, activeItems;
statusChangeMenu = document.getElementById("status-change-menu");
activeList = document.getElementById("active-items");
itemCheckBox = activeList.getElementsByClassName("item-checkbox");
activeItems = activeList.getElementsByClassName("active-item-text");
function addNewItem(event) {
event.preventDefault();
activeList.insertAdjacentHTML("afterbegin", "\
<li class=\"item\">\
<input class=\"item-checkbox\" type=\"checkbox\" name=\"checkbox\" />\
<span class=\"active-item-text\"></span>\
<button class=\"btn-complete\">complete</button>\
</li>");
activeItems[0].textContent = document.getElementById("new-item-text").value;
}
document.getElementById("btn-add-item").addEventListener("click", addNewItem, false);
activeList.addEventListener("change", function() {
var i, len;
for (i = 0, len = itemCheckBox.length; i < len || (i = 0); ++i) {
if (itemCheckBox[i].checked) {
i = 40;
break;
}
}
statusChangeMenu.style.height = i + "px";
}, false);
*{
margin: 0;
padding: 0;
}
body{
background-color: #393F4D;
}
header{
background-color: #1D1E22;
color: #FEDA6A;
text-align: center;
font-size: 10px;
}
main{
background-color: #707070;
max-width: 700px;
margin: auto;
margin-top: 20px;
padding: 15px;
}
#status-change-menu{
background-color: rgb(218, 123, 123);
margin-top: 10px;
height: 0px;
overflow: hidden;
transition: all .25s ease-in-out;
}
#status-change-menu>button>img{
height: 40px;
}
form{
background-color: #D4D4DC;
padding: 10px;
text-align: right;
box-shadow: 1px 1px 3px;
}
#new-item-text{
width: 100%;
}
#btn-add-item{
padding: 5px;
box-shadow: 1px 1px 3px;
}
.item-list-container{
background-color: #D4D4DC;
margin-top: 20px;
box-shadow: 1px 1px 3px;
}
.item{
background-color: rgb(165, 233, 222);
list-style: none;
display: grid;
grid-template-columns: auto 1fr max-content;
grid-template-rows: 30px;
margin-top: 10px;
}
.item-checkbox{
grid-column: 1/2;
width: 30px;
margin:auto;
}
.active-item-text{
grid-column: 2/3;
background: rgb(252, 252, 252);
overflow: hidden;
}
.btn-complete{
grid-column: 3/4;
}
.item>input{
height: 20px;
}
<body id="the-list">
<header>
<h1>The List V4</h1>
</header>
<main>
<form action="#">
<textarea name="textbox" id="new-item-text" cols="30" rows="1"></textarea>
<button type="submit" id="btn-add-item">Add</button>
</form>
<div id="status-change-menu" class="change-menu">
<h3>Status Change Menu</h3>
<button class="btn-bar-hold">BTN1<img src="img/btn_hold.svg" alt=""></button>
<button class="btn-bar-delete">BTN2<img src="img/btn_delete.svg" alt=""></button>
</div>
<div class="item-list-container">
<ul id="active-items" class="item-list">
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
</ul>
</div>
</main>
</body>
I'm working on a simple checklist web app using pure vanilla HTML, CSS, javascript. I've been stuck in one part all weekend. Hoping someone can shed some light on what I'm missing or doing wrong. Here's where I'm at.
My Goal
Whenever an item in the checklist (ul) is selected (via checkbox), a hidden menu slides out with various options to manipulate the selected item(s). The menu must stay visible if any of the checkboxes on the list are checked. The menu must close if no checkboxes are checked.
Where I'm Stuck
I'm able to get the menu to slide out during a 'change' event of the checkbox, but I can't get the menu element to react after the initial change event. During debugging, it also appears the menu element is not reacting to the checkbox is in a 'checked' state, but simply just reacting to the checkbox being changed in general. Here's the JS code I have, but I've tested various other configurations with no success.
Code Pen with Full Code & Snippet of related JS code below.
Updated Codepen 10/4/18
https://codepen.io/skazx/pen/mzeoEO?
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]')
var statusChangeMenu = document.getElementById("status-change-menu")
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
if (!itemCheckBox.checked)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
I've read a few dozen different post and articles, but most were related to only having 1 checkbox or used jquery. Let me know if you need any further details. Thank you!
itemCheckBox refers to a NodeList returned by querySelectorAll, not an individual element, so saying itemCheckBox.checked doesn't really make sense.
You should be checking if any checkbox in the list is checked, which you can use with the .some() function, like so:
Here's a working demo
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", function(event) {
if (!event.target.checked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
});
}
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]');
var statusChangeMenu = document.getElementById("status-change-menu");
function changeHandler (event) {
// get the list of checkboxes in real time in case any were added to the DOM
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var anyChecked = [].some.call(checkboxes, function(checkbox) { return checkbox.checked; });
// alternatively (instead of using .some()):
// var anyChecked = false;
// checkboxes.forEach(function (checkbox) {
// if (checkbox.checked) {
// anyChecked = true;
// }
// });
if (anyChecked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
}
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", changeHandler);
}
for (var i = itemCheckBox.length; i < itemCheckBox.length + 2; i++) {
// add some checkboxes dynamically
var newCheckbox = document.createElement("input");
var newLabel = document.createElement("label");
newLabel.innerText = "Checkbox " + (i + 1);
newCheckbox.type = "checkbox";
// -- IMPORTANT-- bind event listener on dynamically added checkbox
newCheckbox.addEventListener("change", changeHandler);
newLabel.appendChild(newCheckbox);
newLabel.appendChild(document.createElement("br"));
document.body.appendChild(newLabel);
}
#status-change-menu {
height: 0;
background-color: red;
overflow: hidden;
color: white;
font-weight: bold;
}
<div id="status-change-menu">I should be visible if any checkboxes are checked</div>
<label>Checkbox 1<input type="checkbox"/></label><br/>
<label>Checkbox 2<input type="checkbox"/></label><br/>
<label>Checkbox 3<input type="checkbox"/></label><br/>
mhodges is correct in that itemCheckBox is a NodeList, not an individual element. Another issue is that you are trying to test if the box that changed is checked, and if it isn't, you are closing the menu. As you described, that is not what you want.
You need another way to check to see if all check boxes are unchecked before you close the menu. A simple way to do that is just another inner loop in the onChange function:
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
showMenu = false
for(var j = 0; j < itemCheckBox.length; j++)
{
if(itemCheckBox[j].checked)
showMenu = true
}
if (showMenu)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
Heres a modified Snippet

dynamically update css content using javascript

There is a need to update css to dynamic value and I am not sure what's the best approach to it.
<div id="app" style="zoom: 0.XX;">
...
</div>
The zoom level will trigger based on window resize and the app will zoom according. I loaded this app into cordova and have it run within iPAD, then I realize the font-size needs to be adjusted to the same as zoom level using "-webkit-text-size-adjust" in order for it to not break the design layout.
My challenge is to set the css dynamically like this:
#app * {
-webkit-text-size-adjust : nn%
}
Where nn is the zoom X 100 + '%'
I have tried:
1) Set the style on the app div, but this doesn't help to apply to inner elements
<div id="app" style="zoom: 0.XX; -webkit-text-size-adjust: XX%">
2) Use javascript to set to all inner nodes, but not only I think this is less efficient, but it won't get trigger if my window doesn't resize, that means if I navigate to other pages, this logic won't get called.
REF: https://stackoverflow.com/questions/25305719/change-css-for-all-elements-from-js
let textSizeAdjust = function(zoom) {
let i,
tags = document.getElementById("app").getElementsByTagName("*"),
total = tags.length;
for ( i = 0; i < total; i++ ) {
tags[i].style.webkitTextSizeAdjust = (zoom * 100) + '%';
}
}
3) I tried using javascript, and most likely they are technically incorrect because querySelector return null.
document.querySelector('#app *').style.webkitTextSizeAdjust = zoom *100 + '%';
document.querySelector('#app').querySelector('*').style.webkitTextSizeAdjust = zoom * 100 + "%";
Ultimate, I believe I need to dynamically create the css, for the browser to apply this setting to the DOM:
#app * {
-webkit-text-size-adjust: nn
}
Please let me know if this is the right, or how to use javascript to create the above css and change the value dynamically?
CSS Variables
Requirements
HTML
Each form control that has numerical data should have:
value={a default, don't leave it blank}
class='num'
data-unit={unit of measurement or a single space}
The select/option tag should have the selected attribute
CSS
CSS Variable Signature: propertyName: var(--propertyValue)
// Declare CSS Variables at the top of a stylesheet
:root {
--mx0: 50px;
--my0: 50px;
--rz0: 1.0;
--zm0: 1.0;
--sp0: 360deg;
}
JavaScript
There's step by step details commented in the JavaScript Demo. Here's the most important statement in the code:
CSSStyleDeclaration CSS Variable
🢃 🢃
`ele.style.setProperty(`--${node.id}`,
${node.valueAsNumber}${node.dataset.unit})
🢁 🢁
HTMLInputElement DataSet API
Demo 1
// Reference form#UI
var ui = document.forms.UI;
// Register form#UI to change event
ui.addEventListener('change', setCSS);
// Callback passes Event Object
function setCSS(e) {
// Collect all form controls of form#UI into a NodeList
var fx = ui.elements;
// Reference select#pk0
var pk0 = fx.pk0;
// Get select#pk0 value
var pick = pk0.options[pk0.selectedIndex].value
// if the changed element has class .num...
if (e.target.className === 'num') {
// Reference Event Target
var tgt = e.target;
// Then reference is by its #id
var node = document.getElementById(tgt.id);
// DOM Object to reference either html, square, or circle
var ele;
/* Determine which tag to test on: html (affects everything),
|| #sQ<uare> and #ciR<cle> shapes.
*/
switch (pick) {
case "rT":
ele = document.documentElement;
break;
case "sQ":
ele = document.getElementById('sQ');
break;
case "cR":
ele = document.getElementById('cR');
break;
default:
break;
}
/* Sets a target element's Transform:
|| translateXY, scale, and rotate
*/
ele.style.setProperty(`--${node.id}`, `${node.valueAsNumber}${node.dataset.unit}`);
}
}
/* Declare CSS Variables on the :root selector at the top of sheet
All CSSVar must be prefixed with 2 dashes: --
*/
:root {
--mx0: 50px;
--my0: 50px;
--rz0: 1.0;
--sp0: 360deg;
}
.set {
border: 3px ridge grey;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
padding: 5px;
}
/* The var() function's signature is:
propertyName: var(--propertyValue)
*/
#sQ {
position: relative;
background: rgba(0, 100, 200, 0.3);
width: 50px;
height: 50px;
transform: translateX(var(--mx0)) translateY(var(--my0)) scale(var(--rz0)) rotate(var(--sp0));
border: 3px ridge grey;
z-index: 1;
transition: all 1s ease;
}
#cR {
position: relative;
background: rgba(200, 100, 0, 0.3);
width: 50px;
height: 50px;
transform: translateX(var(--mx0)) translateY(var(--my0)) scale(var(--rz0)) rotate(var(--sp0));
border: 3px ridge grey;
border-radius: 50%;
transition: all 1s ease;
}
#sQ::before {
content: '\1f504';
text-align: center;
font-size: 2.25rem;
transform: translate(1px, -8px)
}
#cR::after {
content: '\1f3b1';
text-align: center;
font-size: 2.25rem;
}
input,
select {
display: inline-block;
width: 6ch;
font: inherit;
text-align: right;
line-height: 1.1;
padding: 1px 2px;
}
select {
width: 9ch
}
.extension {
overflow-y: scroll;
overflow-x: auto;
min-height: 90vh;
}
/* For debugging on Stack Snippets */
/*.as-console-wrapper {
width: 25%;
margin-left: 75%;
min-height: 85vh;
}*/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style></style>
</head>
<body>
<!--
HTML Requirements
Each form control that has numerical data should have:
1. value={a default, don't leave it blank}
2. class='num'
3. data-unit={unit of measurement or a single space}
4. The select/option tag should have the selected attribute
-->
<form id='UI'>
<section class='set'>
<label>X: </label>
<input id='mx0' class='num' type='number' min='-350' max='350' value='50' step='10' data-unit='px'>
<label>Y: </label>
<input id='my0' class='num' type='number' min='-350' max='350' value='50' step='10' data-unit='px'>
<label>Size: </label>
<input id='rz0' class='num' type='number' min='0' max='5' value='1' step='0.1' data-unit=' '>
<label>Spin: </label>
<input id='sp0' class='num' type='number' min='0' max='1440' value='360' step='180' data-unit='deg'>
<label>Pick: </label>
<select id='pk0' class='num'>
<option value='rT' selected>Root</option>
<option value='sQ'>Square</option>
<option value='cR'>Circle</option>
</select>
</section>
</form>
<section class='set extension'>
<div id='sQ' class='test shape' width="50" height="50"></div>
<div id='cR' class='test shape' width="50" height="50"></div>
</section>
</body>
</html>
Update
This update is specifically for OP, so this may be of help or not for other users.
Deno 2
:root {
--opc: 0;
--zoom: 1;
}
.fc {
display: inline-block;
width: 18ch;
margin:0 0 10px 0
}
#app * {
opacity: var(--opc);
transform: scale(var(--zoom));
}
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
</head>
<body>
<form id='app' action='https://httpbin.org/post' method='post' target='view'>
<fieldset class='sec'>
<legend>App of Mystery</legend>
<input id='A0' name='A0' class='fc' type='text' placeholder='User Name'>
<input id='A1' name='A1' class='fc' type='password' placeholder='Password'>
<input type='submit'>
<input type='reset'>
<input id='zBtn' type='button' value='Zoom'>
<iframe name='view' frameborder='1' width='100%'></iframe>
</fieldset>
</form>
<script>
var node = document.querySelector('#app *');
var zBtn = document.getElementById('zBtn');
var flag = false;
document.addEventListener('DOMContentLoaded', function(e) {
node.style.setProperty("--opc", "0.5");
});
document.addEventListener('click', function(e) {
node.style.setProperty("--opc", "1");
});
zBtn.addEventListener('click', function(e) {
if (flag) {
flag = false;
node.style.setProperty("--zoom", "1");
} else {
flag = true;
node.style.setProperty("--zoom", "1.25");
}
});
</script>
</body>
</html>
I don't have much knowledge about -webkit-text-size-adjust
However, this should work for creating a dynamic stylesheet and inserting it:
I have added code to dynamically update it as well
const form = document.getElementById('colorChooser');
form.addEventListener('submit', (e) => {
e.preventDefault();
color = document.getElementById('colorInput').value;
const style = document.getElementById('colorStyle');
style.innerHTML = `#app * {
background-color: ${color};
}`;
});
const style = document.createElement('style');
style.id = 'colorStyle';
style.type = 'text/css';
style.innerHTML = `#app * {
background-color: red;
}`;
document.head.appendChild(style);
#app {
margin-bottom: 10px;
}
#inner {
width: 50px;
height: 50px;
background-color: black;
}
<div id="app">
<div id="inner"></div>
</div>
<form id="colorChooser">
<input id="colorInput" type="text" placeholder="red" />
<input type="submit" value="Update color"/>
</form>

Credit cards types for jessepollak's JQuery.Card.js

I am using jquery.card.js from jessepollak. It is awesome.
If anyone has experience with it, could you please tell me if there is an option to choose what types of credit card you want to support?
e.g.
//This is how I would like it to be...
var card = new Card({
supportedCardTypes: 'Visa, Master'; //I don't want DC or AMEX etc...
});
Is there any options like that? How do I achieve it?
Thank you.
Answer ------------------------------------------------------------
Turns out, only changing cardTypes as TMan suggested didn't work. But it is not about the fish, it is about giving me the idea of fishing. Following TMan's idea hacking into the script, I found adding this line would work:
Card.prototype.handlers = {
setCardType: function($el, e) {
//my modification here to support only Visa and Master!!
var cardType = e.data === 'mastercard' || e.data === 'visa' ? e.data : 'unknown';
//end of my modification!!
if (!QJ.hasClass(this.$card, cardType)) {
QJ.removeClass(this.$card, 'jp-card-unknown');
QJ.removeClass(this.$card, this.cardTypes.join(' '));
QJ.addClass(this.$card, "jp-card-" + cardType);
QJ.toggleClass(this.$card, 'jp-card-identified', cardType !== 'unknown');
return this.cardType = cardType;
}
},
You can just hack the library source code, quick and dirty NOT the best idea, or do something to initialise the handlers your way in your own code.
Thanks again.
Great ideas all around. Here's a way to take your addition to the handler and override it without having to hack at the library. This will persist future changes much better.
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
Demo in Stack Snippets
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
var card = new Card({ form: '.form-container form', container: '.card-wrapper' })
.form-container {
margin-top: 20px;
}
.form-container input {
font-family: 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
float: left;
}
.form-container input.col-6 {
width: 50%
}
.form-container input.col-3 {
width: 25%
}
.form-container input[type="text"] {
background-color: #fff;
border: 1px solid #cccccc;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-container .button {
cursor: pointer;
position: relative;
text-decoration: none;
text-align: center;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
color: #fff;
background-color: #008CBA;
border-width: 0;
}
.form-container .button:hover,
.form-container .button:focus {
background-color: #007295;
}
<script src="https://rawgit.com/jessepollak/card/master/lib/js/card.js"></script>
<div class="demo-container">
<div class="card-wrapper"></div>
<div class="form-container">
<form action="">
<input placeholder="Card number" type="text" name="number" class="col-6"/>
<input placeholder="Full name" type="text" name="name" class="col-6"/>
<input placeholder="MM/YY" type="text" name="expiry" class="col-3"/>
<input placeholder="CVC" type="text" name="cvc" class="col-3"/>
<input type="submit" value="Submit" class="button col-6"/>
</form>
</div>
</div>
To test it, you can look at the card payment definitions:
mastercard (55*) - works ✓
visa (4*) - works ✓
amex (37*) - doesn't ✓
Based on the Coffeescript file, I think your best bet would be to fork the library and then remove the cards you don't want to support from the cardTypes array so that all other numbers would show up as undefined.
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee
Or the following line in card.js:
https://github.com/jessepollak/card/blob/master/lib/js/card.js#L1134
Card.prototype.cardTypes = ['jp-card-amex', 'jp-card-dankort', 'jp-card-dinersclub',
'jp-card-discover', 'jp-card-jcb', 'jp-card-laser', 'jp-card-maestro',
'jp-card-mastercard', 'jp-card-unionpay', 'jp-card-visa', 'jp-card-visaelectron'];
You'll also probably want to modify the cardTemplate variable to remove the DOM nodes that no longer apply:
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee#L36

Have different line-height between input and output area

I'm trying to make a terminal shell like page.
See my code at jsfiddle:
http://jsfiddle.net/paopaomj/qGw4Q/9/
The input line seems have more line-height then the outputs.
Try it and type something press some enters you'll know what I mean.
Thanks.
html:
<body>
<div id="output"></div>
<div id="input">
root#host
<input type="text" id="command" />
</div>
javascript:
$("#command").keyup(function (e) {
if (e.keyCode == 13) {
submit();
}
});
var submit = function () {
var commandEl = document.getElementById("command");
var command = commandEl.value;
var outputel = document.getElementById("output");
var new_row = document.createElement("div");
new_row.innerHTML = "root#host " + command;
outputel.appendChild(new_row);
commandEl.value="";
};
The input got some padding. Add
padding:0px;
margin-left:-1px;
to the input css
OK.
I got it sovled finally by setting margin=0 for input field, margin-top=0 for iutput div, and margin-bottom=0 for output div:
#output { margin-bottom: 0px; background-color: #000000; }
#input { margin-top: 0px; background-color: #000000; }
input {
border: 0;
background: #000000;
color: #00FF00;
outline: none;
font-family:'Rosario', sans-serif;
font-size: 16px;
padding: 0px;
margin-left: -0.1px;
margin: 0px;
}
Thanks for Johan's help!

Categories

Resources