How can I get my JavaScript carousel to work? - javascript

I can't get my carousel working. As far as I can tell the code is right, maybe you can see the problem? Here's the code...
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randy's Webpage</title>
<link rel="stylesheet" type="text/css" href="Ani.css">
</head>
<body>
<div class= "scene">
<div class= "carousel">
<div class= "cell">1</div>
<div class= "cell">2</div>
<div class= "cell">3</div>
<div class= "cell">4</div>
<div class= "cell">5</div>
<div class= "cell">6</div>
<div class= "cell">7</div>
<div class= "cell">8</div>
<div class= "cell">9</div>
<div class= "cell">10</div>
<div class= "cell">11</div>
<div class= "cell">12</div>
<div class= "cell">13</div>
<div class= "cell">14</div>
<div class= "cell">15</div>
</div>
</div>
<div class= "carousel-options">
<p>
<label>
Cells
<input class= "cells-range" type= "range" min= "3" max= "15" value= "9" />
</label>
</p>
<p>
<button class= "previous-button">Previous</button>
<button class= "next-button">Next</button>
</p>
<p class= "pee">Orientation: </p>
<label>
<input type= "radio" name= "orientation" value= "horizontal" checked />
Horizontal
</label>
<label>
<input type= "radio" name= "orientation" value= "vertical" />
Vertical
</label>
</p>
</div>
</body>
</html>
<script>
var nextButton = document.querySelector(".next-button");
nextButton.aaddEventListener("click", function() {
selectedIndex++;
rotateCarousel();
});
var cellsRange = document.querySelector(".cells-range");
cellsRange.addEventListener("change", changeCarousel);
cellsRange.addEventListener("input", changeCarousel);
function changeCarousel() {
cellCount = cellsRange.value;
theta = 360 / cellCount;
var cellSize = isHorizontal ? cellWidth : cellHeight;
radius = Math.round(cellSize / 2 / Math.tan(Math.PI / cellCount));
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (i < cellCount) {
//visible cell
cell.style.opacity = 1;
var cellAngle = thetaa * i;
cell.style.transform =
rotateFn + ")" + cellAngle + "deg) translateZ(" + radius + "px)";
} else {
// hidden cell
cell.style.opacity = 0;
cell.style.transform = "none";
}
}
rotateCarousel();
}
var orientationRadios = document.querySelectorAll('input[name="orientation"]');
(function() {
for (var i = 0; i < orientationRadios.length; i++) {
var radio = orientationRadios[i];
radio.addEventListener("change", onOrientationChange);
}
})();
function onOrientationChange() {
var checkedRadio = document.querySelector(
'input[name="orientation"]:checked'
);
isHorizontal = checkedRadio.value == "horizontal";
rotateFn = isHorizontal ? "rotateY" : "rotateX";
changeCarousel();
}
//set initials
onOrientationChange();
</script>
</body>
</html>
The html and css work, i cant get the pictures to cycle through or the number of cells to change. so none of the javascript is working for some reason.
it keeps saying add more details even though i already have.

You've got an extra a in one of your event listeners
Change:
nextButton.aaddEventListener( 'click', function() {
selectedIndex++;
rotateCarousel();
});
to
nextButton.addEventListener( 'click', function() {
selectedIndex++;
rotateCarousel();
});

Related

Dark mode script only works if script is in the index

