Setting font-size with random value using jQuery? - javascript

When returning a fixed value, font-size is changing fine:
$wordElement.css('font-size', function() {
return '3vw';
});
But when trying to return a random value like this:
$wordElement.css('font-size', function() {
return '\'' + Math.ceil((cssRandom * 3) + 1) + 'vw\'';
});
It does not work.
What's wrong here? And how do I set font-size to random value?

Remove unnecessary escape and quotes surrounding Math.ceil call. You can use $.now() .slice() to retrieve a "random" numeric value
var cssRandom = String($.now()).slice(-1);
$("div").css("font-size", function() {
return Math.ceil((cssRandom * 3) + 1) + "vw";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>abc</div>

I don't think cssRandom is javascript.
Try
Math.ceil((Math.random() *3 )+1)

Related

Pure Javascript - Turn number into a %

My program spits out a number between 0 and 1, and I cant change that. I need to turn it into a % to use as a variable for a CSS selector.
<div id="Value">0.50</div>
<script>
var element = document.getElementById("Value");
var percent = element * 100;
</script>
But how am I meant to put a % symbol on the end so I can do this:
document.getElementById("circle").style.marginLeft = percent;
Any help would be appreciated, thank you.
String concatenation:
document.getElementById("circle").style.marginLeft = percent + "%";
Since "%" is a string, percent will get converted to string and then the result will be the percent value followed by "%".
As Federico pointed out, you should be using either .value (if the id="Value" element is a field element [an input, textarea, or select]) or .textContent or .innerHTML (if it's not). In your case, it's a div, so textContent would make sense:
var value = document.getElementById("Value").textContent;
var percent = value * 100; // Implicitly converts `value` to number
document.getElementById("circle").style.marginLeft = percent + "%"; // Implicitly converts `percent` to string
try
circle.style.marginLeft = Value.innerText*100 + '%'
<div id="Value">0.50</div>
<div id="circle">◉<div>
document.getElementById("circle").style.marginLeft = percent + '%';
When used on strings, the + operator is called the concatenation operator.
Reference: Javascript Operators
This should solve it.
document.getElementById("circle").style.marginLeft = percent+"%";
In Javascript you can concat natively an int and a string using the '+' operator which means that -
var a = 5
var b = a + '%'
result is b = '5%'
Use innerHTML to get the text from the element
var element = document.getElementById("Value").innerHTML;
var percent = parseFloat(element)*100;
percent+='%';
console.log(percent)
<div id="Value">0.50</div>

Trying to generate a random integer within a specific range then have it displayed inline

So, here's what I have (I am running JQuery):
http://jsfiddle.net/KDmwn/111/
The computer chose <span id="x"></span>.
$(document).ready(function () {
var x = function getRandomInt(1, 4) {
return Math.floor(Math.random() * (4 - 1 + 1)) + 1
};
$('#x').html(x);
}
I feel like the issue has to do with this $('#x').html(x);
Any help is much appreciated. Thanks!
The issue is because your x function has two integers set as the arguments, which is syntactically incorrect.
To achieve what you need you should remove the integers in the argument list, fix the mis-matched bracket at the end of the DOMReady handler and you can also remove the - 1 + 1 from the Math.random value.
Try this:
var x = function getRandomInt() {
return Math.floor(Math.random() * 4) + 1;
}
$('#x').html(x);
Updated fiddle
Use below code
$('#x').html(Math.floor(Math.random() * 4 ) + 1);
Fiddle

JavaScript Calculation Problem - NaN message

I'm calculating a total number. I get the sum values from div's. But in total, instead of numbers I get (NaN - Not a Number)
JavaScript Function:
<script type="text/javascript">
function calculateTotal(){
var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
document.getElementById('total').innerHTML = total;
}
</script>
EDIT:
I found the error, I had a closing tag inside the DIV's like this:
<center><div id="valor1"></center></div>
Changed to:
<center><div id="valor1"></div></center>
You cannot use document.getElementById('valor1').innerHTML directly. You have to convert this to number. Please try this.
var value = document.getElementById('valor1').innerHTML;
var number = parseFloat(value)||0;
Do this for each div innerHTML which have number.
var number = parseFloat(value)||0;
The above line will help you to assign 0 to value if div is empty or div html cannot be converted to a number.
Use parseFloat(document.getElementById('x').innerHTML) to convert them to numbers before performing operations:
var total = parseFloat(document.getElementById('x1').innerHTML) + parseFloat(document.getElementById('x2').innerHTML);
You also may want to check them if they're numeric, here's a simple test using isNaN:
alert((isNaN("23"))?'not number':'number');
HTML:
<div id="valor1">2</div>
<div id="valor2">2</div>
<div id="valor3">ccccc</div>
<div id="valor4">2</div>
<div id="valor5">2</div>
<div id="valor6">2</div>
<hr/>
<div id="total">0</div>
JavaScript:
function $(id) { return document.getElementById(id); }
function get(elem) { return parseFloat($(elem).innerHTML) || 0; }
(function() {
var total =
get('valor1') * 1 + get('valor2') * 1 + get('valor3') * 1 +
get('valor4') * 1 + get('valor5') * 1 + get('valor6') * 1;
$('total').innerHTML = total;
}());
A little optimization of the work and demo.
But why stop here? :) we can make it even better ( I think ):
function get(elem) {
return (parseFloat($(elem).innerHTML) || (function() {
$(elem).innerHTML += " <i>Not a number assumed 0</i>";
return 0;
}()));
}
And the updated demo.
Edit: no errors on Chrome & Mozilla (Linux).
try using parseInt() as in
var total = parseInt(document.getElementById('valor1').innerHTML)*1 + parseInt(document.getElementById('valor2').innerHTML)*1 + ... ;
etc etc
this will ensure that what you're getting out of the fields is in fact, a number
Did you try to put these parts into brackets?
(document.getElementById('valor1').innerHTML * 1) + ...
See: http://rx4ajax-jscore.com/ecmacore/operator/predence.html
Even better - use the parseInt(var string) function;
parseInt(document.getElementById('valor1').innerHTML) + ...

Change margin value on table with value from a variable with jQuery?

I select some tables using this:
$('.StatusDateTable').each(function() {
var statusLight = $(this).find(".StatusLight").attr("src");
statusLight = statusLight.substring(33).slice(0,-9);
if (statusLight == "Blue") {
var columns = Math.abs((start - end)-1);
var columnWidth = 40;
var marginRight = Math.abs(columnWidth * columns);
Now I want to set margin-right="theValueOfmarginRightHere" on the current table, is this possible?
I tried something like:
$(this).attr('margin-right=" + marginRight + "');
but obviously it doesn't work.
Thanks in advance.
$(this).css('marginRight',marginRight + 'px');
$(this).css({marginRight:marginRight})
Use .css():
$(this).css('margin-right', marginRight);
You might have to add px at the end, not sure about this: marginRight + 'px'.
Comments on your code line:
margin-right is no attribute of an HTML element. It is a CSS property. So you cannot set such properties with the attr() method.
Have a look at attr() which parameters the method expects. It is either:
attr(name) to get the attribute value.
attr(name, value) to set the value. You don't have to create a string like name=value.
When you do string concatenation, you have to be careful with mixing ' and ". Yours would indeed create the string margin-right=" + marginRight + " (as you can see from the syntax highlighter). To concatenate the right way, you have to put single quotes at the right spot:
'margin-right="' + marginRight + '"'
// --^ --^
`

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources