How do I use a JS variable in document.getElementById().style? [duplicate] - javascript

This question already has answers here:
How to interpolate variables in strings in JavaScript, without concatenation?
(17 answers)
Closed 4 years ago.
I want to make it so when ever I reload the page, the background gets chosen randomly.
function switchBG(urlThing) {
document.getElementById("bg-img").style.display="block";
document.getElementById("bg-img").style.backgroundImage="url(urlThing)";
}
var n = Math.floor((Math.random() * 2) + 1);
if (n == 1) {
switchBG('back1.jpg');
}
else if (n == 2) {
switchBG('back2.jpg')
}
I tried that, but nothing happened.
Edit: This is the div. It's the first thing under the tag.
<div id="bg-img"></div>

I am assuming bg-img is the <img> tag.
this is how you can do it
function switchBG(urlThing) {
document.getElementById("bg-img").style.display="block";
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
document.getElementById("bg-img").src=dir + urlThing;
}

You need to concatenate the variable like this:
document.getElementById("bg-img").style.backgroundImage="url(" + urlThing + ")";

Related

How to increment the end of string using Javascript [duplicate]

This question already has answers here:
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 2 years ago.
So the challenge is to increment a string and the exact rules are as follows:
If the string already ends with a number, the number should be
incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
I've gotten so close with two different attempts. Both check off certain boxes but neither do both.
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/[1-9]/g,'') + num;
} else {
return strng + "1";
}
}
This returns the string, keeping the zeros ahead of the incremented number. However on a test like "foobar099" I need to return "foobar100" but get "foobar0100".
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/\d/g,'') + num;
} else {
return strng + "1";
}
}
This is another close attempt that successfully increments tests like "foobar099" -> "foobar100" but abandons the zeros for tests such as "foobar0042" which becomes "foobar43".
Anyone able to solve this?
Is this what you want?
function incrementString(text) {
return text.replace(/(\d*)$/, (_, t) => (+t + 1).toString().padStart(t.length, 0));
}
console.log(incrementString('foo'));
console.log(incrementString('foobar23'));
console.log(incrementString('foo0042'));
console.log(incrementString('foo9'));
console.log(incrementString('foo099'));

How to make alert() come after .innerHTML? [duplicate]

This question already has answers here:
Javascript alert() supersedes preceding code
(4 answers)
Closed 2 years ago.
I currently have some code like this:
function markAlert() {
if (qnsAnsd == 4) {
alert("You got " + mark + "/4! Refresh page if you want to try again.")
};
}
function addEval() {
var addMrknElem = document.getElementById('q__add-mrkn');
qnsAnsdCntr();
document.getElementById('q__add-btn').disabled = true;
if (document.getElementById('q__add-ans').value == addSoln) {
addMrknElem.innerHTML = "Your answer is correct!";
markCntr();
} else {
addMrknElem.innerHTML = "Your answer is incorrect. The correct answer is " + addSoln + ".";
}
markAlert();
};
Basically title... I want the alert in markAlert() to pop up after the the .innerHTML takes effect.
just wrap your alert() method in the setTimeout See the example below.
setTimeout(() => {
markAlert()
}, 1000);
Here, 1000 means 1 second so this markAlert() will be invoked after 1 second. you can change this value to 500 means half a second too.

Randomize an html tag with JavaScript [duplicate]

This question already has answers here:
JavaScript getElementByName doesn't work
(4 answers)
Closed 6 years ago.
I wanted to use Google Chrome's feature called theme-color. The normal syntax looks like this:
<meta name="theme-color" content="#c12432">
However i want to use 3 different colors so I came up with this code. It's worth metioning that I don't have experience with JavaScript so please tell me what's wrong with the code. What i want to do is that it ramdomly chooses a number and with that number it changes the content="value" with the ones specified below.
function colorchanger() {
var x = Math.floor((Math.random() * 3) + 1);
if (x >= 3) {
document.getElementByName("theme-color").content = "#c12432";
}
if (x = 2) {
document.getElementByName("theme-color").content = "#338fc4";
}
if (x = 1) {
document.getElementByName("theme-color").content = "#d99e33";
}
}
Not what you asked for but if you have access to PHP then you can use as an alternative:
<?php
randomTheme() {
$themeColor[] = "#c12432"; // Color Name I.E. Red
$themeColor[] = "#338fc4"; // Color Name I.E. Blue
$themeColor[] = "#d99e33"; // Color Name I.E. Yellow
$randomThemeColor = array_rand($themeColor);
return $themeColor[$randomThemeColor];
}
?>
And then in your meta tag: <meta name="theme-color" content="<?php echo randomTheme(); ?>">
You can also make the function like so, but I prefer the longer version so you can note what hex colors are what by a name beside them. This solution is good for a few colors, but the first solution is good for a big list.
<?php
randomTheme() {
$themeColor = array("#c12432","#338fc4","#d99e33");
$randomThemeColor = array_rand($themeColor);
return $themeColor[$randomThemeColor];
}
?>
So first you can combine your if statements to save on run time like so:
if (x >= 3) {
document.getElementByName("theme-color").content = "#c12432";
}
else if (x == 2) {
document.getElementByName("theme-color").content = "#338fc4";
}
else if (x == 1) {
document.getElementByName("theme-color").content = "#d99e33";
}
Also, if you noticed I changed x = 2 and x = 3 to x == 2 and x == 3 because one equal sign is an assignment while the double equal is the comparison operator. Therefore when you think you're checking if x = 2 you are actually setting x to 2.
Also take consideration to what is being added in the comments, these are just obvious JavaScript errors.

for loop with chars java script [duplicate]

This question already has answers here:
How can I display letters using html table cells as colored pixels?
(2 answers)
Closed 7 years ago.
Quick question. I am trying to give out numbers with a for loop in JavaScript.
Unfortunately this is not working, if I would code in java then the solution would be replace var with char and cosole.log with println and got it, but hereā€¦ do you have a solution for that ?
for ( var i = 'a'; i < 'z'; i++) {
console.log(i);
}
for (var i = 'a'; i !== nextChar('z'); i = nextChar(i)) {
console.log(i);
}
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}

positive integer value using jquery/javascript [duplicate]

This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 9 years ago.
I am using following js function in my asp.net MVC application on click of Ok button to make sure that value entered in the text box is integer but it always returns false;
function isInteger(n) {
return n === +n && n === (n | 0);
}
and here is how I am using it:
if (!isInteger(selectedPhoneValue)) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
Please suggest me how to change this function to allow only positive integer/numberic value without "." and "-"
You can use regular Expresion instead
function isInteger(n) {
return /^[0-9]+$/.test(n);
}
function isInteger(n) {
return $.isNumeric(n) && parseInt(n, 10) > 0;
}
Update:
Then change the if check like so:
//Assuming selectedPhoneValue is not already converted to a number.
//Assuming you want an exact length of 10 for your phone number.
if (isInteger(selectedPhoneValue) && selectedPhoneValue.length == 10) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
You can use this code to strip out the "." and "-" characters.
selectedPhoneValue = selectedPhoneValue.replace(/-/g, "").replace(/\./g, "");

Categories