At present I have a very basic Javascript counter-style function:
<body>
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Add One To Chain</button>
<p>Chain: <a id="clicks">0</a></p>
</body>
However now I wish to present the user with different text prompts at different points whilst counting.
For example if the counter reaches 10 I would like it to say hello, and if it reaches 20 it would say something like keep going, and at 30 STOP! and so on.
Any help would be much appreciated!
You could use a switch statement like so:
switch (clicks) {
case 10:
text = 'Hello';
break;
case 20:
text = 'Keep going';
break;
case 30:
text = 'STOP';
break;
default:
text = clicks;
break;
}
document.getElementById("clicks").textContent = text;
This is a dynamic approach. It will alert as many prompts as you fill in the prompts array.
var clicks = 0,
prompts = ['Hello', 'Keep going', 'STOP'];
function onClick()
{
clicks += 1;
var promptKey = clicks / 10 - 1;
if (clicks % 10 == 0 && prompts[promptKey] !== undefined) {
alert(prompts[promptKey]);
}
document.getElementById("clicks").innerHTML = clicks;
};
You can use if else in Javascript for this to work.
Here is working example.
var clicks = 0;
function onClick1() {
clicks += 1;
if (clicks == 10) {
alert("Hello");
} else if (clicks == 20) {
document.getElementById("clicks").style.color = "green";
document.getElementById("clicks").innerHTML = clicks + " Keep Going";
} else if (clicks == 30) {
document.getElementById("clicks").style.color = "red";
document.getElementById("clicks").innerHTML = clicks + "Stop !!";
} else {
document.getElementById("clicks").innerHTML = clicks;
}
}
<button type="button" onClick="onClick1()">Add One To Chain</button>
<p>Chain: <a id="clicks">0</a>
</p>
The easiest way to do it would be like this. I've included comments to help you understand what's up.
<body>
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
var nextClick = clicks + 1; // Get the next click too.
document.getElementById("clicks").innerHTML = clicks;
// Based on what the next click will be,
switch (nextClick) {
case 10:
// Put a message in div#message.
document.getElementById('message').innerHTML = 'hello';
break;
case 30:
document.getElementById('message').innerHTML = 'STAHP';
break;
}
};
</script>
<button type="button" onClick="onClick()">Add One To Chain</button>
<p>Chain: <a id="clicks">0</a></p>
<!-- A container for the message from JS -->
<div id="message"></div>
</body>
Hope that's helpful!
[Edited]:
The following will be more maintable : Steps and messages are stored in an object rather than hardcoded in a switch case loop.
var clicks = 0;
var messages = {"10": "hello", "20": "keep going", "30": "stop"};
function onClick() {
clicks++;
document.getElementById("clicks").innerHTML = (messages.hasOwnProperty(clicks.toString())) ? messages[clicks.toString()] : clicks;
return;
};
see the following fiddle
Related
I want to use a button to display a text with the styles and to revert to the original text when I click the button again. I have done the first part which is to display the text but I cant revert back to the original text. This is what I have so far:
function myFunction() {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
Declaring a a variable let count = 1; outside the function which will help me to check the state i am in currently in.so first i assigned the value of 1 to it.
in my function i am saying is count is equal to 1 change it to Hello Javascript with other properties and change count to zero.so when you click the next time count is now zero and the first if gets rejected instead it goes to the second if else
condition and makes it this is me and changes count to 1 this time.
basically changing the text with count as a statemanagement.
let count = 1;
function myFunction() {
if (count == 1) {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
count = 0;
} else if (count == 0) {
document.getElementById("second").innerHTML = "This is me";
document.getElementById("second").style.fontSize = "16px";
document.getElementById("second").style.color = "black";
count = 1;
}
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
perhaps using sequence style 😉
const sequence = [
['This is me', '20px', 'blue'],
['Hello Javascript', '25px', 'red'],
['stackoverflow', '50px', 'green'],
];
let index = 0;
function myFunction() {
const element = document.getElementById("second");
element.innerText = sequence[index][0];
element.style.fontSize = sequence[index][1];
element.style.color = sequence[index][2];
// increment the index then wrap index to the start when needed
index = (index + 1) % sequence.length;
}
// intialize
myFunction();
One way to do so would be to toggle your styles on the element. The code to do so is given below.
function myFunction() {
document.getElementById("second").classList.toggle("mystyle");
}
.mystyle {
font-size: 25px;
color: red;
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
<!DOCTYPE html>
<html>
<script>
var count = 0;
function myFunction() {
count += 1;
if (count % 2 > 0) {
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
document.getElementById("second").innerText = "Hello Javascript";
} else if (count % 2 == 0) {
document.getElementById("second").style.fontSize = "15px";
document.getElementById("second").style.color = "black";
document.getElementById("second").innerText = "This is me";
}
}
</script>
<body>
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
</body>
</html>
You should store the button style somewhere, and you should store your element reference, interrogating the DOM is performance consuming.
You can get compute styles with window.getComputedStyle(element)
Something like
const buttonRef = document.getElementById("second")
const buttonDefaultStyle = window.getComputedStyle(buttonRef)
const isDefaultStyle = true
let buttonInnerHTML = "text"
function myFunction() {
if (isDefaultStyle) {
buttonRef.innerHTML = "Hello Javascript";
buttonRef.style.fontSize = "25px";
buttonRef.style.color = "red";
isDefaultStyle = false;
} else {
buttonRef.innerHTML = buttonInnerHTML;
buttonRef.style.fontSize = buttonDefaultStyle.fontSize;
buttonRef.style.color = buttonDefaultStyle.color;
isDefaultStyle = true;
}
}
You have to pardon me, as I'm still learning JS, but I thought i'd give it a try as an exercise. There are probably simpler ways to do this, but this is what I came up with.
For a faux 'boolean', if you will, you can go through even and odd numbers with a counter increasing each time you press the button. If left to its own devices, a counter will go to infinity, so adding an if clause (or a case switch, could be either), for the counter if it goes above a certain number will keep it reasonable.
Rather than adding font styles, I think it would be easier to toggle between classes, that way you can just edit the CSS instead of having to go change JS every time you want to change the output style of one of the states.
Using an event listener instead of an onclick assigned to the html Button tag will allow the function to count up the clicks, because essentially the function is continually running instead of just firing once every time the button is clicked.
let counter = 0; //establishing the counter
button.addEventListener("click", function() { //using an event listener instead of an onclick event allows the function to continually run instead of firing once each time the button is clicked
let button = document.querySelector("#button");
let print1 = 'Goodbye Foo'; //making the change state the first state assigned by the click means that the content will in fact change the first time you click the button, which took me a hot second to figure out
let print2 = 'Hello World';
let printer = document.getElementById('second');
if (counter % 2 == 0) { //if the counter, when divided by two has a remainder of 0
printer.innerHTML = print1; //then print "print1" as the inner html
printer.classList.replace('print2', 'print1'); //and toggle the classes
} else { //else, if the remainder of the counter divided by 2 is not zero
printer.innerHTML = print2; //print the other state
printer.classList.replace('print1', 'print2'); //and replace the css
}
if (counter >= 9) { //if the counter ever gets to 9 (an odd number)
counter = 0; //then restart the counter at zero (which gives a remainder of 0, making it "even" in this case
} else {
counter++; //otherwise count up one each time the button is pressed
}
});
.print1 {
color: red;
font-size: 24px;
}
.print2 {
color: blue;
font-size: 12px;
}
<button id="button" type="submit">
Click me
</button>
<p id="second" class="print2">
Hello World
</p>
here it is in jsfiddle:
https://jsfiddle.net/slingtruchoice/wkt3pz9v/
you can switch from a class to another using toogle to change the style like this :
document.getElementById("second").classList.toggle("mystyle");
and you keep inner-html to change the text like this:
if (document.getElementById("second").innerHTML === "Click here")
{
document.getElementById("second").innerHTML = "Hello Javascript";
} else {
document.getElementById("second").innerHTML = "Click here";
}
I eventually used this and it worked perfectly fine for me. it also changed the text on the button as well.
let count = 1;
function mySecond() {
if (count == 1) {
document.getElementById("button3").innerHTML = "Hello Javascript";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Back";
count = 0;
} else if (count == 0) {
document.getElementById("button3").innerHTML = "This is the best";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Start";
count = 1;
}
}
<button id="button2" onclick="mySecond()">Start</button>
<p id="button3">This is the best</p>
.myStyle {
color: brown;
}
I have a function that chooses a random string from an array and types it in a paragraph. I trigger this function by pressing a button.
var myArray = ['something', 'something else', 'another thing',];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;
var speed = 55;
function typeWriter() {
if (i < rand.length) {
document.getElementById("question").innerHTML += rand.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>
<p id="question"></p>
Pressing the "next" button triggers the typeWriter function, which chooses a random string from myArray and begins to type it in the paragraph "question". What I want to happen is, upon pressing "next" again (either while the typing is going on or after the typing is done), the text that has been typed already is deleted and the typeWriter triggers again, choosing another string and typing it in paragraph "question".
You want something like this?
var myArray = ['something', 'something else', 'another thing',];
var speed = 100;
var target = document.getElementById("question");
var char;
var timer;
var sentence;
function type(){
if(char < sentence.length) {
target.innerHTML += sentence.charAt(char++);
} else {
clearInterval(timer);
}
}
function reset() {
clearInterval(timer);
sentence = myArray[Math.floor(Math.random() * myArray.length)];
char = 0;
target.innerHTML = '';
}
function typeWriter() {
reset();
timer = setInterval(type, speed);
}
<button class="button next" id = "next" onclick="typeWriter()"> Next</button>
<p id="question"></p>
The setTimeout you have used implies that each time a character is "pressed", a new timer is started. My approach is to use an interval timer, which is simply writing the next character until the sentence ends or the typewriter is reset. In these two cases, the timer is cleared.
if you are fetching random string then you need to write that code inside your function.
please try below solution.
<button class="button next"
id = "next"
onclick="typeWriter()">
Next
</button>
<p id="question"></p>
<script>
var myArray = ['a', 'b', 'c',];
var i = 0;
var speed = 55;
function typeWriter() {
var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (i < rand.length) {
document.getElementById("question").innerHTML = rand.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
else
{
i--;
}
}
</script>
So I am trying to use jQuery, (in the heading) and javascript (normally) in the same document, but it seems that because of the script source thing, it conflicts with the JavaScript and doesn't word as I need it too
<head>
<title> Panel </title>
<link type="text/css" rel="stylesheet" href="clicker.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(function( $ ){
$(document).ready(function(){
$("#buckhead").click(function(){
$("#buckpanel").slideToggle(750);
});
});
})( jQuery );
</script>
</head>
Then later on in the document I put:
<script type="text/javascript">
var bcost = 1;
var clickmulti = 1;
var clicks = 0;
var bcost = 1000;
var mcost = 100;
var y = 0;
var x = 0;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("mcost").innerHTML = mcost;
document.getElementById("bcost").innerHTML = bcost;
function clickFunc() {
clicks += cps * clickmulti;
document.getElementById("clicks").innerHTML = clicks;
return true;
}
function clickMulti() {
if(clicks >= mcost && y < 50) {
clicks -= mcost;
mcost *= 1.25;
mcost = math.ceil(mcost * 1) / 1;
clickmulti += 1;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("mcost").innerHTML = mcost;
y += 1;
return true;
} else if(y == 50) {
alert("This upgrade is maxed!");
return false;
} else {
alert("You do not have enough fish to purchase this!");
return false;
}
}
function clickBase() {
if(clicks >= bcost && x < 100) {
clicks -= bcost;
bcost *= 1.25;
bcost = math.ceil(bcost * 1) / 1;
x += 1;
cps += 1;
document.getElementById("clicks").innerHTML = clicks;
document.getElementById("bcost").innerHTML = bcost;
return true;
} else if(x == 100) {
alert("This upgrade is maxed!");
return false;
} else {
alert("You do not have enough fish to purchase this!");
return false;
}
}
</script>
And it seems like the code is conflicting, because the jQuery is working just fine, as it is simple code, but the buttons to activate the JavaScript, which should be working as buttons are really easy, seems so when I click it, the functions aren't working, although almost every function is working, (ALMOST) except for
function clickFunc()
If you have the answer it would be greatly appreciated!
edit: here is the button calls, which by the way the buttons are before the second script.
<div class="fish"
<h2>Click for fish</h2><br>
<button onclick="clickFunc()" type="button">Click for fish</button><br>
<p> You have <span id="clicks"></span> fish</p>
<button type="button" onclick="clickMulti()"> Upgrade your click multiplier! (Cost:<span id="mcost"></span>)</button>
<button type="button" onclick="clickBase()">Upgrade base clicks!<br>
(Cost:<span id="bcost"></span>)</button>
</div><br><br>
Resolved, simply my problem of forgetting to make a global variable instead of a local variable. I forgot to make the global variable "cps"
Code edited. Apologizes for the incomplete first code
I've this code that takes input from the user, and it appends an image that matches that input. What I want to do is to set different buttons (200 aprox.) to append a different image if other button is pressed. The approaching I'm doing for this is to target the first if, within the first switch case, with the ("#id").length condition.
This is a short example of my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<section id="section">
<input id="input">
<button id="1"></button>
<button id="2"></button>
</section>
<div id="div"></div>
</body>
</html>
Javascript:
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(); });
});
var input = ['a','b','c'];
function test() {
var interval = setInterval(match, 1);
$("div").html("");
str = $("input").val().toLowerCase();
var i = 0;
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>",
"<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if ($("#1").length){
$("div").append(imgs[0]);
i++;
break;
}else if ($("#2").length){
$("div").append(imgs[1]);
i++;
break;
}
}
else {
clearInterval(interval);
$("input").val("");
}
}
}
Now, I've managed to make the if work, it shows the image, but if I press the second button, the else-if never works. What am I doing wrong?
Well I can't for the life of me figure out what you're trying to do with this code, but here is a working version of it...
$(document).ready(function() {
var str;
$("#1, #2").click(function () { test(this); });
});
var input = ['a','b','c'];
function test(caller) {
var interval = setInterval(match, 1);
var i = 0;
$("div").html("");
str = $("input").val().toLowerCase();
function match() {
var imgs = ["<img src='https://1.bp.blogspot.com/-v2N2hPY33pc/V488gHu5aWI/AAAAAAAAHFM/loGVDK5OlGcft5UUz8-AHZjAd3E7OlZjACLcB/s1600/colorful-background-with-waves.jpg' alt='0'>","<img src='https://upload.wikimedia.org/wikipedia/commons/c/c8/Widget_icon.png' alt='1'>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/100px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg' alt='2'/>","<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Corythucha_ciliata.jpg/120px-Corythucha_ciliata.jpg' alt='3'/>"];
if (i < str.length) {
switch (str[i]) {
case input[0]:
if (caller.id == "1") {
$("div").append(imgs[0]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[1]);
i++;
break;
}
case input[1]:
if (caller.id == "1") {
$("div").append(imgs[2]);
i++;
break;
} else if (caller.id == "2") {
$("div").append(imgs[3]);
i++;
break;
}
}
} else {
clearInterval(interval);
$("input").val("");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>
<button id="1">1</button>
<button id="2">2</button>
<div></div>
I'm fairly new to JavaScript, but I have some experience in other languages. I've been working on making my own small project, and I'm still figuring out how some things work. I have two problems that I need help solving. The first one, is that I have a button that should appear after you get 100 points, and click the button. This is at the if (buyupgrade == 1) and the following parts of that. I want the button to appear after the conditions are met (buy the first upgrade after getting 100 points). I also want to be printing the text part of a button, but in the text, I need it to display a variable, So my button text will display some words and a variable. Thanks for the help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost 200</button>
<script>
var points = 98;
var pointMulti = 1;
var buyupgrade = 0;
var currentpoints = setInterval(pointupdate, 1000);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
}
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + points + " points!";
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
Your code that is supposed to make the third button visible is by itself outside any function. This seems like a typo:
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
This only gets called the first time through the program when buyupgrade == 0
I think you meant for this to be inside the function:
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
// add some text to the button
firstbuild.innerText = "buyupgrade: " + buyupgrade
}
}
Also, there's a typo:
document.getElementById("firstbuild");
should probably be:
var firstbuild = document.getElementById("firstbuild");