Inverting slider scale on pie chart - javascript

I'm trying to create this pie chart where by changing the slider, the slice increases or decreases and then the "Perda na carteira" section will increase or decrease, respectively.
Basically, when all sliders are on "Perda potencial 100%", the "Perda na carteira" should also be at 100%. I've tried using direction: rtl, but this simply changes the slider to go from right to left and doesn't actually change the values.
Thank you in advance!
/************** Canvas ***************/
let myCanvas = document.getElementById("myCanvas");
myCanvas.width = 300;
myCanvas.height = 300;
var ctx = myCanvas.getContext("2d"),
val;
/************** Slider Variables ***************/
//Gruen
var sliderGruen = document.getElementById("gruen");
var outputGruen = document.getElementById("gruenValue");
outputGruen.innerHTML = "Perda potencial" + " " + sliderGruen.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderGruen.oninput = function () {
outputGruen.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Gelb
var sliderGelb = document.getElementById("gelb");
var outputGelb = document.getElementById("gelbValue");
outputGelb.innerHTML = "Perda potencial" + " " + sliderGelb.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderGelb.oninput = function () {
outputGelb.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Rot
var sliderRot = document.getElementById("rot");
var outputRot = document.getElementById("rotValue");
outputRot.innerHTML = "Perda potencial" + " " + sliderRot.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderRot.oninput = function () {
outputRot.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Magenta
var sliderMagenta = document.getElementById("magenta");
var outputMagenta = document.getElementById("magentaValue");
outputMagenta.innerHTML = "Perda potencial" + " " + sliderMagenta.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderMagenta.oninput = function () {
outputMagenta.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Blau
var sliderBlau = document.getElementById("blau");
var outputBlau = document.getElementById("blauValue");
outputBlau.innerHTML = "Perda potencial" + " " + sliderBlau.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderBlau.oninput = function () {
outputBlau.innerHTML = "Perda potencial" + " " + this.value + "%";
};
/************** Utility Functions ***************/
function changeColoursData() {
var colours = {
"Gruen": parseInt(sliderGruen.value),
"Gelb": parseInt(sliderGelb.value),
"Red": parseInt(sliderRot.value),
"Magenta": parseInt(sliderMagenta.value),
"Blau": parseInt(sliderBlau.value),
"Cyan": parseInt(100 - (parseInt(sliderGruen.value) / 5) - (parseInt(sliderGelb.value) / 5) - (parseInt(sliderRot.value) / 5) - (parseInt(sliderMagenta.value) / 5) - (parseInt(sliderBlau.value) / 5))
};
var outputCyan = document.getElementById("cyanValue");
outputCyan.innerHTML = colours.Cyan + " " + "%";
return colours;
}
function drawPieSlice(ctx, centerX, centerY, radius, startAngle, endAngle, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fill();
}
/************** Piechart Object ***************/
var Piechart = function (options) {
this.options = options;
this.canvas = options.canvas;
this.ctx = this.canvas.getContext("2d");
this.colors = options.colors;
this.draw = function () {
var total_value = 0;
var color_index = 0;
for (var categ in this.options.data) {
val = this.options.data[categ];
total_value += val;
}
var start_angle = 0;
for (categ in this.options.data) {
val = this.options.data[categ];
var slice_angle = 2 * Math.PI * val / total_value;
drawPieSlice(
this.ctx,
this.canvas.width / 2,
this.canvas.height / 2,
Math.min(this.canvas.width / 2, this.canvas.height / 2),
start_angle,
start_angle + slice_angle,
this.colors[color_index % this.colors.length]
);
start_angle += slice_angle;
color_index++;
}
};
};
/************** Initialize code and draw pie chart ***************/
function refreshPiechart() {
var myPiechart = new Piechart(
{
canvas: myCanvas,
data: changeColoursData(),
colors: ["#00A878", "#FFEA65", "#86CDC5", "#53131E", "#246EB9", "#FF5964"]
//colours : gruen, gelb, rot, magenta, blau,cyan
}
);
myPiechart.draw();
}
refreshPiechart();
<style>
body {
background-color: #EDDDD4;
}
.content {
width: 100%;
overflow-y: scroll;
overflow-x: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.slider1 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #00A878;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider2 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #FFEA65;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider3 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #86CDC5;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider4 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #53131E;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider5 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #246EB9;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider1::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider2::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider3::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider4::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider5::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
ul {
width: 100%;
}
li {
list-style: none;
}
.title {
float: left;
}
h5 {
float: right;
width: 31%;
display: inline;
margin-right: 0px;
font-family: Arial, Helvetica, sans-serif;
}
h4 {
float: right;
width: 60%;
display: inline;
margin-right: 5px;
font-family: Arial, Helvetica, sans-serif;
}
canvas {
margin-right: 10px;
background: #EDDDD4;
}
</style>
<!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>Document</title>
</head>
<body>
<div class="content">
<canvas id="myCanvas">
</canvas>
<li>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: TSLA</h5>
<h5 id="gruenValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider1" id="gruen"
onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: MSFT</h5>
<h5 id="gelbValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider2" id="gelb"
onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: AAPL</h5>
<h5 id="rotValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider3" id="rot"
onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: HOOD</h5>
<h5 id="magentaValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider4" id="magenta"
onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: MRNA</h5>
<h5 id="blauValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider5" id="blau"
onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h4 class="title">Perda na carteira:</h4>
<h5 id="cyanValue">
</h1>
</div>
</ul>
</li>
</div>
</div>
</body>
</html>

Simple way is to subtract colours.Cyan from 100 and display it.
/************** Canvas ***************/
let myCanvas = document.getElementById("myCanvas");
myCanvas.width = 300;
myCanvas.height = 300;
var ctx = myCanvas.getContext("2d"),
val;
/************** Slider Variables ***************/
//Gruen
var sliderGruen = document.getElementById("gruen");
var outputGruen = document.getElementById("gruenValue");
outputGruen.innerHTML = "Perda potencial" + " " + sliderGruen.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderGruen.oninput = function() {
outputGruen.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Gelb
var sliderGelb = document.getElementById("gelb");
var outputGelb = document.getElementById("gelbValue");
outputGelb.innerHTML = "Perda potencial" + " " + sliderGelb.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderGelb.oninput = function() {
outputGelb.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Rot
var sliderRot = document.getElementById("rot");
var outputRot = document.getElementById("rotValue");
outputRot.innerHTML = "Perda potencial" + " " + sliderRot.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderRot.oninput = function() {
outputRot.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Magenta
var sliderMagenta = document.getElementById("magenta");
var outputMagenta = document.getElementById("magentaValue");
outputMagenta.innerHTML = "Perda potencial" + " " + sliderMagenta.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderMagenta.oninput = function() {
outputMagenta.innerHTML = "Perda potencial" + " " + this.value + "%";
};
//Blau
var sliderBlau = document.getElementById("blau");
var outputBlau = document.getElementById("blauValue");
outputBlau.innerHTML = "Perda potencial" + " " + sliderBlau.value + "%"; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
sliderBlau.oninput = function() {
outputBlau.innerHTML = "Perda potencial" + " " + this.value + "%";
};
/************** Utility Functions ***************/
function changeColoursData() {
var colours = {
"Gruen": parseInt(sliderGruen.value),
"Gelb": parseInt(sliderGelb.value),
"Red": parseInt(sliderRot.value),
"Magenta": parseInt(sliderMagenta.value),
"Blau": parseInt(sliderBlau.value),
"Cyan": parseInt(100 - (parseInt(sliderGruen.value) / 5) - (parseInt(sliderGelb.value) / 5) - (parseInt(sliderRot.value) / 5) - (parseInt(sliderMagenta.value) / 5) - (parseInt(sliderBlau.value) / 5))
};
var outputCyan = document.getElementById("cyanValue");
var invertedOutputCyan = 100 - colours.Cyan;
outputCyan.innerHTML = invertedOutputCyan + " " + "%";
return colours;
}
function drawPieSlice(ctx, centerX, centerY, radius, startAngle, endAngle, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fill();
}
/************** Piechart Object ***************/
var Piechart = function(options) {
this.options = options;
this.canvas = options.canvas;
this.ctx = this.canvas.getContext("2d");
this.colors = options.colors;
this.draw = function() {
var total_value = 0;
var color_index = 0;
for (var categ in this.options.data) {
val = this.options.data[categ];
total_value += val;
}
var start_angle = 0;
for (categ in this.options.data) {
val = this.options.data[categ];
var slice_angle = 2 * Math.PI * val / total_value;
drawPieSlice(
this.ctx,
this.canvas.width / 2,
this.canvas.height / 2,
Math.min(this.canvas.width / 2, this.canvas.height / 2),
start_angle,
start_angle + slice_angle,
this.colors[color_index % this.colors.length]
);
start_angle += slice_angle;
color_index++;
}
};
};
/************** Initialize code and draw pie chart ***************/
function refreshPiechart() {
var myPiechart = new Piechart({
canvas: myCanvas,
data: changeColoursData(),
colors: ["#00A878", "#FFEA65", "#86CDC5", "#53131E", "#246EB9", "#FF5964"]
//colours : gruen, gelb, rot, magenta, blau,cyan
});
myPiechart.draw();
}
refreshPiechart();
<style>body {
background-color: #EDDDD4;
}
.content {
width: 100%;
overflow-y: scroll;
overflow-x: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.slider1 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #00A878;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider2 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #FFEA65;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider3 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #86CDC5;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider4 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #53131E;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider5 {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #246EB9;
outline: none;
opacity: 1;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider1::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider2::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider3::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider4::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider5::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border: solid black 0.15em;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #FAF6EB;
cursor: pointer;
}
ul {
width: 100%;
}
li {
list-style: none;
}
.title {
float: left;
}
h5 {
float: right;
width: 31%;
display: inline;
margin-right: 0px;
font-family: Arial, Helvetica, sans-serif;
}
h4 {
float: right;
width: 60%;
display: inline;
margin-right: 5px;
font-family: Arial, Helvetica, sans-serif;
}
canvas {
margin-right: 10px;
background: #EDDDD4;
}
</style>
<!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>Document</title>
</head>
<body>
<div class="content">
<canvas id="myCanvas">
</canvas>
<li>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: TSLA</h5>
<h5 id="gruenValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider1" id="gruen" onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: MSFT</h5>
<h5 id="gelbValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider2" id="gelb" onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: AAPL</h5>
<h5 id="rotValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider3" id="rot" onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: HOOD</h5>
<h5 id="magentaValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider4" id="magenta" onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h5 class="title">Quota: 20%</h5>
<h5 class="title">Ativo: MRNA</h5>
<h5 id="blauValue">
</h1>
<input type="range" min="0" max="100" value="0" class="slider5" id="blau" onChange="refreshPiechart();">
</div>
</ul>
<ul>
<div id="slidecontainer">
<h4 class="title">Perda na carteira:</h4>
<h5 id="cyanValue">
</h1>
</div>
</ul>
</li>
</div>
</div>
</body>
</html>

Related

How to make my javascript change only my div background color and not the full body color?

I found this awesome video to make a music player on html:
https://www.youtube.com/watch?v=oscPp3KghS8
The only problem is that the script changes the whole body's background and not just the .player's or the .music-player-container's background color. I have absolutely no experience whatsoever with javascript so I have no idea how to solve this problem...
Ideally I'd love the script to change only .music-player-container's background (which will also "change" the player's background color as it's transparent).
let now_playing = document.querySelector('.now-playing');
let track_art = document.querySelector('.track-art');
let track_name = document.querySelector('.track-name');
let track_artist = document.querySelector('.track-artist');
let playpause_btn = document.querySelector('.playpause-track');
let next_btn = document.querySelector('.next-track');
let prev_btn = document.querySelector('.prev-track');
let seek_slider = document.querySelector('.seek_slider');
let volume_slider = document.querySelector('.volume_slider');
let curr_time = document.querySelector('.current-time');
let total_duration = document.querySelector('.total-duration');
let wave = document.getElementById('wave');
let randomIcon = document.querySelector('.fa-random');
let curr_track = document.createElement('audio');
let track_index = 0;
let isPlaying = false;
let isRandom = false;
let updateTimer;
const music_list = [
{
img : 'images/image1.jpg',
name : 'Tokyo By Night',
artist : 'Depression',
music : 'musiques/tokyo-by-night.mp3'
},
{
img : 'images/image2.png',
name : 'Caramelldansen',
artist : 'Caramell',
music : 'musiques/caramelldansen.mp3'
},
{
img : 'images/image3.jpg',
name : 'Angel',
artist : 'Depression',
music : 'musiques/angel.mp3'
},
{
img : 'images/image4.jpg',
name : 'Little Dark Age',
artist : 'Mgmt',
music : 'musiques/little-dark-age.mp3'
},
];
loadTrack(track_index);
function loadTrack(track_index){
clearInterval(updateTimer);
reset();
curr_track.src = music_list[track_index].music;
curr_track.load();
track_art.style.backgroundImage = "url(" + music_list[track_index].img + ")";
track_name.textContent = music_list[track_index].name;
track_artist.textContent = music_list[track_index].artist;
now_playing.textContent = "Playing music " + (track_index + 1) + " of " + music_list.length;
updateTimer = setInterval(setUpdate, 1000);
curr_track.addEventListener('ended', nextTrack);
random_bg_color();
}
function random_bg_color(){
let hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e'];
let a;
function populate(a){
for(let i=0; i<6; i++){
let x = Math.round(Math.random() * 14);
let y = hex[x];
a += y;
}
return a;
}
let Color1 = populate('#');
let Color2 = populate('#');
var angle = 'to right';
let gradient = 'linear-gradient(' + angle + ',' + Color1 + ', ' + Color2 + ")";
document.body.style.background = gradient;
}
function reset(){
curr_time.textContent = "00:00";
total_duration.textContent = "00:00";
seek_slider.value = 0;
}
function randomTrack(){
isRandom ? pauseRandom() : playRandom();
}
function playRandom(){
isRandom = true;
randomIcon.classList.add('randomActive');
}
function pauseRandom(){
isRandom = false;
randomIcon.classList.remove('randomActive');
}
function repeatTrack(){
let current_index = track_index;
loadTrack(current_index);
playTrack();
}
function playpauseTrack(){
isPlaying ? pauseTrack() : playTrack();
}
function playTrack(){
curr_track.play();
isPlaying = true;
track_art.classList.add('rotate');
wave.classList.add('loader');
playpause_btn.innerHTML = '<i class="fa fa-pause-circle fa-5x"></i>';
}
function pauseTrack(){
curr_track.pause();
isPlaying = false;
track_art.classList.remove('rotate');
wave.classList.remove('loader');
playpause_btn.innerHTML = '<i class="fa fa-play-circle fa-5x"></i>';
}
function nextTrack(){
if(track_index < music_list.length - 1 && isRandom === false){
track_index += 1;
}else if(track_index < music_list.length - 1 && isRandom === true){
let random_index = Number.parseInt(Math.random() * music_list.length);
track_index = random_index;
}else{
track_index = 0;
}
loadTrack(track_index);
playTrack();
}
function prevTrack(){
if(track_index > 0){
track_index -= 1;
}else{
track_index = music_list.length -1;
}
loadTrack(track_index);
playTrack();
}
function seekTo(){
let seekto = curr_track.duration * (seek_slider.value / 100);
curr_track.currentTime = seekto;
}
function setVolume(){
curr_track.volume = volume_slider.value / 100;
}
function setUpdate(){
let seekPosition = 0;
if(!isNaN(curr_track.duration)){
seekPosition = curr_track.currentTime * (100 / curr_track.duration);
seek_slider.value = seekPosition;
let currentMinutes = Math.floor(curr_track.currentTime / 60);
let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60);
let durationMinutes = Math.floor(curr_track.duration / 60);
let durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60);
if(currentSeconds < 10) {currentSeconds = "0" + currentSeconds; }
if(durationSeconds < 10) { durationSeconds = "0" + durationSeconds; }
if(currentMinutes < 10) {currentMinutes = "0" + currentMinutes; }
if(durationMinutes < 10) { durationMinutes = "0" + durationMinutes; }
curr_time.textContent = currentMinutes + ":" + currentSeconds;
total_duration.textContent = durationMinutes + ":" + durationSeconds;
}
}
.player {
font-family: Arial, Helvetica, sans-serif;
height: 95vh;
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
color: white;
}
.wrapper {
border: 1px solid transparent;
padding: 30px;
border-radius: 20px;
box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px,
rgba(0, 0, 0, 0.22) 0px 15px 12px;
}
.details {
display: flex;
align-items: center;
flex-direction: column;
justify-content: center;
}
.track-art {
margin: 25px;
height: 250px;
width: 250px;
border: 2px solid #fff;
background-size: cover;
background-position: center;
border-radius: 50%;
-moz-box-shadow: 0px 6px 5px #ccc;
-webkit-box-shadow: 0px 6px 5px #ccc;
box-shadow: 0px 6px 5px #ccc;
-moz-border-radius: 190px;
-webkit-border-radius: 190px;
border-radius: 190px;
}
.now-playing {
font-size: 1rem;
}
.track-name {
font-size: 2.5rem;
}
.track-artist {
margin-top: 5px;
font-size: 1.5rem;
}
.buttons {
display: flex;
flex-direction: row;
align-items: center;
margin-bottom: 30px;
}
.active {
color: black;
}
.repeat-track,
.random-track,
.playpause-track,
.prev-track,
.next-track {
padding: 25px;
opacity: 0.8;
transition: opacity 0.2s;
}
.repeat-track:hover,
.random-track:hover,
.playpause-track:hover,
.prev-track:hover,
.next-track:hover {
opacity: 1;
}
.slider_container {
display: flex;
justify-content: center;
align-items: center;
}
.seek_slider,
.volume_slider {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
height: 5px;
background: #83a9ff;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
}
.seek_slider::-webkit-slider-thumb,
.volume_slider::-webkit-slider-thumb {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 15px;
height: 15px;
background: white;
border: 3px solid #3774ff;
cursor: pointer;
border-radius: 100%;
}
.seek_slider:hover,
.volume_slider:hover {
opacity: 1;
}
.seek_slider {
width: 60%;
}
.volume_slider {
width: 30%;
}
.current-time,
.total-duration {
padding: 10px;
}
i.fa-volume-down,
i.fa-volume-up {
padding: 10px;
}
i,
i.fa-play-circle,
i.fa-pause-circle,
i.fa-step-forward,
i.fa-step-backward {
cursor: pointer;
}
.randomActive {
color: black;
}
.rotate {
animation: rotation 8s infinite linear;
}
#keyframes rotation {
from {
transform: rotate(0deg);
}
to {
transform: rotate(359deg);
}
}
.loader {
height: 70px;
display: flex;
justify-content: center;
align-items: center;
}
.loader .stroke {
background: #f1f1f1;
height: 150%;
width: 10px;
border-radius: 50px;
margin: 0px 5px;
animation: animate 1.4s linear infinite;
}
#keyframes animate {
50% {
height: 20%;
background: #4286f4;
}
100% {
height: 100%;
}
}
.stroke:nth-child(1) {
animation-delay: 0s;
}
.stroke:nth-child(2) {
animation-delay: 0.3s;
}
.stroke:nth-child(3) {
animation-delay: 0.6s;
}
.stroke:nth-child(4) {
animation-delay: 0.9s;
}
.stroke:nth-child(5) {
animation-delay: 0.6s;
}
.stroke:nth-child(6) {
animation-delay: 0.3s;
}
.stroke:nth-child(7) {
animation-delay: 0s;
}
<!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>Music Player</title>
<link rel="stylesheet" href="music-player.css">
<script src="script.js" defer></script>
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="music-player-container">
<div class="player">
<div class="wrapper">
<div class="details">
<div class="now-playing">PLAYING x OF y</div>
<div class="track-art"></div>
<div class="track-name">Track Name</div>
<div class="track-artist">Track Artist</div>
</div>
<div class="slider_container">
<div class="current-time">00:00</div>
<input type="range" min="1" max="100" value="0" class="seek_slider" onchange="seekTo()">
<div class="total-duration">00:00</div>
</div>
<div class="slider_container">
<i class="fa fa-volume-down"></i>
<input type="range" min="0" max="100" value="25" class="volume_slider" onchange="setVolume()">
<i class="fa fa-volume-up"></i>
</div>
<div class="buttons">
<div class="random-track" onclick="randomTrack()">
<i class="fas fa-random fa-2x" title="random"></i>
</div>
<div class="prev-track" onclick="prevTrack()">
<i class="fa fa-step-backward fa-2x"></i>
</div>
<div class="playpause-track" onclick="playpauseTrack()">
<i class="fa fa-play-circle fa-5x"></i>
</div>
<div class="next-track" onclick="nextTrack()">
<i class="fa fa-step-forward fa-2x"></i>
</div>
<div class="repeat-track" onclick="repeatTrack()">
<i class="fa fa-repeat fa-2x" title="repeat"></i>
</div>
</div>
<div id="wave">
<span class="stroke"></span>
<span class="stroke"></span>
<span class="stroke"></span>
<span class="stroke"></span>
<span class="stroke"></span>
<span class="stroke"></span>
<span class="stroke"></span>
</div>
</div>
</div>
</div>
</body>
</html>
Kindly replace this code document.body.style.background = gradient;
with this document.querySelector('.music-player-container').style.background = gradient.

I have a button and I only want it to be pressed with a left click not enter key

I have a button in my site which is a simple aim trainer and you should click the button with left click. Everything works like a charm but if you click the button and hold it, then you hold enter, you can click 303 times in 10secs and that is cheating. I want it to only be pressed with left click. Explain your answer please.
Link to the site: https://mfa-aim-trainer.netlify.app
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change() {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
body {
margin: 0px;
padding: 0px;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>
I recommend checking the event.pointerId variable when the click occurs.
b.addEventListener('click', change);
const change = (event) => {
if(event.pointerId === -1) {
// this is a "keyboard click" that you want to avoid
}
else {
// actual click
}
};
When the mouse is used, the pointerId should be non-negative. When the keyboard is used to "click," the ID will be -1.
If I understand correctly, you want to stop an edge case where users can hold down enter and the left mouse button as they will keep scoring.
I would recommend listening for the enter key using the keydown and keyup events to track when enter is pressed then using the state to disable any logic while it is pressed.
let isEnterPressed = false
window.addEventListener("keydown", e => {
if(e.keyCode === 13)
isEnterPressed = true // 13 is keycode for enter
})
window.addEventListener("keyup", e => {
if(e.keyCode === 13)
isEnterPressed = false // 13 is keycode for enter
})
then just use isEnterPressed to block any logic triggered by clicking.
This is just a simple example, you could generalize this to track any keyboard input
You can use keypress listener on the button and preventDefault() when the enter triggers on the button priventDefault() will stop that
var b = document.querySelector("button");
var score = document.getElementById('score');
var counter = 0;
var btn = document.getElementById("button");
var tensec = document.getElementById("10sec");
var pxs = document.getElementsByClassName('div');
var scr = document.getElementById("scr");
var mis = document.getElementById("mis");
var htm = document.getElementById("htm");
var missc = 0;
var height1 = 100;
var width1 = 100;
var theLeftSide = document.getElementById("theLeftSide");
var resetbtn = document.getElementById("reset");
var vr = document.getElementById("vr");
var hit = 1080;
var fontsize = 25;
var ulcls = document.getElementsByClassName("theul");
var ul = document.getElementById('10sec');
var best = document.getElementById("best");
var cntrspn = document.getElementsByClassName("cntrspn");
var lists = document.getElementsByClassName("lists");
b.addEventListener("click", change);
b.addEventListener("click", plus);
htm.addEventListener("click", miss);
pxs[0].addEventListener("click", plussize);
pxs[1].addEventListener("click", minesize);
theLeftSide.addEventListener("click", leftsclick);
b.addEventListener("click", misscmines);
resetbtn.addEventListener("click", resetall);
function plussize() {
height1 += 10;
width1 += 10;
missc++
missc + 1
missc--
fontsize += 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function minesize() {
height1 -= 10;
width1 -= 10;
missc++
missc + 1
missc--
fontsize -= 3;
b.style.fontSize = fontsize + "px";
b.style.height = height1 + "px";
b.style.width = width1 + "px";
missc - 1;
}
function miss() {
missc++
mis.innerHTML = missc - counter;
}
setInterval(function() {
var misc = missc - counter;
ul.style.height = window.offsetheight;
var currscr = counter;
for (var i = 0; i < cntrspn.length; i += 1) {
if (parseInt(scr.textContent) > parseInt(best.textContent)) {
best.textContent = scr.textContent;
} else {
console.log("no new best");
}
}
mis.textContent = missc - counter;
ul.innerHTML += '<li class="lists">' + '<span class="cntrspn">' + counter + '</span>' + "-" + misc + '</li>';
missc = 0;
misc = 0;
counter = 0;
scr.textContent = counter;
mis.textContent = missc;
}, 10000);
function change(e) {
var i = Math.floor(Math.random() * 1500) + 1;
var j = Math.floor(Math.random() * 250) + 1;
var r = Math.floor(Math.random() * -1100) + 1;
b.style.padding = 0 + "px";
b.style.left = i + "px";
b.style.top = j + "px";
b.style.right = r + "px";
}
function plus() {
missc--
missc - 1
counter++;
scr.textContent = counter;
}
function leftsclick() {
missc--
missc - 1
}
function misscmines() {
missc++
missc + 1
}
function resetall() {
window.location.reload(true);
}
b.addEventListener("keypress", e => {
let key = e.keyCode || e.charCode;
if (key == 13) {
e.stopPropagation();
e.preventDefault();
}
})
body {
margin: 0px;
padding: 0px;
}
button{
outline: none;
}
.btn {
position: relative;
height: 125px;
width: 125px;
border-radius: 10px;
display: block;
background-color: whitesmoke;
font-size: 20px;
text-align: center;
user-select: none;
font-family: 'Roboto Mono', monospace;
}
.btn:hover {
background-color: #dcdcdc;
border-color: #dcdcdc;
}
.btndiv {
display: grid;
gap: 10px;
top: 5px;
left: 200px;
width: 1724px;
position: fixed;
user-select: none;
}
.sizes {
width: 80px;
height: auto;
color: white;
background-color: #2f2f2f;
cursor: pointer;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
padding-left: 5px;
user-select: none;
}
.score {
font-family: 'Roboto Mono', monospace;
color: white;
font-size: 30px;
white-space: nowrap;
user-select: none
}
.shr7 {
font-size: 20px;
font-family: 'Roboto Mono', monospace;
left: 100px;
color: white;
left: 49%;
padding-left: 5px;
user-select: none
}
.allcont {
display: grid;
grid-template-columns: repeat(25, 1fr);
gap: 10px;
padding-left: 5px;
}
.theLeftSide {
width: 190px;
display: block;
height: 100vh;
background-color: #2f2f2f;
border-right: 6px solid #464646;
overflow-y: auto;
overflow-x: hidden;
}
.theul {
background-color: #2f2f2f;
color: white;
width: 150px;
margin-bottom: 0px;
font-family: 'Roboto Mono', monospace;
border-right: solid 6px #464646;
display: block;
}
li {
font-family: 'Roboto Mono', monospace;
font-size: 15px;
color: white;
user-select: none;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-thumb {
border-radius: 10px;
background-color: #2a2a2a;
}
::-webkit-scrollbar-thumb:hover {
background-color: #252525;
}
<!DOCTYPE html>
<html id="htm" style="font-family: 'Roboto Mono', monospace; user-select: none;">
<head>
<meta charset="utf-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght#300&display=swap" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="icons\icon.png">
<link rel="stylesheet" type="text/css" href="aimcss.css">
<div class="btndiv"><button id="btn" class="btn"><b>Click me</b></button></div>
<div id="theLeftSide" class="theLeftSide">
<div id="pxs" class="sizes div">+ 10px</div>
<div id="pxs" class="sizes div">- 10px</div>
<div class="allcont">
<p id="score" class="score">score:
<p id="scr" class="score">0</p>
</p>
<title>Aim trainer</title>
</div>
<div class="allcont">
<p id="misses" class="score">misses:
<p id="mis" class="score">0</p>
</p>
</div>
<br onscroll="func()">
<div class="allcont" id="bestdiv">
<p class="score">Best:
<p class="score" id="best">0</p>
</p>
</div>
<br>
<div style=" padding-left: 5px;"><button style="height: 30px; width: 70px; font-size: 15px; font-family: 'Roboto Mono', monospace;" id="reset"><b>RESET</b></button></div>
<br><br>
<p type="inherit" class="shr7">• Score-Misses</p>
<ol start="1" id='10sec' class='theul'>
<li style="display: none;" class="lists"><span class="cntrspn">0</span>-0</li>
</ol>
</div>
</head>
<body id="bod" style="background-color: #181818;">
<script type="text/javascript" src="aimscript.js">
</script>
</body>
</html>

Calculation Slider to increase after certain number

I have a slider that calculates (x * y) * 35. I want to make it so if (x * y) = >200 then it should be:
(x * y) * 35 + 5
But the calculations should only come after 200. For example:
x = 1
y = 50
z = 1750
x = 1
y = 200
z = 7000
x = 1
y = 201
z = 7040
So basically the number should increase by 35 until x * y = >200, then it should increase by 40.
This is my code:
html
<div class="slidecontainer">
<p>Elever: <span id="saleprice"></span></p>
<input type="range" min="0" max="100" value="1" class="slider" id="sale">
</div>
<div class="slidecontainer">
<p>Paket sålda: <span id="commission"></span></p>
<input type="range" min="0" max="200" value="1" class="slider" id="commission_range" step="1">
</div>
<div class="outputbox">
<p>Totalt: <span id="total_commission" ></span>:-</p>
</div>
css
.slidecontainer {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.outputbox p{
padding-top:20px;
font-size:30px;
font-family: Dosis;
}
.slidecontainer p{
font-size: 25px;
font-family: Dosis;
}
JS
<script>
var comslider = document.getElementById("sale");
var comoutput = document.getElementById("saleprice");
var salep = document.getElementById("saleprice");
var comp = document.getElementById("commission");
var totalout = document.getElementById("total_commission");
var slider = document.getElementById("commission_range");
var output = document.getElementById("commission");
comoutput.innerHTML = comslider.value; // Display the default slider value
output.innerHTML = slider.value; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
comslider.oninput = function() {
comoutput.innerHTML = this.value;
calcTotalCommission();
}
// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
output.innerHTML = this.value;
calcTotalCommission();
}
// Update the totalCommision number with current values
function calcTotalCommission(price, percentage) {
var total = parseInt(salep.innerHTML) * (parseFloat(comp.innerHTML) * 35);
totalout.innerHTML = total.toFixed(0);
}
</script>
Add an IF check after getting the total. If total is greater than 200, then run function again with multiple of 40, otherwise if not greater than 200 server total as normal.
var comslider = document.getElementById("sale");
var comoutput = document.getElementById("saleprice");
var salep = document.getElementById("saleprice");
var comp = document.getElementById("commission");
var totalout = document.getElementById("total_commission");
var slider = document.getElementById("commission_range");
var output = document.getElementById("commission");
comoutput.innerHTML = comslider.value; // Display the default slider value
output.innerHTML = slider.value; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
comslider.oninput = function() {
comoutput.innerHTML = this.value;
calcTotalCommission();
}
// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
output.innerHTML = this.value;
calcTotalCommission();
}
// Update the totalCommision number with current values
function calcTotalCommission(price, percentage) {
var total = parseInt(salep.innerHTML) * (parseFloat(comp.innerHTML) * 35);
// Check if total is greater than 200 and get new total if so
if (total > 200) {
total = parseInt(salep.innerHTML) * (parseFloat(comp.innerHTML) * 40);
}
totalout.innerHTML = total.toFixed(0);
}
.slidecontainer {
width: 100%;
}
.slider {
-webkit-appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.outputbox p {
padding-top: 20px;
font-size: 30px;
font-family: Dosis;
}
.slidecontainer p {
font-size: 25px;
font-family: Dosis;
}
<div class="slidecontainer">
<p>Elever: <span id="saleprice"></span></p>
<input type="range" min="0" max="100" value="1" class="slider" id="sale">
</div>
<div class="slidecontainer">
<p>Paket sålda: <span id="commission"></span></p>
<input type="range" min="0" max="200" value="1" class="slider" id="commission_range" step="1">
</div>
<div class="outputbox">
<p>Totalt: <span id="total_commission"></span>:-</p>
</div>

Unable to reset JavaScript bar graph

I have a bar graph created in JavaScript to display values using colors. I am having trouble resetting the bar graph. Basically what needs to happen is when the "reset" button is clicked, all bars clear values and reset to "0". Then the button needs to give the option to "Generate" and the previous values are shown again. Also, this is my first time using constant velocity to ease the bars up and down as the button is clicked to give it a little flair. Not sure what I am missing to have the data clear and be set to zero on the bottom line of the graph while using constant velocity to make it ease down and when button is clicked to restore the values to previous state. Any help is appreciated. Here is the code so far:
HTML
/*
* Some base values.
*/
var millisecondsPerFrame = 30;
/*
* Helper function for managing button event handlers.
*/
var setupButton = function(button, label, onclickHandler) {
button.value = label;
button.onclick = onclickHandler;
button.disabled = false;
};
var startConstantVelocityAnimation = function() {
// Grab the desired velocity.
var velocity = parseFloat(document.getElementById("chart").value);
// Grab the object to animate, and initialize if necessary.
var colors = document.getElementById("colors");
chart.style.bottom = chart.style.bottom || "0px";
// Start animating.
var intervalID = setInterval(function() {
var newBottom = parseInt(box.style.bottom) + velocity;
if ((newBottom < 0) || (newBottom > maxBottom)) {
velocity = -velocity;
} else {
chart.style.bottom = newBottom + "px";
}
}, millisecondsPerFrame);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"), "Reset", function() {
clearInterval(intervalID);
// Toggle the start button to stop animation.
setupButton(document.getElementById("Reset"),
"Generate", startConstantVelocityAnimation);
});
};
window.onload = function() {
// Set up the initial event handlers.
document.getElementById("Reset").onclick = startConstantVelocityAnimation;
};
**
* Graph JS Code ** *
function createBarChart(data) {
// Start with the container.
var chart = document.createElement("div");
// The container must have position: relative.
chart.style.position = "relative";
// The chart's height is the value of its largest
// data item plus a little margin.
var height = 0;
for (var i = 0; i < data.length; i += 1) {
height = Math.max(height, data[i].value);
}
chart.style.height = (height + 10) + "px";
// Give the chart a bottom border.
chart.style.borderBottomStyle = "solid";
chart.style.borderBottomWidth = "1px";
// Iterate through the data.
var barPosition = 0;
// We have a preset bar width for the purposes of this
// example. A full-blown chart module would make this
// customizable.
var barWidth = 48.30;
for (i = 0; i < data.length; i += 1) {
// Basic column setup.
var dataItem = data[i];
var bar = document.createElement("div");
bar.style.position = "absolute";
bar.style.left = barPosition + "px";
bar.style.width = barWidth + "px";
bar.style.backgroundColor = dataItem.color;
bar.style.height = dataItem.value + "px";
bar.style.borderStyle = "ridge";
bar.style.borderColor = dataItem.color;
// Visual flair with CSS Level 3 (for maximum compatibility
// we set multiple possible properties to the same value).
// Hardcoded values here just for illustration; a
// full module would allow major customizability.
bar.style.MozBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.WebkitBoxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.boxShadow = "rgba(128, 128, 128, 0.75) 0px 7px 12px";
bar.style.MozBorderRadiusTopleft = "8px";
bar.style.WebkitBorderTopLeftRadius = "8px";
bar.style.borderTopLeftRadius = "8px";
bar.style.MozBorderRadiusTopright = "8px";
bar.style.WebkitBorderTopRightRadius = "8px";
bar.style.borderTopRightRadius = "8px";
bar.style.backgroundImage =
"-moz-linear-gradient(" + dataItem.color + ", black)";
bar.style.backgroundImage =
"-webkit-gradient(linear, 0% 0%, 0% 100%," +
"color-stop(0, " + dataItem.color + "), color-stop(1, black))";
bar.style.backgroundImage =
"linear-gradient(" + dataItem.color + ", black)";
// Recall that positioning properties are treated *relative*
// to the corresponding sides of the containing element.
bar.style.bottom = "-1px";
chart.appendChild(bar);
// Move to the next bar. We provide an entire bar's
// width as space between columns.
barPosition += (barWidth * 2);
}
return chart;
};
window.onload = function() {
var colors = [{
color: "red",
value: 40
},
{
color: "blue",
value: 10
},
{
color: "green",
value: 100
},
{
color: "black",
value: 65
},
{
color: "yellow",
value: 75
},
{
color: "purple",
value: 120
},
{
color: "grey",
value: 121
},
{
color: "orange",
value: 175
},
{
color: "olive",
value: 220
},
{
color: "maroon",
value: 275
},
{
color: "brown",
value: 300
},
{
color: "teal",
value: 15
}
];
var chart = createBarChart(colors);
document.querySelector("#wrapper").appendChild(chart); // keeps chart inside wrapper div
};
#wrapper {
margin-left: auto;
margin-right: auto;
width: 85%;
border: groove;
border-color: white;
padding: 2px;
}
#loginwrap {
margin-left: auto;
margin-right: auto;
padding: 3px;
text-align: center;
}
body {
font-family: Georgia;
padding: 10px;
background: #f1f1f1;
font-weight: bold;
}
/* top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* three columns next to each other */
.column1 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
.column2 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #bbb;
}
.column3 {
float: left;
width: 30%;
padding: 15px;
height: 300px;
text-align: center;
background-color: #aaa;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Card-like background for each section */
.card {
background-color: white;
padding: 30px;
margin-top: 20px;
overflow: auto;
}
/* Align about section image to right */
.aboutimg {
float: right;
}
/* Footer */
.footer {
padding: 20px;
background: #ddd;
margin-top: 20px;
}
.copyright {
margin-right: auto;
margin-left: auto;
width: 85%;
text-align: center;
font-size: 10px;
padding: 5px;
}
/*Chart Color Legend*/
.legend .legend-scale ul {
margin: 0;
padding: 0;
float: left;
list-style: none;
}
.legend .legend-scale ul li {
display: block;
float: left;
width: 50px;
margin-bottom: 6px;
text-align: center;
font-size: 80%;
list-style: none;
}
.legend ul.legend-labels li span {
display: block;
float: left;
height: 15px;
width: 50px;
}
.legend a {
color: #777;
}
.subs {
font-size: 10px;
font-style: italic;
padding: 5px;
text-align: center;
}
.reset-button {
text-align: right;
padding-top: 2px;
padding-right: 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tissue: Titan Issue Tracking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Issue Tracking System" />
<meta name="author" content="S Morris">
<link rel="stylesheet" type="text/css" href="tissue.css">
<script src="js/animation.js"></script>
</head>
<body>
<div id="wrapper">
<h2>TISSUE: Sales Subscription Dashboard</h2>
<div class="topnav">
Home
Tracker Login
</div>
<div>
<div class="legend">
<div class="legend-scale">
<div class="reset-button">
<input type="button" value="Reset Graph" id="Reset">
</div>
<ul class="legend-labels">
<li><span></span>40</li>
<li><span></span>10</li>
<li><span></span>100</li>
<li><span></span>65</li>
<li><span></span>75</li>
<li><span></span>120</li>
<li><span></span>121</li>
<li><span></span>175</li>
<li><span></span>220</li>
<li><span></span>275</li>
<li><span></span>300</li>
<li><span></span>15</li>
</ul>
</div>
</div>
<div class="legend">
<div class="legend-scale">
<ul class="legend-labels">
<li><span style='background:red;'></span>Jan</li>
<li><span style='background:blue;'></span>Feb</li>
<li><span style='background:green;'></span>March</li>
<li><span style='background:black;'></span>Apr</li>
<li><span style='background:yellow;'></span>May</li>
<li><span style='background:purple;'></span>June</li>
<li><span style='background:grey;'></span>July</li>
<li><span style='background:orange;'></span>Aug</li>
<li><span style='background:olive;'></span>Sept</li>
<li><span style='background:maroon;'></span>Oct</li>
<li><span style='background:brown;'></span>Nov</li>
<li><span style='background:teal;'></span>Dec</li>
</ul>
</div>
</div>
<br><br><br><br>
<hr>
<div class="subs">***Subscribers in Thousands***</div>
<script src="js/subscriptions_graph.js"></script>
</div>
</div>
<div class="copyright">
Copyright © 2018 Titan Issue Tracker
</div>
</body>
</html>

JavaScript NaN issue on click

I have the following script at:
function rotateFoo(current) {
var angle = (current.data('angle') + 90);
current.data('angle', angle);
console.log('angle: ', angle);
current.css({
'transform': 'rotate(' + angle + 'deg)'
});
current.data('angle1', angle);
}
$(document).ready(function() {
function generateNumb() {
var start = [0, 90, 180, 270];
var start = start[Math.floor(Math.random() * 4)];
return start;
}
$('.foo').each(function() {
$(this).css({
'transform': 'rotate(' + generateNumb() + 'deg)'
});
});
$('.foo').on('click', function() {
rotateFoo($(this));
});
});
.wrapper {
width: 306px;
border: 3px solid black;
margin: 50px auto 0;
overflow: hidden;
}
.foo {
width: 100px;
height: 70px;
background-color: #faa;
transition: all .5s ease;
float: left;
cursor: pointer;
text-align: center;
padding-top: 30px;
border: 1px solid #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section class="wrapper">
<div class="foo">1</div>
<div class="foo">2</div>
<div class="foo">3</div>
<div class="foo">4</div>
<div class="foo">5</div>
<div class="foo">6</div>
<div class="foo">7</div>
<div class="foo">8</div>
<div class="foo">9</div>
</section>
<p>
</p>
it's a very simple puzzle game prototype. https://jsfiddle.net/dg0ugws1/70/
It starts with a random angle for each tile. However when I click on it I would like to rotate it by 90 degrees clockwise.
However my console.log is throwing this error:
angle: NaN
It's because on initial rotation you do not set any data('agle') to element and when clicking you get undefined + 90
function rotateFoo(current){
var angle = (current.data('angle') + 90);
current.data('angle', angle);
console.log('angle: ', current.data('angle'));
current.css({'transform': 'rotate(' + angle + 'deg)'});
current.data('angle1', angle);
}
$(document).ready(function(){
function generateNumb() {
var start = [0, 90, 180, 270];
var start = start[Math.floor(Math.random() * 4)];
return start;
}
$('.foo').each(function(){
var angle = generateNumb();
$(this).css({'transform': 'rotate(' + angle + 'deg)'}).data('angle', angle);
});
$('.foo').on('click', function(){
rotateFoo($(this));
});
});
body {
font-family: sans-serif;
}
button {
width: 180px;
height: 80px;
padding: 10px;
cursor: pointer;
font-size: 20px;
}
.wrapper {
width: 306px;
border: 3px solid black;
margin: 50px auto 0;
overflow: hidden;
}
.foo {
width:100px;
height:70px;
background-color:#faa;
transition: all .5s ease;
float: left;
cursor: pointer;
text-align: center;
padding-top: 30px;
border: 1px solid #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section class="wrapper">
<div class="foo">1</div>
<div class="foo">2</div>
<div class="foo">3</div>
<div class="foo">4</div>
<div class="foo">5</div>
<div class="foo">6</div>
<div class="foo">7</div>
<div class="foo">8</div>
<div class="foo">9</div>
</section>
<p>
</p>
you just need to change this
$('.foo').each(function(){
$(this).css({'transform': 'rotate(' + generateNumb() + 'deg)'});
});
with
$('.foo').each(function(){
var ang = generateNumb();
$(this).css({'transform': 'rotate(' + ang + 'deg)'});
$(this).data('angle', ang);
});
This way the angle value is set.

Categories

Resources