I have 2 pages, each with the same code for the dark mode button.
The script on the index works, but the script in a different file doesn't. There are no errors.
Here is the script that doesn't work.
<body id = "body" class = "">
<h1 id="h1">Learn Chemistry!</h1>
start skill test
<form >
<h3 id="question"></h3>
<label for = "CO">CO:</label>
<input type = "text" id = "CO" class='input' autocomplete="off" placeholder="Answer">
<label for = "cb">Cl4Br5:</label>
<input type = "text" id = "cb" class='input' autocomplete="off" placeholder="Answer">
</form>
<button id = "check" onclick ="check()">Show answers</button>
<p id='demo'></p>
<form action='coming.html'>
<button id="next" onclick="next()">next</button>
</form>
<form action='index.html'>
<button id = "back" >back</button>
</form>
Here is the dark mode code in the same script.
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<script src="script.js"></script>
Here is the Js function darkmode. (works only for the script in the index)
const labels=document.getElementsByTagName("labels")
const answers=document.getElementById("demo");
const content=document.getElementById("content");
const body = document.getElementById("body");
const heading1 = document.getElementsByTagName("h1")[0];
const heading3 = document.getElementsByTagName("h3")[0];
const buttons = document.getElementsByTagName("button")
const titles = [heading1, heading3,answers]
const time=document.getElementById("time");
const button = document.getElementById("dark-btn");
// console.log(labels.length);
let dark = false;
function darkMode() {
if (dark == false){
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "darks");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "dark-txt");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "dark-txt");
i++;
}
body.setAttribute("class", "dark");
button.style.backgroundColor = "white";
button.style.color = "rgb(88, 119, 255)";
time.style.color = "white"
content.style.color="greenyellow"
dark = true;
} else {
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "");
i++;
}
body.setAttribute("class", "");
dark = false;
button.style.backgroundColor = "rgb(88, 119, 255)";
button.style.color = "white";
content.style.color="green"
}
}
#john
Here is the page that works. It is in the index.
<html >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body id = "body" class = "">
<h1 id='h1'>Learn Chemistry!</h1>
<style>
#content{
color: green;
transform:translate(140px,30px);
line-height:6px;
font-family:sans-serif;
}
</style>
<img id="flask" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<img id="flasktwo" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<button type="button" id="time"
onclick="document.getElementById('date').innerHTML = Date()">
Date and Time.</button>
<p id="date"></p>
<form >
<button id="learn" name="learn"onclick="nextc();return false" >Learn</button>
</form>
<img class="example" src="c2.png">
<h3 id="title"></h3>
<p id="content"></p>
<button id="next" name="hi" onclick="nextc();return false" >Next</button>
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<p id='demo'></p>
<!-- CONCEPTS -->
<!-- <body id = "body" class = ""> -->
<h3 class="title"></h3>
<button id="back">back</button>
<form id='next' action='q2.html'>
<button id="nexttwo" name="nexttwo" onclick="next()">Test</button>
</form>
<script src="script.js"></script>
</body>
</html>

How can i show flipbook when user clicks on flipbook's icons in jquery

