How to select elements to apply a transformation(rotation, etc) to? - javascript

I am trying to rotate or transform all elements inside a div but I currently have this function. It rotates all elements on the page. How can I select a div or a class to rotate instead?Array.from(document.all).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")

You need to use document.getElementsByClassName() or document.getElementsByTagName():
var selected = document.getElementsByClassName('myClass');
Array.from(selected).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")

function randomRotate(selector) {
var elem = document.querySelector(selector);
if (!elem) return;
elem.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
}
randomRotate('.someClass');
Basically it doest the same as your code, but instead of taking all elements it looks for particular via selector. If there are multiple elements with such class it will apply rotation only for first of them.
So if you want to apply rotation to all objects with that class, you should use a bit another function:
function randomRotate(selector) {
var elems = document.querySelectorAll(selector);
if (elems.length === 0) return;
elems.forEach(function(el){
el.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
})
}
randomRotate('.someClass')

Related

How to make a list of numbers that perfectly divide with 6000 or the most approach to 6000

I need to Make an program that calculate the perfect way of cut bars of 6000milimeters to Make indoor doors and Windows and i need to waste less I can everytime I cut there ia 2 mm that is wasted because of blade. So for example i Have this inputs: 2x1450 2x1600 3x1004 And neeed to show me how can i sort to give me perfect 6000 or the most aproach for example cut 1600+2x1450 And the next one cut 1600+3x1004 with 2 mm cut error at every input.So IT s like sort every inputs in grids of 6000mm.
function bign(){
var bignumber;
var nr1;
var nr2;
var nr3;
var bara = 6000;
var nrbuc1;
var nrbuc2;
var nrbuc3;
var bucx1;
var bucx2;
var bucx3;
nr1=parseInt(document.getElementById("no1").value)
nrbuc1=parseInt(document.getElementById("buc1").value);
nr2=parseInt(document.getElementById("no2").value);
nrbuc2=parseInt(document.getElementById("buc2").value)
nr3=parseInt(document.getElementById("no3").value);
nrbuc3=parseInt(document.getElementById("buc3").value)
bucx1=nr1 * nrbuc1;
bucx2=nr2 * nrbuc2;
bucx3=nr3 * nrbuc3; '
var total1 = bucx1+bucx2;
var total2 = bucx2+bucx3;
var total3 = bucx1+bucx2+bucx3;
var rezultat1= document.getElementById("VERIFICAT").innerHTML = nr1 + " plus " + nr2 + " result";
var rezultat2= document.getElementById("VERIFICAT").innerHTML = nr2 + " plus " + nr3 + " rusult";
var rezultat3= document.getElementById("VERIFICAT").innerHTML = nr1 + " plus " + nr2 + " plus" + nr3;
var gresit = document.getElementById("VERIFICAT").innerHTML = "GRESIT";
if (total1 % bara == 0){
alert (rezultat1);
}
if (total2 % bara == 0){
alert (rezultat2);
}
if (total3 % bara == 0){
alert (rezultat3);
}
else (total1%bara != 0 || total2%bara != 0 || total3%bara !=0 )
alert(gresit);
}
Details are commented in example
/**
* Given a constant width and one or more smaller
* widths, find how many of the smaller widths can
* be combined to get as close as possible to the
* constant width (but not exceed it)
* #param {number} sheet - The width limit that
* cannot be exceeded
* #param {rest<string>} ...points - The points to
* to cut widths to.
*/
class Chop {
constructor(sheet, ...points) {
this.sheet = sheet;
this.points = [...points];
}
/**
* A utility method that formats text
* #param {any} data - Any input a JSON can handle
* #param {boolean} noConsole - Determine whether
* data is to display in console or
* returned. #default is false
* #return {any} any output a JSON can handle
*/
static log(data, noConsole = false) {
if (noConsole) {
return JSON.stringify(data).trim();
}
console.log(JSON.stringify(data));
}
/**
* Given an array of number-strings, convert them
* into a simple format. Each formatted number is
* a width to be "cut"
* # return {array} - An array of numbers used to
* cut the widths
*/
mark() {
this.points = this.points.flatMap(str => {
/**
* If a string has a space...
* ...split the string at every space
*/
if (str.includes(' ')) {
let y = str.split(' ');
y[0] = +y[0] + 2;
y[1] = +y[1] + 2;
return y;
}
/**
* If a string has a "x"...
* ...split string at every "x"...
* ...each number to the left of "x" determines...
* ...how many times the number on the right of "x" is
* repeated
*/
if (str.includes('x')) {
let x = str.split('x');
x.splice(-1, 1, ' ' + (+x[1] + 2));
return x[1]
.repeat(x[0])
.split(' ')
.map(n => +n);
}
return (parseInt(str) + 2);
});
let order = this.points.sort((a, b) => a - b);
Chop.log(order);
return order;
}
/**
* Separates the numbers that fit within the limit
* and those that don't.
* #return {array<array>} - An array of arrays
*/
cut() {
let sum = 0, cutoff, index;
for (const [idx, num] of this.points.entries()) {
if (num + sum > this.sheet) {
cutoff = `Cutoff is ${num}mm at index: ${idx}`;
index = idx;
break;
} else {
sum = num + sum;
}
}
let done = this.points.slice(0, index);
let notDone = this.points.slice(index);
Chop.log(
`Sum of cut sections: ${sum}mm
${cutoff}`);
return [done, notDone];
}
}
let z = new Chop(6000, '2x1140', '1000', '3x500', '3000 5000');
Chop.log(z.mark());
Chop.log(z.cut());

