How to set width of a div in percent in JavaScript? - javascript

Is it possible to set the height/width of an element in percent using JavaScript or jQuery?

document.getElementById('header').style.width = '50%';
If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

jQuery way -
$("#id").width('30%');

I always do it like this:
$("#id").css("width", "50%");

The question is what do you want the div's height/width to be a percent of?
By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.
So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:
obj.style.width = '50%';

Yes, it is:
<div id="myid">Some Content........</div>
document.getElementById('myid').style.width = '50%';

Also you can use .prop() and it should be better because
Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.
$(elem).prop('width', '100%');
$(elem).prop('height', '100%');

testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>

Related

input type password is immovable

I have this code and the 1st input won't ever move whatever I do the only thing that made it move was float:right; but I don't want it to be like this I even created this div->P so maybe it would move. Has anyone encountered this problem before?
Is it possibly interfearing with my js? That's the only thing I can think of rn
.inner {
display:inline-block;
margin-right:500px;
}
.pswd {
display:inline-block;
margin-right:500px;
}
</style>
</head>
<body>
<div class="P">
<input class="inner" type="password" id="pswd">
<input class="inner" type="button" value="Submit" onclick="checkPswd();"/>
</div>
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "admin";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="A.html";
}
else{
alert("Password incorrect.");
}
}
</script>
This should work if you use the ID selector rather than the class selector (i.e. use # rather than .):
#pswd {
display:inline-block;
margin-right:500px;
}
There are multiple ways to center-align a div both vertically and horizontally on the screen.
I have used display:flex for the same.
'use-strict'
function checkPswd(form) {
const confirmPassword = "admin";
let passwordProvided = form.elements.newPassword.value;
if (passwordProvided === confirmPassword) {
// If correct
} else {
// If failure
}
// to prevent default action
return false;
}
.form--wrapper {
width: 150px;
height: 150px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
width: 100%;
border: 2px dashed orange
}
<div class="form--wrapper">
<form name="change-password" onsubmit="return checkPswd(this)">
<input class="inner" name="newPassword" type="password">
<input class="inner" type="submit" value="Submit" />
</form>
</div>

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>

Apply error message to textbox