Hope you all are fine. I Stuck in one problem from last three days and can't understand what should i do. If you can kindly help me. This is my code when user click on publication button a carousel of images become shown in the screen and when user click on these images it becomes filpbook of that images. The Problem in that is it works fine in first time and when user close that open flipbook and want to open new flipbook that old one still there and new clickable flipbook's icon didn't open in form of flipbook. I hope you people understand my question what i want to ask ? I also attached some images of results and also paste code so that you could relate to it.
Image Carousel (flipbook's icon)
flipbook open as expected when user click on it first time
Image Carousel (flipbook's icon) User want to open new flipbook from carousel
New flipbook open but old flipbook didn't disappear it still open. New Flipbook should open instead of old one and hide old one
$(document).ready(function() {
getPdfsIcons()
$("#back").hide();
// Load the HTML4 version if there's not CSS transform
// $("#flipview").hide();
// var carousel = $("#carousel").slidingCarousel({
// squeeze: 100
// });
$("#back").click(function() {
$("#flipview").hide();
$("#carousel").hide();
$("#pub").hide();
$("#switch-field").hide();
$("#close-btn").hide();
loadMain();
});
$("#close-btn").hide();
});
function getPdfsIcons() {
var dir;
var choosenlanguage = $("input[type='radio']:checked").val();
if (choosenlanguage == "e")
dir = "assets/Publications/English/";
else if (choosenlanguage == "a")
dir = "assets/Publications/Arabic/";
else if (choosenlanguage == "f")
dir = "assets/Publications/French/";
var fileextension = ".jpg";
var inc = 0;
$.ajax({
url: dir,
success: function(data) {
$(data)
.find("a:contains(" + fileextension + ")")
.each(function(i) {
var filename = this.href
.replace(window.location.host, "")
.replace("http://", "");
var folder = filename;
$(".carousel").append(
"<div id='slide" + i + "' class='slide' onClick=getAllrecords(document.getElementById('slide" + i + "').style.opacity,'" + folder.replace("assets/Publications/English/", "").replace(".jpg", "").replace("/", "") + "','" + i + "');><p> <span> " + filename + " </span> </p></div>" + "</div>"
);
});
},
});
}
function getAllrecords(opacity, foldername, x) {
if (opacity == 1) {
var choosenlanguage = $("input[type='radio']:checked").val();
if (choosenlanguage == "e")
dir = "assets/Publications/English/" + foldername + "/";
else if (choosenlanguage == "a")
dir = "assets/Publications/Arabic/" + foldername + "/";
else if (choosenlanguage == "f")
dir = "assets/Publications/French/" + foldername + "/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function(data) {
$(data)
.find("a:contains(" + fileextension + ")")
.each(function(i) {
var filename = this.href
.replace(window.location.host, "")
.replace("http://", "");
$(".flipbook-pages").append("<div class='flipImgs" + x + "'><img src='" + filename + "' width='600' height='600' /></div>");
$(".flipbook-thumbnail").append(
"<li>" +
"<img class='page-" +
++i +
"' src='" +
filename +
"' width='200' height='200' ' />" +
"</li>"
);
});
},
});
$("#flipview").show();
$("#carousel").hide();
$("#pub").hide();
$("#switch-field").hide();
$("#close-btn").show();
$("#close-btn")
.click(function() {
//window.location.href = "home.html"
$("#flipview").hide();
//$(".mainmenu_row1").hide()
//$(".mainmenu_row2").hide()
$("#pub").show();
$("#carousel").show();
//$(".flipbook-pages").empty();
//$(".flipbook-thumbnail").empty();
// var rangeObj = new Range();
// // Select all of theParent 's children
// rangeObj.selectNodeContents(document.getElementById('flipbook-pages'));
// // Delete everything that is selected
// rangeObj.deleteContents();
});
yepnope({
test: Modernizr.csstransforms,
yep: ["assets/js/turn.min.js"],
nope: ["assets/js/turn.html4.min.js"],
both: [
"assets/css/basic.css",
"assets/css/magazine.css",
"assets/js/magazine.js",
],
complete: loadApp,
});
}
}
function loadApp() {
// Create the flipbook
$(".flipbook-pages").turn({
// Width
width: 922,
// Height
height: 600,
// Elevation
elevation: 50,
// Enable gradients
gradients: true,
// Auto center this flipbook
autoCenter: true,
});
$(".thumbnails").click(function(event) {
var page;
if (
event.target &&
(page = /page-([0-90]+)/.exec($(event.target).attr("class")))
) {
$(".flipbook-pages").turn("page", page[1]);
}
});
$(".next-button")
.bind("mouseover", function() {
$(this).addClass("next-button-hover");
})
.click(function() {
$(".flipbook-pages").turn("next");
});
$(".previous-button")
.bind("mouseover", function() {
$(this).addClass("previous-button-hover");
})
.click(function() {
$(".flipbook-pages").turn("previous");
});
}
function loadMain() {
window.location.href = "home.html";
// $("icon_1").removeClass("animate__fadeOut");
// // $("icon_2").removeClass("animate__fadeOut");
// // $("icon_3").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_4").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_5").removeClass("animate__animated animate__swing animate__fadeOut");
// // $("icon_6").removeClass("animate__animated animate__swing animate__fadeOut");
// document.getElementById("icon_1").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_3").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_4").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_5").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_6").classList.add("animate__animated animate__swing animate__fadeIn");
// document.getElementById("icon_2").classList.add("animate__animated animate__swing animate__fadeIn");
}
function onBounce(id) {
document.getElementById(id).classList.add("animate__bounceOut");
if (id = "icon_2") {
getPdfsIcons();
document.getElementById("icon_1").classList.add("animate__fadeOut");
document.getElementById("icon_3").classList.add("animate__fadeOut");
document.getElementById("icon_4").classList.add("animate__fadeOut");
document.getElementById("icon_5").classList.add("animate__fadeOut");
document.getElementById("icon_6").classList.add("animate__fadeOut");
document.getElementById(id).addEventListener('animationend', () => {
// document.getElementById("mainmenu").style.setProperty('--animate-duration', '0.1s');
// document.getElementById("mainmenu").classList.add("animate__fadeOut");
document.getElementById("pub").style.setProperty('display', 'block');
document.getElementById("pub").classList.add("animate__zoomInRight");
$("#back").show();
var carousel = $("#carousel").slidingCarousel({
squeeze: 100
});
// do something animate__zoomInRight
});
$(".carousel").append(
"<div class='navigate-left'><img src='assets/images/backward.png' /></div>" +
"<div class='navigate-right'><img src='assets/images/forward.png' /></div>"
);
}
}
function language(lang) {
if (lang == 0) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/ebv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/ebv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/ebv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/ebv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/ebv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/ebv7.png')";
} else if (lang == 1) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/abv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/abv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/abv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/abv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/abv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/abv7.png')";
} else if (lang == 2) {
document.getElementById('icon_1').style.backgroundImage = "url('assets/images/fbv1.png')";
document.getElementById('icon_2').style.backgroundImage = "url('assets/images/fbv2.png')";
document.getElementById('icon_3').style.backgroundImage = "url('assets/images/fbv4.png')";
document.getElementById('icon_4').style.backgroundImage = "url('assets/images/fbv5.png')";
document.getElementById('icon_5').style.backgroundImage = "url('assets/images/fbv6.png')";
document.getElementById('icon_6').style.backgroundImage = "url('assets/images/fbv7.png')";
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<!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" />
<link rel="stylesheet" href="assets/css/main.css" />
<link rel="stylesheet" href="assets/css/animate.min.css" />
<link rel="stylesheet" href="assets/css/experiment.css" />
<link type="text/css" rel="stylesheet" href="assets/css/jquery.ui.css">
</link>
<link type="text/css" rel="stylesheet" href="assets/css/default.css">
</link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/modernizr.2.5.3.min.js"></script>
<script type="text/javascript" src="assets/js/hash.js"></script>
<script type="text/javascript" src="assets/js/turn.html4.js"></script>
<script type="text/javascript" src="assets/js/zoom.js"></script>
<script type="text/javascript" src="assets/js/scissor.min.js"></script>
<script src="assets/js/jquery-slidingCarousel.js" type="text/javascript"></script>
<link rel="stylesheet" href="assets/css/sliding-carousel.css" />
<!-- <link rel="manifest" href="/manifest.json" /> -->
<meta name="msapplication-TileColor" content="#ffffff" />
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png" />
<meta name="theme-color" content="#ffffff" />
<!-- <script src="assets/js/app.js"></script> -->
<title>Interactive Apps</title>
<style>
.scrollmenu {
background-color: white;
overflow: auto;
white-space: nowrap;
}
.scrollmenu li {
display: inline-block;
color: white;
padding: 14px;
text-decoration: none;
}
</style>
</head>
<body>
<div class="fullscreen">
<div class="row">
<div class="logo">
<img src="assets/images/logo.png" alt="logo image" />
</div>
<div id="switch-field" class="switch-field">
<input type="radio" id="radio-three" onclick="language(0);" name="langchoice" value="e" checked />
<label for="radio-three">English</label>
<input type="radio" id="radio-four" name="langchoice" onclick="language(1);" value="a" />
<label for="radio-four">عربى</label>
<input type="radio" id="radio-five" name="langchoice" onclick="language(2);" value="f" />
<label for="radio-five">Français</label>
</div>
<div class="pole-clock">
<div id="clock">
<div id="hour"><img src="assets/images/small_hand.png" /></div>
<div id="minute"><img src="assets/images/long_hand.png" /></div>
<div id="second"><img src="assets/images/sec_hand.png" /></div>
</div>
</div>
</div>
<div class="footer">
<img src="assets/images/Path 60.png" alt="footer image" />
</div>
<div id="mainmenu" class="animate__animated">
<div class='mainmenu_row1'>
<div id="icon_1" class='menu1 animate__animated animate__swing' onclick="onBounce('icon_1');">
</div>
<div id="icon_2" class='menu2 animate__animated animate__swing' onclick="onBounce('icon_2');">
</div>
<div id="icon_3" class='menu3 animate__animated animate__swing' onclick="onBounce('icon_3');"> </div>
</div>
<div class='mainmenu_row2'>
<div id="icon_4" class='menu4 animate__animated animate__swing' onclick="onBounce('icon_4');"> </div>
<div id="icon_5" class='menu5 animate__animated animate__swing' onclick="onBounce('icon_5');"> </div>
<div id="icon_6" class='menu6 animate__animated animate__swing' onclick="onBounce('icon_6');"> </div>
</div>
</div>
<!-- publications -->
<div id="pub" style="display: none;" class="pub animate__animated">
<div id="carousel" class="carousel">
</div>
</div>
<div id="flipview" class="flipview">
<div class="flipbook-viewport">
<div class="container">
<div class="flipbook">
<div id="flipbook-pages" class="flipbook-pages" style="margin-top: -8rem">
<div ignore="1" class="next-button"></div>
<!-- Previous button -->
<div ignore="1" class="previous-button"></div>
</div>
<button type="button" class="btn close" id="close-btn" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true" style="font-size: -webkit-xxx-large">×</span>
</button>
</div>
</div>
</div>
<div class="thumbnails" style="padding-top: 44rem">
<div>
<ul class="flipbook-thumbnail scrollmenu"></ul>
</div>
</div>
</div>
<div id="back" class="back"></div>
</div>
</body>
</html>

Function that assigns new value appears to initially work the first time, but doesn't appear to return to beginning of if statement the second time

I am in the middle of the Pig Dice problem and I am trying to use the function switchPlayers() to switch between player1 and player2. When clicking "Roll Dice", it appears to switch to the second player but then no longer switches to the first player. After re-working it a few times, I'm starting to think the issue may be that even if Player2 updates to .isTurn = false the function is longer being called? I appreciate any pointers here (Note, haven't worked on the New Game or Hold Button yet)Thank you!
JSFiddle
//business logic for dice
function Dice() {
this.diceValue = 1;
this.roll = 0;
}
function Player() {
this.score = 0;
this.dice = new Dice()
this.isTurn = true
}
//global Players
player1 = new Player();
player2 = new Player();
function switchPlayers() {
if (player1.dice.roll === 0) {
player1.isTurn = false;
} else if (player2.dice.roll === 0) {
player2.isTurn = false;
}
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random() * 6) + 1);
if (this.diceValue === 1) {
this.roll = 0;
} else {
this.roll = this.diceValue;
}
}
Player.prototype.calcScore = function() {
this.dice.rollDice()
if (this.dice.roll === 0) {
switchPlayers();
} else {
this.score += this.dice.roll
}
}
//ui logic
$(document).ready(function() {
$("button.btn-roll").click(function(event) {
if (player1.isTurn !== false) {
player1.calcScore();
$('#p1-total').html(player1.score);
$('#p1-roll').html(player1.dice.roll);
} else if (player2.isTurn === true) {
player2.calcScore();
$('#p2-total').html(player2.score);
$('#p2-roll').html(player2.dice.roll)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-1-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player1-score">
<p>this roll points: <span id="p1-roll"></span></p>
<p>
total: <span id="p1-total"></span>
</p>
</div>
</div>
</div>
<div class="player-2-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player1-score">
<p>this roll: <span id="p2-roll"></span></p>
<p>
total: <span id="p2-total"></span>
</p>
</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>
Keeping your logic, i have reviewed your code, added some tips (button hold), so you could easily understant what i have done and increase yours skills:
function initGame(){
//selectRandomly wich players begins
idToPlay = Math.floor((Math.random()*maxNumberPlayers));
for(let p = 0;p < maxNumberPlayers;p++){
let id = '#p' + p;
$(id + '-action').html('');
$(id + '-name').text(players[p].name);
$(id + '-total').html(players[p].score);
$(id + '-roll').html('--');
$(id + '-round').html('--');
$(id + '-dice').html('--');
}
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
//business logic for dice
function Dice() {
this.diceValue=1;
this.roll=0;
this.round=0;
}
function Player(name) {
this.name = name
this.score = 0;
players.push(this);
}
//global Players
players = [];
new Player("John");
new Player("Peter");
maxNumberPlayers = players.length;
dice = new Dice();
idToPlay = -1;//first player will be choosen by initGame
function switchPlayers() {
displayResult();
if(++idToPlay == maxNumberPlayers) idToPlay = 0;
dice.round = 0;
$( 'span[id$="-action"]').html('');
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random()*6)+1);
if (this.diceValue === 1) {
this.roll = 0;
this.round = 0
} else {
this.roll = this.diceValue;
this.round += this.roll;
}
}
Player.prototype.calcScore = function(isHoldButton = false) {
dice.rollDice();
if (dice.roll === 0) {
dice.round = 0;
switchPlayers();
} else {
this.round += dice.roll;
displayResult();
}
}
function displayResult(){
let id = '#p' + idToPlay;
$(id + '-name').html(players[idToPlay].name);
$(id + '-total').html(players[idToPlay].score);
$(id + '-roll').html(dice.roll);
$(id + '-round').html(dice.round);
$(id + '-dice').html(dice.diceValue);
}
//ui logic
$(document).ready(function() {
initGame();
$("button.btn-roll").click(function() {
players[idToPlay].calcScore();
});
$("button.btn-hold").click(function() {
players[idToPlay].score += dice.round;
switchPlayers();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<p>Rule: If you roll a 1, you will receive 0 roll points for the round and it will be the other player's turn.
</p>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name"><span id="p0-name">Player 1</span><span> </span><span id="p0-action"></span></div>
<div class="player0-score">
<p>Dice points:<span id="p0-dice"></span>
<span> </span>Roll points:<span id="p0-roll"></span>
<span> </span>Round points:<span id="p0-round"></span>
<span> </span>total:<span id="p0-total"></span>
</p>
</div>
</div>
<div class="player-1-panel">
<div class="player-name"><span id="p1-name">Player 1</span><span> </span><span id="p1-action"></span></div>
<div class="player1-score">
<p>Dice points:<span id="p1-dice"></span>
<span> </span>Roll points:<span id="p1-roll"></span>
<span> </span>Round points:<span id="p1-round"></span>
<span> </span>total:<span id="p1-total"></span>
</p>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>

dynamic change in javascript, won't move my div

Hi there fellow programmers!
I Want to be able to type in to the boxes how much px i want my div to move. But it won't move and I cant see whats wrong with my code. Can someone with fresh eyes spot the problem?
Any help is much appreciated!
Here's the code so far:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title> javascript</title>
<style>
#changeme {
background-color: lightblue;
position: absolute;
}
</style>
<script>
var $Rob = {};
$Rob.moveUpp = 0;
$Rob.moveLeft = 0;
$Rob.elementid = "";
$Rob.move = function(elementid, movex, movey)
{
$Rob.moveUpp = movey;
$Rob.moveLeft = movex;
$Rob.elementid = elementid;
$Rob.movesoft();
}
$Rob.movesoft = function() {
var elem = document.getElementById($Rob.elementid);
if ($Rob.moveUpp > 0) {
elem.style.top = (parseInt(elem.style.top) + 1) +
"px";
$Rob.moveUpp--;
} else if ($Rob.moveUpp < 0) {
elem.style.top = (parseInt(elem.style.top) - 1) +
"px";
$Rob.moveUpp++;
}
if ($Rob.moveUpp != 0) {
setTimeout($Rob.movesoft, 100);
}
}
</script>
</head>
<body>
<h1> Dynamic changes </h1>
<form>
<p>Move right:</p> <input value="0" type="text" id="moveRight" />
<p>Move down: </p> <input value="0" type="text" id="moveDown" />
<input type="button" value="Move" onClick="$Rob.move(document.getElementById('changeme'),parseInt(document.getElementById('moveRight').value),parseInt(document.getElementById('moveDown').value));" />
</form>
<div id="changeme" style="top: 100px;left: 100px;"> Hello </div>
</body>
</html>
All the best
I love Stackoverflow and its members!
cheers
// Mcgayjver
You're doing:
$Rob.move(document.getElementById('changeme'), x, y).
When you should just be doing:
$Rob.move('changeme, x, y)
Because $Rob.move expects an elementID string as a first parameter, not an actual HTMLElement.

Javascript event handler is not working

I am trying to to increment/decrement a value in a paragraph when a button is clicked.
$(document).ready(function() {
var breakTime = 5;
var section = 25;
var start = "Start";
var stop = "Stop";
function Pomodoro(element, target) {
this.element = element;
this.target = target;
};
Pomodoro.prototype.incrementer = function incrementer() {
// this takes care of break and section timers incrementing
this.element.click(function() {
breakTime++;
var el = this.target;
el.html(breakTime);
});
};
// end
Pomodoro.prototype.decrementer = function decrementer() {
// this takes care of break and section timers incrementing
breakerDec.element.click(function() {
breakTime--;
var el = breakerDec.target.html(breakTime);
});
};
// end
var breakerInc = new Pomodoro();
var ele = $("#inner1");
var tar = $("#par");
breakerInc.element = ele;
breakerInc.target = tar;
breakerInc.incrementer.bind(breakerInc);
//end
var breakerDec = new Pomodoro();
breakerDec.element = $("#inner2");
breakerDec.target = $("#par");
breakerDec.decrementer();
var sectionInc = new Pomodoro($("#inner3"), $("#par2"));
sectionInc.incrementer.bind(sectionInc);
});
and i am getting no result when i click the button.
this is the 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">
<title>Pomodoro Timer</title><!-- End of Title -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="div div-1"><p id="par" class="breaktime-1">5</p>
<div class="inner-div inner-1"><button id="inner1" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner2" type="button" class="btn">-</button></div>
</div>
<div class="div div-2"><p id="par2" class="breaktime">25</p>
<div class="inner-div inner-1"><button id="inner3" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner4" type="button" class="btn">-</button></div>
</div>
</div>
<div class="div div-3">
<h3 class="heading">section</h3>
<button type="button" class="btn-Start-Stop"></button
</div>
<div><p></p></div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Here is one (trimmed-down) solution just using vanilla javascript:
function changeValue() {
var breaktime = this.parentNode.getElementsByClassName('breaktime')[0];
var val = breaktime.innerHTML;
if (this.className === 'increment') {
val++;
}
else if (this.className === 'decrement') {
val--;
}
breaktime.innerHTML = val;
}
function startStop() {
var values = [];
var breaktimes = document.getElementsByClassName('breaktime');
breaktimes[1].classList.toggle('decrementing');
if (breaktimes[1].classList.contains('decrementing') === true) {
values[1] = parseInt(breaktimes[1].innerHTML);
values[1]--;
breaktimes[1].innerHTML = values[1];
var decrementer = setInterval(function(){
values[0] = parseInt(breaktimes[0].innerHTML);
values[1] = parseInt(breaktimes[1].innerHTML);
if (breaktimes[1].classList.contains('decrementing') !== true) {
clearInterval(decrementer);
}
values[1]--;
breaktimes[1].innerHTML = values[1];
if (values[1] === values[0]) {
window.alert('The counter has reached ' + values[1]);
clearInterval(decrementer);
}
}, 1000);
}
}
var buttons = document.getElementsByTagName('button');
var startStopButton = buttons[(buttons.length -1)];
for (var i = 0; (i+1) < buttons.length; i++) {
buttons[i].addEventListener('click',changeValue,false);
}
startStopButton.addEventListener('click',startStop,false);
<section>
<div>
<p class="breaktime">5</p>
<button id="inner1" type="button" class="increment">+</button>
<button id="inner2" type="button" class="decrement">-</button>
</div>
<div>
<p class="breaktime">25</p>
<button id="inner3" type="button" class="increment">+</button>
<button id="inner4" type="button" class="decrement">-</button>
</div>
<div>
<h3>Section</h3>
<button type="button" class="btn-Start-Stop">Start / Stop</button>
</div>
<div>
<p></p>
</div>
</section>
If you'd like to implement logic using constructors, you can bind events inside of initialization of your instance.
Here is reworked your code based on your html. But code could be improved, so Pomodoro instance can be able not only to decrease or increase, but do both functions.
Also some template engine can give you ability to easy define amount of increase/decrease blocks you want to add to your page.

Categories