Unexpected token 'this' (javascript)

I'm new to coding, and this is my first post. Any help you can offer is greatly appreciated. I'm trying to create a level calculation system that you might see in an RPG for a character with different stats. When I run the program at different values, I get the following message:
Unexpected token 'this'
I have put the section of code where the error message occurs in stars.
const Sean = {
fullName: `Sean`,
attack: 1,
strength: 1,
defense: 38,
hitpoints: 40,
prayer: 15,
range: 98,
magic: 99,
calcCombatLevel: function () {
this.Meleelvl = .25 * (this.defense + this.hitpoints + Math.floor((this.prayer / 2))) + ((13 / 40) * (this.attack + this.strength));
this.magiclvl = .25 * (this.defense + this.hitpoints + Math.floor((this.prayer / 2))) + ((13 / 40) * (this.magic * (3 / 2)));
this.rangelvl = 0.25 * (this.defense + this.hitpoints + Math.floor((this.prayer / 2))) + ((13 / 40) * (this.range * (3 / 2)));
if ((this.attack + this.strength) > ((2 / 3) * this.magic) && (this.attack + this.strength) > ((2 / 3) * this.range)) {
return this.meleelvl;
}
// **********************************
else if ((2 / 3) this.magic > (this.attack + this.strength) && (this.magic >** this.range)) {
return this.magiclvl;
}
else if((2 / 3) * this.range > (this.attack + this.strength) && (this.range > this.magic)) {
return this.rangelvl;
}
}
}
Sean.calcCombatLevel();
console.log(Math.floor(Sean.lvl));
The first elseif has:
(this.magic >** this.range)
// also missing * at start, has (2/3) magic, where the 'this' error is from
which I assume you meant to be:
else if ((2 / 3) * this.magic > (this.attack + this.strength) && (this.magic > this.range)) {
Didn't play with the code but that's the only first obvious thing that stands out to me.
Also as someone commented above Sean.lvl doesn't seem to be defined, so the output at end probably isn't working either. You could do something like the following instead (or define a field named lvl):
var mylvl = Math.floor(Sean.calcCombatLevel());
console.log(mylvl);
And at least in one place your variable names have inconsistent casing, this.Meleelvl and this.meleelvl, fix that too (first line in function should have this.meleelvl, keeping all variable names lowercase).

Adding numbers instead of adding increment

I have a small script that increments the number by the number in a given time period. If incrementing by one value++ works, if I want to add another value of the type generated by the math.random function instead of adding, add to the existing value. How can I change this? I want the generated number to add to an existing value in innerHTML.
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML += Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
You append numbers to a string. Convert your innerHTML to a number with parseInt and it'll work as you expecting.
document.getElementById("data-gen").innerText = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
// parseInt( yourString, radix )
const num = parseInt( document.getElementById("data-gen").innerText, 10 );
document.getElementById("data-gen").innerText = num + Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
But one downside is, that you are querying the DOM each time you want to change it. It's better to store your number outside of your timeout and use an interval like this:
let num = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
document.getElementById("data-gen").innerText = num;
nowResources = function() {
num += Math.floor((Math.random() * 10) + 1);
document.getElementById("data-gen").innerText = num;
}
setInterval( nowResources, 1000 );
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
This way you don't need to parse your number with each iteration.
When you use + it takes as string and concatenate as a string, convert it to an integer using parseInt
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
DEMO
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1)+ Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
To keep the logic clear, just use a local variable to store the value, no need to backward converting via parseInt and weary (and expensive, and messy) DOM element methods dancing:
var value = 0;
function setValue(addValue) {
value += addValue;
document.getElementById("data-gen").innerHTML = value;
}
nowResources = function() {
setValue(Math.floor((Math.random() * 10) + 1))
setTimeout(nowResources, 1000);
}
nowResources();

