I want a button that every time you click it it gives you a different answer(Animals, Movies or TV Shows, and so on), the thing is I have a button (that I found online, I'm new at coding) but that button gives me the answer in a little alert box, is there a way to make it give me the answer below the button? Here's the code I found:
var words = ['Animals', 'Movies', 'TV Shows'];
function randomAlert() {
var alertIndex;
var randomValue = Math.random();
if (randomValue < 0.5) {
alertIndex = 0;
}
else if(randomValue < 0.8) {
alertIndex = 1;
}
else {
alertIndex = 2;
}
alert(words[alertIndex]).innerHTML
}
You can just get rid of the alert call and insert it into a div, span, h1, whatever. Here's an example out of the many ways:
var words = ['Animals', 'Movies', 'TV Shows'];
function randomSelect() {
var index;
var randomValue = Math.random();
if (randomValue < 0.5) {
index = 0;
}
else if(randomValue < 0.8) {
index = 1;
}
else {
index= 2;
}
document.getElementById('answer').innerText = words[index]; //Get's an element of id 'answer'
}
randomSelect(); //Executes function
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="answer">
<!-- Answer is inserted into here !-->
</div>
</body>
</html>
The above get's an element of id answer and inserts it into the element's text. This is done by accessing the innerText attribute of the element, which returns the text of the element. I then reassign the value to the index. This is quite a simple way of doing it, and I cleaned up some of the names of functions, variables.
Related
I have multiple lines of text that print in typewriter animation, but when I refresh my browser the different lines of texts get mixed up.
Something like this "****eI icsr eAahtmeedr .t hWiesl cWoembes ittoe muys iWnegb sHiTtMeL,. CSS, and JS.**"
Click around Run snippet 5 or 6 times and including the code buttons, and you will see it see the problem.
The intro is a automatic animation when you first land the page which reads "Hello! My name is Frank. Welcome to my Website."
Tell Me More button prints out "I created this Website using HTML, CSS, and JS."
Nice! button prints out "This website is to showcase my skills."
Ok prints out "You should hire me. Scroll down to see why."
This is just a template. I am actually very new to Java and getting familiar with CSS and HTML. I am creating a portfolio and also learning to code, so bear with me.
I am basically trying to copy this website here https://www.amysboyd.com
I would like the buttons to disappear like in the website, but I don't know how to do that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio</title>
<link rel="stylesheet" href="Portfolio Styles.css" </head>
<body>
<div class="abouttextsection">
<h1 id='output'></h1>
<script>
var a = 0;
var introtxt = 'Hello! My name is Frank. Welcome to my Website.';
var speed = 50;
function aboutintro() {
if (a < introtxt.length) {
document.getElementById("output").innerHTML += introtxt.charAt(a);
a++;
setTimeout(aboutintro, 50);
}
}
window.onload = aboutintro;
var doc, bod, I, TypeMaker; // for use on other loads
addEventListener('load', function() {
doc = document;
bod = doc.body;
I = function(id) {
return doc.getElementById(id);
}
TypeMaker = function(element, interval) {
this.element = element;
this.interval = interval || 50;
var t = this,
r;
this.type = function(string) {
if (r) clearInterval(r);
var s = string.split(''),
l = s.length,
i = 0;
var p = 'value' in this.element ? 'value' : 'innerHTML';
this.element[p] = '';
r = setInterval(function() {
t.element[p] += s[i++];
if (i === l) {
clearInterval(r);
r = undefined;
}
}, t.interval);
}
}
var typer = new TypeMaker(I('output')),
First_test = I('First_test'),
Second_test = I('Second_test'),
Third_test = I('Third_test');
var testArray = [''];
var testArrayL = testArray.length;
First_test.onclick = function() {
typer.type('I created this Website using HTML, CSS, and JS.');
}
Second_test.onclick = function() {
typer.type('This website is to showcase my skills.');
}
Third_test.onclick = function() {
typer.type('You should hire me. Scroll down to see why.');
}
});
</script>
<div class="aboutsectionbutton">
<button id='First_test' type='button' value='Tell Me More' />Tell Me More</button>
<button id='Second_test' type='button' value='Nice!' />Nice!</button>
<button id='Third_test'>Ok</button>
</div>
</div>
</body>
</html>
Add fadeOut transition to css class ->
CSS:
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s .25s, opacity .25s linear;
}
And on click event just add this class ->
JS:
Second_test.onclick = function() {
this.classList.add('hidden')
typer.type('This website is to showcase my skills.');
}
jsfiddle
The purpose of my website is to find a hex color code by hitting a button, while the website's background is randomly changed by itself. However, when the button is clicked, the printed color code does not match with the current background color. how can I fix this?
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
document.body.style.backgroundColor = getRandomColor();
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").innerHTML = getRandomColor(); // printed code does not match with bg
}
<html lang="en">
<head>
<meta charset="UTF-8">
<!--<meta http-equiv="X-UA-Compatible" content="IE=edge">-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>What color is it</title>
</head>
<body>
<h1>What color is it ...</h1>
<h2 id="hexcode"></h2>
<div id="center">
<input type="button" onclick="stopColor()" class="button" value="Find A Color Code For Me">
</div> <!-- onclick stop loop -->
</body>
</html>
Why are you generating another random color to show? You're literally never getting the color you've set.
You should have retrieved it from the style attribute (or store it somewhere).
document.getElementById("hexcode").innerHTML = document.body.style.backgroundColor;
This at least shows something like rgb(123, 45, 67) that matches the background color. You may need some extra work if you want the #rrggbb format.
You are calling getRandomColor twice: once for the background and once for the hex code display. They won't match. Instead, use a variable and set it to the result of the function
let randomColor;
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
randomColor = getRandomColor();
document.body.style.backgroundColor = randomColor;
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").innerHTML = randomColor;
}
Your code in the stopColor function invokes the getRandomColor function, which generates a new random color, rather than using the one that was present when the button was clicked.
You can solve this by adding a new variable that always has the current color in it and referencing that variable in the stopColor function. (You could also just access the current document background color, but storing it in a variable is a bit more scalable.)
Also (FYI), don't use .innerHTML if you can avoid it (which is almost always) because it has security and performance implications to it. Since you aren't reading or writing HTML anyway, use .textContent.
let currentColor = null; // Will always hold the current color
const infiniteColorChange = setInterval(() => {
setColor()
}, 5000);
function setColor() {
currentColor = getRandomColor(); // Store the color for use elsewhere
document.body.style.backgroundColor = currentColor;
}
function getRandomColor() {
for(let y = 0; y < 16777215; y++) {
const randomNumber = Math.floor(Math.random()*16777215);
return "#" + randomNumber.toString(16);
}
}
function stopColor() {
clearInterval(infiniteColorChange);
document.getElementById("hexcode").textContent = currentColor; // Access current color
}
<html lang="en">
<head>
<meta charset="UTF-8">
<!--<meta http-equiv="X-UA-Compatible" content="IE=edge">-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>What color is it</title>
</head>
<body>
<h1>What color is it ...</h1>
<h2 id="hexcode"></h2>
<div id="center">
<input type="button" onclick="stopColor()" class="button" value="Find A Color Code For Me">
</div> <!-- onclick stop loop -->
</body>
</html>
I’m trying to track the clicks on a button on my website. I’ve tried adding the following but to no success. I’m a noob to JS..
function trackButton(e) {
onPage.innerHTML = ++i;
}
var i = 0;
var onPage = document.getElementById(‘track’);
var clickCount = document.getElementById(‘bttn’);
clickCount.addEventListener('click', function (e) {
addOne(e);
}, false);
You did some mistake:
The function addOne doesn't exist, it's trackbutton
it's i++ to increment a value, not ++i
And some tips for you:
Use let and const (ES6) for the variable, not var
And the e for the event is useless here, you are not using it, so it's not mandatory here
Do these change and it must work !
UPDATE:
To increment a value ++i works, see the documentation
Change the quotes ‘‘ with " " or ' '.
Like so: document.getElementById(‘track‘) to document.getElementById('track')
I was checkin your code and its almost all right, i think that the problem its in your addOne function, here is a way to resolve the problem.
i creat the button and paragraph elements in html and in javascript a variable n where we are going to storage the clicks tha the user did and we increment n when the function its called in the button's event
var n = 0;
var button = document.getElementById('track');
button.addEventListener('click', trakeo);
var texto = document.getElementById('number');
function trakeo(){
n++
texto.innerHTML = n;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A Great Demo on CodePen</title>
</head>
<body>
<button id="track">Button</button>
<p id="number"></p>
</body>
</html>
Try to use
addEventListener('click',)
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
I'm making a simple program that cuts the circle evenly.
enter image description here
and I want to put it image using 'setAttribute' method.
but, It doesn't work as i thought.
here is my code.
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0; padding:0;}
</style>
<script>
function elt(name, attributes){
var node = document.createElement(name);
if( attributes ){
for(var attr in attributes){
if(attributes.hasOwnProperty(attr)){
node.setAttribute(attr,attributes[attr]);
}
}
}
for(var i=2; i<arguments.length; i++){
var child = arguments[i];
if( typeof child == "string" ){
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
window.onload=()=>{
const IMG_W_COUNT = 50;
const IMG_H_COUNT = 33;
const IMG_SUM = 1650;
for(var i=1,j=0;i<=IMG_SUM;i++,j+=18){
var ImageSaver = elt("div",{
class:"menu item"+i,
width:18+"px",
height:18+"px",
background:"url('paint.jpg')",
backgroundPosition:0+"px"+" "+j+"px"
});
document.body.appendChild(ImageSaver);
}
}
</script>
</head>
<body>
</body>
</html>
The elt function is a function that helps to easily generate an element.
I'd really appreciate your help.
background, height and width aren't attributes (except on a few elements, and there they are mostly deprecated), nor is backgroundPosition.
To set a CSS property value with a function use setProperty on a style declaration.
Make sure you use the CSS property name, which is background-position not backgroundPosition.
element.style.setProperty("name", "value");
You have to set CSS properties.
element.style.width=18+"px";
element.style.height=18+"px";
element.style.background="url('paint.jpg')";
element.style.backgroundPosition="top right";
I could need some help, or maybe just an answer. Is there a way to show changes made by aa js within an executing for loop ? I know there is a way with setInterval, but I have an example with a greater progress where I need it to progress the problem with a for loop. So here is my try:
<!doctype html>
<html>
<head>
<title>life change test</title>
<meta charset="UTF-8">
</head>
<body>
<div id="wrapper">
</div>
<script type="text/javascript">
var el = document.getElementById("wrapper");
/*var i = 0;
var counter = setInterval(function(){
el.innerHTML = i;
i++;
if(i == 18000){
clearInterval(counter);
}
}, 10);*/
for (var i = 400000; i >= 0; i--) {
el.innerHTML = i;
};
</script>
</body>
</html>
My Firefox just freezes until it is completely done, and than displays the result. Is there a chance to actually see the progress ?