I am trying to make this code to generate a random number of 10 images, so every time I click the button I will get a random number of images and I just want this 1 image and the button doesn't disappear so I can try again.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = "Myimage.jpg";
var rnd = Math.floor( Math.random() * 10 );
document.write(myImages1[rnd]);
}
</script>
</body>
</html>
myImages1 is a string an not an array. And you need to multiple the random() by the number of elements in the array.
function randomImg1() {
var myImages1 = ['Myimage.jpg'];
var rnd = Math.floor(Math.random() * myImages1.length );
document.write(myImages1[rnd]);
}
You'll need to update the content dynamically, not using document.write. In addition, myImages1 must be an array.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = new Array();
myImages1[0] = "Myimage.jpg";
myImages1[1] = "Myimage1.jpg";
var rnd = Math.floor( Math.random() * myImages1.length ); //incorporated other solution
document.getElementById("image").innerHTML = "<img src='" + myImages1[rnd] + "' alt='image'></img>";
}
</script>
<div id="image"></div>
</body>
</html>
Related
So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>
I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
<script>
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementsByClassName('boxed').innerHTML = numList;
</script>
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div class="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>
your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div>
When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
console.log(numList)
};
numList.toString();
document.getElementById('boxed').innerHTML = numList;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>
I'm trying to create a button to go on the first history page but I don't know why doesn't my code work.This is my code:
function firstpg() {
var startpt = '-' + window.history.length;
window.history.go(startpt);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="firstpg()">Go First</button>
</body>
</html>
What is the problem?
The history also includes current page so you need to decrement 1 from the length in order go to the first page.
var startpt = '-' + ( window.history.length - 1) ;
or
var startpt = -(window.history.length - 1) ;
You need to negate the length as it is not 0 based. So try:
var startpt = ( window.history.length - 1) * -1;
This should work:
<!DOCTYPE html>
<html>
<head>
<script>
function firstpg() {
var startpt = ( window.history.length - 1) * -1;
window.history.go(startpt);
}
</script>
</head>
<body>
<button onclick="firstpg()">Go First</button>
</body>
</html>
I am new to javascript and I'm trying to pass image from database into javascript, but I can not.
The problem code is :
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
and this is my code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="box">
<img id="image" />
</div>
<?php
$query = $this->db->get('product');
foreach($query->result() as $val):
?>
<script>
var images =
'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
</script>
<?php endforeach; ?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Javascript random image</title>
<?php
/* Query the db */
$query = $this->db->get('product');
/* use php to generate the javascript array of images from db query */
echo "
<script type='text/javascript'>
var images=[];
var baseurl='".base_url()."';
var path='./images/burger/';";
foreach( $query->result() as $val ){
/* Add image to javascript array */
echo "images.push('{$val->image}');\n";
}
echo "
</script>";
?>
<script type='text/javascript'>
function rnd_index(a,b) {
return Math.round( a + ( Math.random() * ( b - a ) ) );
}
function randImg() {
var x = rnd_index( 0, images.length-1 );
document.getElementById('image').src = baseurl + path + images[ x ];
}
function orig__randImg() {
var size = images.length;/* This might be too large sometimes for the array */
var x = Math.floor( size * Math.random() );
document.getElementById('image').src = path + images[ x ];
}
/* Load a random image when the page has loaded */
window.onload=randImg;
</script>
</head>
<body>
<div id="box">
<img id="image" />
</div>
</body>
</html>
You need to create an array in javascript and push the image path.
Before <?php foreach(...
<script>
var images = [];
function randImg(images) {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
</script>
Inside the loop..
<script>
images.push("<?php echo base_url().'./images/burger/'.$val->image ?>");
</script>
After loop...
<script>
randImg(images);
</script>
I am trying to make a javascript program that solves the Pythagorean theorem when you give it inputs . But for some reason its not working. Here is the code: `
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
function myFunction() {
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>
First you need to move your gathering of the data inside of the function. Otherwise you will never have a value for the inputs.
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script>
function myFunction() {
//moved two lines below so they are inside the function declaration.
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
</head>
<body>
<strong>A</strong>
<input type="text" id="a"></input> <br>
<strong>B</strong>
<input type="text" id="b"></input><br>
<button onclick="myFunction()">Enter</button>
</body>
</html>
Just replace the script section with the following one:
<script>
function myFunction() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var one = Math.pow(a, 2);
var two = Math.pow(b, 2);
var xone = (one+two);
var c = Math.sqrt(xone);
alert("c="+c);
}
</script>
All you had to do is to move the getElementById lines insied the function :)