Change CSS with Javascript but using Variables

I know this:
document.getElemntById('object').style.height='50px';
But instead of '50' (string), I want to use another variable (for Example number).
I wanted to do this because I want random numbers.
Any easy way to do it?
Simple
var foobar = 25;
document.getElementById('object').style.height=foobar + 'px';
This is how you would do it with a random number between 1 and 100. Read more about Random
var RandomNumber = Math.floor((Math.random() * 100) + 1).toString();
document.getElementById('object').style.height=RandomNumber + 'px';
You can use a variable anywhere you can use a string literal.
var foo = "50px";
document.getElementById('object').style.height = foo;
You can generate random number like this and set the height. In the below example maxHeight is exclusive.
var minHeight = 10;
var maxHeight = 20;
var randomHeight = Math.floor((Math.random() * (maxHeight - minHeight)) + minHeight);
document.getElemntById('object').style.height = randomHeight + 'px';
Use Math.random() * 300 to get a random from 1-300 float number, then parseInt to get a integer.
int + string will get you string in JS so no need to convert, just use randompx + 'px'
var randompx = parseInt(Math.random() * 300) + 1;
//document.getElementById('object').style.height=randompx + 'px';
console.log(randompx+'px');
Try this
document.getElemntById('object').style.height= randomNumber + 'px';

Jquery progressbar random image width

I really don't know what im doing wrong. I want to change the width of the image to a random number from 0 - 100%. Can someone tell me what i'm doing wrong?
function progress(){
$("body").append("<div class='main_div'></div>");
var x = Math.floor(Math.random() * 10) + 1;
var x = 5;
for(var i = 0; i < x; i++){
$(".main_div").append("<div class='statusbar'></div>");
$(".statusbar:nth-child(" + x + ")").append("<img src='project_status.gif'>");
var c = Math.floor(Math.random() * 100) + 1;
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
}
}
There are errors in your Math.floor() function: Instead of
Math.floor(Math.random() * 10) + 1;
It should be
Math.floor((Math.random() * 10) + 1));
with the +1 within the Math.floor brackets.
I don't know if it would be helpful or not, but I have previously produced a random-size progress bar here: http://jsfiddle.net/cu22W/10/
The issue is with this statement:
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
You should read up on JQuery .css() function : http://api.jquery.com/css/
But when you use the .css() function with { } brackets the syntax is the same as CSS itself.
So for your statement the proper way would be :
.css({ width : c +"%" })
or, if you wanted to keep it the way you have it just remove the { } brackets :
.css( "width", c +"%")
I am also pretty sure you don't need to wrap c in ()

Categories