How to use jquery and javascript in same document - javascript

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"

Related

Displaying buttons and printing a variable in javascript

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");

Error code JS with my function Game Over

I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

Display text given a counters current count

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

Repeating Javascript Animations?

I'm trying to make a div go up, down, up again, down again, etc. until you click on it. This is what I've got:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var moving = false;
moving.onclick = start;
function start() {
if (moving == false) {
moving = true;
move();
window.alert("Start!");
}
else {
moving = false;
window.alert("Aww...");
}
}
function move() {
if (moving) {
if (mMargin < 700) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
I was actually quite proud of myself for a while, until it didn't work... As you can see, I made an attempt at troubleshooting by adding those alert boxes. Neither of them were triggered, so right now it's a problem with the initial stuff, although there may be other errors as well. No errors in the console. Advice?
Hippydog's answer got me past the first part. I then realized I had to add another variable to keep the div from spazing out at the bottom of the first run. I just wanted to post what worked for anyone else looking at this for reference:
<!DOCTYPE html>
<html>
<head>
<title>Fun with animations dude</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="moving">
</div>
<script type="text/javascript">
var moving = document.getElementById("moving");
var mMargin = moving.style.marginTop | 0;
var isMoving = false;
var movingDown = true;
moving.onclick = start;
function start() {
if (isMoving == false) {
isMoving = true;
move();
}
else {
isMoving = false;
}
}
function move() {
if (isMoving) {
if (movingDown) {
mMargin += 10;
moving.style.marginTop = mMargin + "px";
if (mMargin >= 1000) {
movingDown = false;
}
setTimeout(move, 20);
}
else {
mMargin -= 10;
moving.style.marginTop = mMargin + "px";
if (mMargin <= 0) {
movingDown = true;
}
setTimeout(move, 20);
}
}
}
</script>
</body>
</html>
If any more experienced coders find some unforseen problem with this script, feel free to let me know.
The first and third local variables are both called moving. Renaming the second to isMoving (and updating any mentions of this variable) causes the alerts to show as expected.

Categories