This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');
Related
I'm creating a simple card game that when a player wins the score should increase per win. But whenever I run this code it keeps resetting the score back to 0.
How can I make it so the scores keep increasing +1 if the corresponding player wins?
I've tried the below and it's unfortunately not working with what I have
$(document).ready(function(){
//storing our images, separating them out by suit. Orderimg from lowest to highest cards.
arrClubs=['2_of_clubs.png','3_of_clubs.png', '4_of_clubs.png', '5_of_clubs.png', '6_of_clubs.png', '7_of_clubs.png', '8_of_clubs.png', '9_of_clubs.png', '10_of_clubs.png', 'jack_of_clubs.png','queen_of_clubs.png', 'king_of_clubs.png', 'ace_of_clubs.png']
arrDiamonds=['2_of_diamonds.png','3_of_diamonds.png', '4_of_diamonds.png', '5_of_diamonds.png', '6_of_diamonds.png', '7_of_diamonds.png', '8_of_diamonds.png', '9_of_diamonds.png', '10_of_diamonds.png', 'jack_of_diamonds.png','queen_of_diamonds.png', 'king_of_diamonds.png', 'ace_of_diamonds.png']
arrHearts=['2_of_hearts.png','3_of_hearts.png', '4_of_hearts.png', '5_of_hearts.png', '6_of_hearts.png', '7_of_hearts.png', '8_of_hearts.png', '9_of_hearts.png', '10_of_hearts.png', 'jack_of_hearts.png','queen_of_hearts.png', 'king_of_hearts.png', 'ace_of_hearts.png']
arrSpades=['2_of_spades.png','3_of_spades.png', '4_of_spades.png', '5_of_spades.png', '6_of_spades.png', '7_of_spades.png', '8_of_spades.png', '9_of_spades.png', '10_of_spades.png', 'jack_of_spades.png','queen_of_spades.png', 'king_of_spades.png', 'ace_of_spades.png']
//console.log(arrClubs);
var player1Score = 0;
var player2Score = 0;
//get random suit. 1 = Clubs, 2 = Diamonds, 3 = Hearts, 4 = Spades.
var suitType = Math.ceil(Math.random() * 4)
var card = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
console.log(arrClubs[card])
selectedCard = arrClubs[card]
} else if(suitType == "2"){
console.log(arrDiamonds[card])
selectedCard = arrDiamonds[card]
} else if (suitType == "3"){
console.log(arrHearts[card])
selectedCard = arrHearts[card]
} else {
console.log(arrSpades[card])
selectedCard = arrSpades[card]
}
document.getElementById('p1Card').src = "./images/cards/" + selectedCard
//Player 2 Randomly Selected Card:
var suitType = Math.ceil(Math.random() * 4)
var card2 = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
// console.log(arrClubs[card2])
selectedCard = arrClubs[card2]
} else if(suitType == "2"){
// console.log(arrDiamonds[card2])
selectedCard = arrDiamonds[card2]
} else if (suitType == "3"){
//console.log(arrHearts[card2])
selectedCard = arrHearts[card2]
} else {
//console.log(arrSpades[card2])
selectedCard = arrSpades[card2]
}
document.getElementById('p2Card').src = "./images/cards/" + selectedCard;
if (card < card2){
player2Score++;
document.getElementById('player2Results').value = player2Score;
// alert("Player 2 Wins")
} else if (card > card2){
player1Score++;
document.getElementById('player1Results').value = player1Score;
// alert("Player 1 wins")
} else {
// alert("TIE!")
console.log('Tie!');
}
})
<!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>War</title>
</head>
<body>
<div> Game</div>
<img src="./images/cards/black_joker.png" id="p1Card">
<img src="./images/cards/red_joker.png" id="p2Card">
<input type="text" readonly id="player1Results"/>
<input type="text" readonly id="player2Results"/>
<button id="play">Play</button>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>
Most likely you are setting player1Score and player2Score back to 0 each time you run it. Here's a working example:
const runGame = (() => {
var player1Score = 0;
var player2Score = 0;
return () => {
const card = Math.random();
const card2 = Math.random();
if (card < card2){
player2Score++;
console.log('Player 2 Wins! Score: ' + player2Score);
document.getElementById('p2').value = player2Score;
} else if (card > card2){
player1Score++;
console.log('Player 1 Wins! Score: ' + player1Score);
document.getElementById('p1').value = player1Score;
} else {
console.log('Tie!');
}
}
})();
document.getElementById('play').addEventListener('click', runGame);
<div id="player1Results"></div>
<div id="player2Results"></div>
<input type="text" readonly id="p1"/>
<input type="text" readonly id="p2"/>
<button id="play">Play</button>
I am trying to detect a keypress using the jQuery keyup function, but it does not seem to work in Firefox. Though it does work in Chrome, Edge, IE and Opera.
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
".textfield" is an iframe with designmode = 'on' So I'm trying to detect a keyup within a editable iframe.
Here's my iframe, nothing special:
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
EDIT: (It's one of my first websites, so don't mind the bad code)
HTML
<head>
<title>Notepad - A minimalistic, free online text editor for your notes</title>
<meta charset="utf-8"/>
<meta name="description" content="Notepad is a free, minimalistic, online text editor for quickly writing down, saving and sharing your notes."/>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="filesaver/filesaver.js"></script>
<link href="https://fonts.googleapis.com/css?family=Khula|Roboto|Open+Sans|Barrio|Cairo|Cantarell|Heebo|Lato|Open+Sans|PT+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<!-- Fonts -->
<script>
WebFont.load({
google: {
families: ['Cantarell', "Open Sans"]
}
});
</script>
</head>
<body onload="enableEdit('dark'); handlePaste(); handleDrop(); retrieveNote(); createCookie();">
<!-- Facebook & Twitter Share -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/nl_NL/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div id="social">
<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-size="small" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fplugins%2F&src=sdkpreparse" style="vertical-align:top;zoom:1;*display:inline">Share</a></div>
<a class="twitter-share-button" href="https://twitter.com/intent/tweet"></a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
<!-- Page -->
<div id="page">
<!-- Textfield -->
<iframe class="textfield" name="textfield" frameBorder="0"></iframe>
<!-- Toolbar -->
<div id="toolbar">
<h1 class="button" id="btn_bold" onclick="bold();" onmouseenter="onMouseEnter('btn_bold');" onmouseleave="onMouseLeave('btn_bold');"><b>B</b></h1>
<h1 class="button" id="btn_ita" onclick="italic();" onmouseenter="onMouseEnter('btn_ita');" onmouseleave="onMouseLeave('btn_ita');"><i>I</i></h1>
<h1 class="button" id="btn_und" onclick="underline();" onmouseenter="onMouseEnter('btn_und');" onmouseleave="onMouseLeave('btn_und');"><u>U</u></h1>
<img src="img/theme_dark.png" alt="Change theme" class="button theme" id="btn_theme" onclick="changeTheme();" onmouseenter="onMouseEnter('btn_theme');" onmouseleave="onMouseLeave('btn_theme')"; alt="Change theme." title="Theme"></img>
<img src="img/save.png" type="button" id="btn_save" value="submit" onclick="post();" class="button theme" alt="Save note." onmouseenter="onMouseEnter('btn_save');" onmouseleave="onMouseLeave('btn_save')" title="Save note"/>
<img src="img/cloud.png" type="button" id="btn_down" onclick="download();" class="button theme" alt="Download note" onmouseenter="onMouseEnter('btn_down');" onmouseleave="onMouseLeave('btn_down')" title="Download note"/>
<h1 class="button" id="btn_plus" onmousedown="changeFontSize(3);" onmouseenter="onMouseEnter('btn_plus');" onmouseleave="onMouseLeave('btn_plus');">+</h1>
<h1 class="button" id="btn_minus" onmousedown="changeFontSize(-3);" onmouseenter="onMouseEnter('btn_minus');" onmouseleave="onMouseLeave('btn_minus');">-</h1>
</div>
<div id="result"></div>
</div>
<?php
require("dbconnect.php");
$id = 0;
$idvar = $_GET['id'];
if ($idvar != null) {
$sel = "SELECT text from content WHERE id = $idvar";
} else {
$sel = "SELECT text from content WHERE id = 0";
}
$result = mysqli_query($connection, $sel);
if (mysqli_num_rows($result) == 1) {
while ($r = mysqli_fetch_array($result)) {
$content = str_replace('"', '"', $r["text"]);
}
} else {
header("Location: index.html");
}
$result = mysqli_query($connection, "SELECT id FROM content ORDER BY id DESC LIMIT 1;");
if (mysqli_num_rows($result) > 0) {
$lastid = mysqli_fetch_row($result);
}
?>
<div id="hid" style="display:none;" data-info="<?php echo $content; ?>"></div>
<script type="text/javascript">
function post() {
if (!saved) {
var content = getContent();
$.post("note.php", {posttext:content}, function (data) {});
var lastid = "<?php echo $lastid[0]; ?>";
if (content != "") {
increment++;
lastid = parseInt(lastid) + increment;
alert("Note saved at:\nnotepad.com/index.html?id=" + lastid);
document.getElementById("btn_save").style.opacity = "0.3";
document.getElementById("btn_save").title = "Saved at:\nnotepad.com/index.html?id=" + lastid;
saved = true;
} else {
alert("Empty note");
}
}
}
</script>
<script type="text/javascript" src="script.js"></script>
</body>
JavaScript
var color_text;
var color_button_light;
var color_button_dark;
var color_background;
var color_hover;
var brightness;
var font_size = 32;
var saved = false;
var mouseObj;
function getContent() {
return textfield.document.body.innerHTML;
}
var increment;
function download() {
if (getContent() != "") {
var blob = new Blob([getContent()], {type: "text/plain;charset=utf-8"});
saveAs(blob, "note");
} else {
alert("Empty note");
}
}
function retrieveNote() {
var info = $("#hid").data("info");
textfield.document.body.innerHTML = info;
}
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
function enableEdit(theme) {
increment = 0;
// Themes
if (theme === 'dark') {
color_text = "#757575";
color_button_light = "#303030";
color_button_dark = "#646464";
color_hover = "#535353";
brightness = 125;
color_background = "#151515";
} else if (theme === 'hacker') {
color_text = "#00BB00";
color_button_light = "#202020";
color_button_dark = "#00BB00";
color_hover = "#009900";
brightness = 125;
color_background = "#000000";
} else if (theme === 'light') {
color_text = "#999";
color_button_light = "#BBBBBB";
color_button_dark = "#757575";
color_hover = "#646464";
brightness = 90;
color_background = "#EEEEEE";
}
// Background Color
document.body.style.backgroundColor = color_background;
document.getElementById("toolbar").backgroundColor = color_background;
// Textfield
textfield.document.designMode = 'on';
var tag = "<link href='https://fonts.googleapis.com/css?family=Open+Sans|Heebo|Lato' rel='stylesheet'><style>body{font-family:consolas, heebo;}</style>"
$(".textfield").contents().find("head").append(tag);
textfield.document.body.style.fontSize = font_size + "px";
textfield.document.body.style.color = color_text;
textfield.document.body.style.padding = "20px";
textfield.document.body.style.tabSize = "4";
textfield.document.body.style.whiteSpace = "pre-wrap";
textfield.document.body.style.wordWrap = "break-word";
textfield.document.body.style.lineHeight = "1.4";
textfield.focus();
// Buttons
document.getElementById("btn_bold").style.color = color_button_light;
document.getElementById("btn_ita").style.color = color_button_light;
document.getElementById("btn_und").style.color = color_button_light;
document.getElementById("btn_plus").style.color = color_button_dark;
document.getElementById("btn_minus").style.color = color_button_dark;
}
function handlePaste() {
textfield.document.addEventListener("paste", function(evnt) {
evnt.preventDefault();
var text = evnt.clipboardData.getData("text/plain");
document.getElementById("btn_save").style.opacity = "1";
saved = false;
textfield.document.execCommand("insertText", false, text);
});
}
function handleDrop() {
textfield.document.addEventListener("drop", function (evnt) {
evnt.preventDefault();
document.getElementById("btn_save").style.opacity = "1";
saved = false;
var text = evnt.dataTransfer.getData("text/plain");
textfield.document.execCommand("insertText", false, text);
});
}
var sources = ["theme_dark.png", "theme_light2.png", "theme_hacker.png"];
var sources2 = ["save_dark.png", "save.png", "save_hacker.png"];
var themes = ["dark", "light", "hacker"];
var iterator;
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function createCookie() {
if (getCookie("theme") == "") {
iterator = 0;
} else {
iterator = getCookie("theme");
}
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
}
function changeTheme () {
createCookie();
if (iterator < sources.length-1) {
iterator++;
} else {
iterator = 0;
}
document.cookie = "theme=" + iterator + ";expires=Date.getTime() + 60 * 60 * 24 * 365 * 10;";
document.getElementById('btn_theme').src = "img/" + sources[iterator];
document.getElementById('btn_save').src = "img/" + sources2[iterator];
enableEdit(themes[iterator]);
onMouseEnter('btn_theme');
}
function bold() {
textfield.document.execCommand("bold", false, null);
}
function italic() {
textfield.document.execCommand("italic", false, null);
}
function underline() {
textfield.document.execCommand("underline", false, null);
}
function changeFontSize (amount) {
font_size += amount;
textfield.document.body.style.fontSize = font_size + "px";
}
function onMouseEnter(id) {
mouseObj = id;
if (mouseObj != 'btn_theme' && mouseObj != 'btn_save') {
document.getElementById(mouseObj).style.color = color_hover;
} else {
document.getElementById(mouseObj).style.filter = "brightness(" + brightness + "%)";
}
}
function onMouseLeave(id) {
mouseObj = null;
}
setInterval(function() {
var isBold = textfield.document.queryCommandState("Bold");
var isItalic = textfield.document.queryCommandState("Italic");
var isUnderlined = textfield.document.queryCommandState("Underline");
if (isBold == true && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_dark;
} else if (isBold == false && mouseObj == null) {
document.getElementById("btn_bold").style.color = color_button_light;
}
if (isItalic == true && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_dark;
} else if (isItalic == false && mouseObj == null) {
document.getElementById("btn_ita").style.color = color_button_light;
}
if (isUnderlined == true && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_dark;
} else if (isUnderlined == false && mouseObj == null) {
document.getElementById("btn_und").style.color = color_button_light;
}
if (mouseObj != 'btn_plus') {
document.getElementById("btn_plus").style.color = color_button_dark;
}
if (mouseObj != 'btn_minus') {
document.getElementById("btn_minus").style.color = color_button_dark;
}
if (mouseObj != 'btn_theme') {
document.getElementById("btn_theme").style.filter = "brightness(100%)";
}
if (mouseObj != 'btn_save') {
document.getElementById("btn_save").style.filter = "brightness(100%)";
}
},10);
PHP for saving the note
<?php
require("dbconnect.php");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_error();
}
if (isset($_POST["posttext"]) && !empty($_POST["posttext"])) {
$content = $_POST['posttext'];
$content = mysqli_real_escape_string($connection, $_POST["posttext"]);
$insert = "INSERT INTO content (text) VALUES ('$content')";
mysqli_query($connection, $insert);
$id = mysqli_insert_id($connection);
}
?>
you can use jquery ...
$(document).ready(function(){
$(".textfield").keyup(function() {
$("#btn_save").css("opacity", 1);
});
});
Okay, I fixed the problem. Apparently Firefox needs $(document).ready() to properly function for keypress events (haven't tested other events).
So your code should be:
$(document).ready(function(){
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
});
Instead of:
$(".textfield").contents().keyup(function(evnt) {
document.getElementById("btn_save").style.opacity = "1";
saved = false;
});
As I already said this is a problem that only occured in Firefox AFAIK.
This code works in Chrome, Firefox, Opera, Edge and Internet Explorer as of time of writing this answer.
I had a similar problem.
The mobile keyboards (in Firefox) don't emit keyup, keydown and keypress events.
So, I met the Text Composition events.
Something like this:
myInput = document.getElementById('myInput');
myInput.addEventListener('compositionupdate', (event) => {
setTimeout(() => {
applyFilter(event)
});
})
The setTimeOut was necessary to wait input value receipt the keyboard value before call my function.
I have a big problem with my JavaScript timer. Everything working fine, except 1 button: STOP! I cant figure out how to stop everything on my counter (like reset every input and the counter). Any ideas how can I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feladat 5</title>
</head>
<body>
<form>
<label>Indulás: </label><input type="number" id="n_start" placeholder="1000"/> <label> (4 számjegyű
szám)</label><br /><br />
<label>Megállás: </label><input type="number" id="n_end" placeholder="1008"/> <label> (4 számjegyű szám)</label><br/><br />
<label>Számolás léptei: </label><input type="number" id="n_count" placeholder="1"/> <br /><br />
<label>Időközönti számolás: </label><input type="number" id="n_timer" placeholder="1"/> <label> (másodpercben)</label><br /><br />
</form>
<label>Számláló: </label><span id="counter">0</span> <br /><br />
<button id="first" type="button" onclick="count()">Start</button>
<button id="pause" type="button" style="display:none;" onclick="show_resume()">Pause</button>
<button id="resume" type="button" style="display:none;" onclick="show_pause()">Resume</button>
<button id="stop" type="button" name="stop">Stop</button>
<script>
function counterLoop(callback, delay)
{
var id
,start
,remaining = delay;
this.pause = function()
{
window.clearTimeout(id);
remaining -= new Date() - start;
};
var resume = function()
{
start = new Date();
id = window.setTimeout(function()
{
remaining = delay;
resume();
callback();
}, remaining);
};
this.resume = resume;
this.resume();
}
function count()
{
var startValue = document.getElementById("n_start").value;
var endValue = document.getElementById("n_end").value;
var countValue = document.getElementById("n_count").value;
var timerValue = document.getElementById("n_timer").value;
var count = startValue;
if (startValue == "" || endValue == "" || countValue == "" || timerValue == "")
{
alert("Minden mező kitöltése kötelező!");
}
else
{
if (startValue < 999 || endValue < 999)
{
alert("Legalább 4 számjegyű kell legyen az érték!")
}
else
{
var math_check = endValue - startValue;
if (math_check % countValue != 0 )
{
alert("A számlálás léptei túl lépnék a megállást.");
}
else
{
var counter = new counterLoop(function ()
{
if (startValue <= endValue)
{
if (countValue == 1)
{
++count;
if (count == endValue )
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
else
{
count = +countValue + +count;
if (count == endValue)
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
}
document.getElementById('counter').innerHTML = count;
}, timerValue * 1000);
document.getElementById('pause').addEventListener('click', function () {
counter.pause()
}, false);
document.getElementById('resume').addEventListener('click', function () {
counter.resume()
}, false);
document.getElementById('pause').style.display = 'inline';
document.getElementById('first').style.display = 'none';
}
}
}
};
function show_resume()
{
document.getElementById('resume').style.display = 'inline';
document.getElementById('pause').style.display = 'none';
}
function show_pause()
{
document.getElementById('resume').style.display = 'none';
document.getElementById('pause').style.display = 'inline';
}
</script>
</body>
</html>
do you want to stop that timer and resume or just stop and reset all the fields?
I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }
I want to add a variable b, that starts off at a value of 100. When I click the add button for value a, it adds 1 to value a but minus 1 from the 100 and vice versa with the minus button.
<head>
<script type="text/javascript">
var b = 100
document.getElementById('Valueb').innerHTML = b;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Valuea').innerHTML = a;
if(a == 0) {
document.getElementById('minus').disabled = true;
} else {
document.getElementById('minus').disabled = false;
}
}
</script>
</head>
<body>
Valueb:<span id="Valueb">0</span>
Valuea:<span id="Valuea">0</span>
<button type="button" id = add onclick="javascript:add(1)">+</button>
<button type="button" id = minus onclick="javascript:add(-1)">-</button>
</body>
You need to put the script in the end of body section.
<head>
<body>
Value b:<span id="Valueb">0</span>
Value a:<span id="Valuea">0</span>
<button type="button" id = add onclick="javascript:add(1)">+</button>
<button type="button" id = minus onclick="javascript:add(-1)">-</button>
<script type="text/javascript">
var b = 100
document.getElementById('Valueb').innerHTML = b;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
b -=valueToAdd;
document.getElementById('Valuea').innerHTML = a;
document.getElementById('Valueb').innerHTML = b;
if(a == 0) {
document.getElementById('minus').disabled = true;
} else {
document.getElementById('minus').disabled = false;
}
}
</script>
</head>
</body>
Press F12 (or whatever) in your browser and look in the console.
Reload the page and you can see errors in your Javascript code.
<span id="Valueb">0</span> if not visible to Javascript the way your code is.
So you can put the Javascript at the end before </body> or you can use window.addEventListener('load', functionname, false); so the code will run when the page has loaded.
Maybe this is what your looking for...
<!DOCTYPE html>
<head>
<title>Something</title>
<style type="text/css">
body, button {
margin: 20px;
font-size: 80px;
text-align: center;
}
button {
width: 2em;
height: 2em;
}
</style>
<script type="text/javascript">
'use strict';
var a = 0,
b = 100,
outputa = null,
outputb = null,
buttonadd = null,
buttonminus = null;
function letsgo() {
outputa = document.getElementById('Valuea');
outputb = document.getElementById('Valueb');
buttonadd = document.getElementById('add');
buttonminus = document.getElementById('minus');
outputa.innerHTML = a;
outputb.innerHTML = b;
checkdisable();
}
function add(valueToAdd) {
a += valueToAdd;
b -= valueToAdd;
outputa.innerHTML = a;
outputb.innerHTML = b;
checkdisable();
}
function checkdisable() {
if(a <= 0) {
buttonminus.disabled = true;
} else {
buttonminus.disabled = false;
}
if(a >= 100) {
buttonadd.disabled = true;
} else {
buttonadd.disabled = false;
}
}
if (window.addEventListener) {
window.addEventListener("load", letsgo, false);
}
</script>
</head>
<body>
<div>
Valuea:<span id="Valuea">X</span>
Valueb:<span id="Valueb">X</span>
</div>
<div>
<button type="button" id="add" onclick="javascript:add(1)">+</button>
<button type="button" id="minus" onclick="javascript:add(-1)">-</button>
</div>
</body>