i am trying to apply some validation error to controls like textbox. i initially was using qtip.js but for some reason it's not working well. so, i was trying to manually show error at the position i would like to show.
How would i exactly get the coordinates at the right-top corner of a control(eg: textbox as shown in picture) so i can show error message. i tried to use offset feature but to no avail.
var x = $("txtBox1").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
I think it's best to just place the error right under the textbox using just plain HTML positioning. The manual positioning using JavaScript is not necessary.
Here is a fiddle: https://jsfiddle.net/v0k1jbug/
<input type="text">
<div class="error">Error</div>
Then if you are using JQuery you can show/hide/populate the error message as you wish.
Hope this helps.
jsFiddle : https://jsfiddle.net/jchotdjk/1/
html
<div class="container">
<div class="input-group">
<input type="text" />
<span class="error">Invalid email address</span>
</div>
</div>
CSS
.container {
padding: 25px;
background-color: #9b9;
}
.input-group input{
height: 20px;
}
.input-group .error{
position: relative;
top: -20px;
}
To place the error just above the input and to the right, place the error in a span. Then you need to set the position of the error to relative and then force it up by the total height of the input which I have specified as 20px
What you need to do is the following:
Create 3 elements, a container, an input and an element for the error.
<div class="input__group">
<input type="text">
<span class="error">Error Message.</span>
</div>
Then define the following CSS:
.input__group {
position: relative;
display: inline-block;
margin-top: 50px; /* Since the error position is absolute, you will need
to add some space, in this demo we are using a margin.*/
}
.error {
position: absolute;
bottom: 100%; /* Used to place the element to
the top by the total container's height (100%) */
left: 100%; /* Used to place the element to
the right by the total container's width (100%) */
}
.input__group {
position: relative;
display: inline-block;
margin-top: 50px;
}
.error {
position: absolute;
bottom: 100%;
left: 100%;
color: whitesmoke;
background-color: coral;
}
<div class="input__group">
<input type="text">
<span class="error">Error Message.</span>
</div>
Something like the below could be helpful.
Idea is to have a absolute positioned element inside a relative and then to adjust the position based on top (as per your question). It can be done without even using external library.
Sample to play around with:
$(document).ready(function() {
$("#validate").click(function(e) {
$(".inputForm").find(".inputFormMessage").show();
});
});
.inputForm {
position: relative;
}
.inputFormMessage {
display: none;
position: absolute;
top: -10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="inputForm">
<label for="txtBox">Enter Input:</label>
<input type="text" id="txtBox" />
<span class="inputFormMessage">Input is not valid!</span>
</div>
<div>
<input type="button" id="validate" value="Validate" />
</div>
</div>
Another snippet to play around with (positioning is controlled by Styles and rendering upon action)
window.onload = function() {
// Attach handler to `validate` button
document.querySelector("#validate").onclick = function(e) {
var isValid = false;
var elementToCheck = null;
// Disable if any `message` elements are active
Object.values(document.querySelectorAll(".inputFormRowMessage")).forEach(function(element, index, array) {
element.style.display = "none";
});
// Validate First name
elementToCheck = document.querySelector("#txtBoxFirstName");
isValid = elementToCheck.value.length > 0;
if (!isValid) {
// Show the error message
document.querySelector(".inputFormRowMessageFirstName").style.display = "inline-block";
}
// Validate Last name
elementToCheck = document.querySelector("#txtBoxLasttName");
isValid = elementToCheck.value.length > 0;
if (!isValid) {
// Show the error message
document.querySelector(".inputFormRowMessageLasttName").style.display = "inline-block";
}
// .. do other validations and stylings...
// ...
};
};
.inputForm {
font-family: "Trebuchet MS", Verdana, Tahoma;
font-size: 12px;
}
.inputFormRow {
position: relative;
padding: 10px;
margin: 10px;
}
.inputFormRow > label {
width: 100px;
display: block;
float: left;
}
.inputFormRowMessage {
display: none;
position: absolute;
top: -10px;
padding: 2px;
color: red;
}
<div>
<div class="inputForm">
<div class="inputFormRow">
<label for="txtBoxFirstName">First Name:</label>
<input type="text" id="txtBoxFirstName" />
<span class="inputFormRowMessage inputFormRowMessageFirstName">Please enter First Name.</span>
</div>
<div class="inputFormRow">
<label for="txtBoxLasttName">Last Name:</label>
<input type="text" id="txtBoxLasttName" />
<span class="inputFormRowMessage inputFormRowMessageLasttName">Please enter Last Name.</span>
</div>
<div class="inputFormRow">
<label for="txtBoxAge">Age:</label>
<input type="text" id="txtBoxAge" />
<span class="inputFormRowMessage">Not a valid age format.</span>
</div>
<div>
<input type="button" id="validate" value="Validate" />
</div>
</div>

Creating a tag box

I'm making a tag box similar to that of StackOverflow. I see that this question has already been asked here (How to make a "tags box" using jQuery (with text input field + tags separated by comma)) but I'm having a question with regards to the Javascript.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tag-container' id = "tag-container">
<span class='dashfolio-tag'>Tag1</span>
<span class='dashfolio-tag'>Tag2</span>
<span class='dashfolio-tag'>Tag3</span>
</div>
<input type="text" value="" placeholder="Add a tag" id = "add-tag-input" />
CSS:
.tag-container {
max-width: 300px; /* helps wrap the tags in a specific width */
}
.dashfolio-tag {
cursor:pointer;
background-color: blue;
padding: 5px 10px 5px 10px;
display: inline-block;
margin-top: 3px; /*incase tags go in next line, will space */
color:#fff;
background:#789;
padding-right: 20px; /* adds space inside the tags for the 'x' button */
}
.dashfolio-tag:hover{
opacity:0.7;
}
.dashfolio-tag:after {
position:absolute;
content:"×";
padding:2px 2px;
margin-left:2px;
font-size:11px;
}
#add-tag-input {
background:#eee;
border:0;
margin:6px 6px 6px 0px ; /* t r b l */
padding:5px;
width:auto;
}
JS:
$(document).ready(function(){
$(function(){
$("#add-tag-input").on({
focusout : function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
this.value = "";
},
keyup : function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('.tag-container').on('click', 'span', function() {
if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
});
});
});
My question is pretty simple, how do I add the new input as a span with class dashfolio-tag inside the #tag-container? I dabbled with the insertBefore property trying to add it to the right node, but to no avail. Thanks in advance guys!
Change this line of code,
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
to
if(txt) {
$("<span/>", {
text:txt.toLowerCase(),
appendTo:"#tag-container",
class:"dashfolio-tag"
});
}
See the demo: https://jsfiddle.net/2gvdsvos/4/
To fix the margins in between tags,
Update HTML to,
<div>
<div class="tag-container" id="tag-container">
<span class='dashfolio-tag'>tag1</span>
<span class='dashfolio-tag'>tag2</span>
<span class='dashfolio-tag'>tag3</span>
</div>
</div>
<div>
<input type="text" value="" placeholder="Add a tag" id="add-tag-input" />
</div>
And add this to CSS,
.tag-container:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.dashfolio-tag {
...
margin-right: 4px;
float: left;
}
Hope this helps! ;)
https://jsfiddle.net/2gvdsvos/5/

Use percentage instead of px as value for script [duplicate]

Is it possible to set the height/width of an element in percent using JavaScript or jQuery?
document.getElementById('header').style.width = '50%';
If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.
jQuery way -
$("#id").width('30%');
I always do it like this:
$("#id").css("width", "50%");
The question is what do you want the div's height/width to be a percent of?
By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.
So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:
obj.style.width = '50%';
Yes, it is:
<div id="myid">Some Content........</div>
document.getElementById('myid').style.width = '50%';
Also you can use .prop() and it should be better because
Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.
$(elem).prop('width', '100%');
$(elem).prop('height', '100%');
testjs2
$(document).ready(function() {
$("#form1").validate({
rules: {
name: "required", //simple rule, converted to {required:true}
email: { //compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
function()
{
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)
location="http://www.yahoo.com"
else
location="http://www.hotmail.com"
}
function changeWidth(){
var e1 = document.getElementById("e1");
e1.style.width = 400;
}
</script>
<style type="text/css">
* { font-family: Verdana; font-size: 11px; line-height: 14px; }
.submit { margin-left: 125px; margin-top: 10px;}
.label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; }
.form-row { padding: 5px 0; clear: both; width: 700px; }
.label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; }
.input[type=text], textarea { width: 250px; float: left; }
.textarea { height: 50px; }
</style>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div>
<div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div>
<div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div>
<div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
<input type="button" value="change width" onclick="changeWidth()"/>
<div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</form>
</body>
</html>

Categories

Resources