I am coding a (mp3) sample/jingle/sound player button.
The top row has 2 control buttons and a volume slider, pressing the section below will play the sound.
The first control button toggles loop mode on off (this is functioning as expected)
The second control button is supposed to toggle "play/pause" mode.
If play/pause mode is "on" and you press the button a second time (while it is playing) it should pause, the when you press a 3rd time should resume playing but instead currently, it restarts from the begining on second press. Where did I go wrong?
function playsound() {
var audiox = document.getElementById('playerx');
audiox.src = "http://glentertainment.keybit.co.uk/audiop2/22%20Air%20Horn%20Single.mp3";
var playmode = document.getElementById('playpauseorrapidpressonoff').innerText;
if (playmode != "off") {
if (audiox.paused) {
audiox.play()
} else {
audiox.pause()
}
} else {
audiox.play();
}
}
function setvolume() {
document.getElementById('playerx').volume = document.getElementById('ssvolume').value;
}
function playmodebuttonpressed() {
onoffcheck = document.getElementById('playpauseorrapidpressonoff').innerText;
if (onoffcheck != "off") {
document.getElementById('playpauseorrapidpress').style.backgroundColor = "grey";
document.getElementById('playpauseorrapidpressonoff').innerText = "off";
} else {
document.getElementById('playpauseorrapidpress').style.backgroundColor = "black";
document.getElementById('playpauseorrapidpressonoff').innerText = "on";
}
}
function repeatbuttonpressed() {
onoffcheck = document.getElementById('repeatbuttonpressed').innerText;
if (onoffcheck != "off") {
document.getElementById('loop').style.backgroundColor = "grey";
document.getElementById('repeatbuttonpressed').innerText = "off";
document.getElementById('playerx').loop = false;
} else {
document.getElementById('loop').style.backgroundColor = "black";
document.getElementById('repeatbuttonpressed').innerText = "on";
document.getElementById('playerx').loop = true;
}
}
.ssvolume {
transform: scale(0.8);
width: 60px;
position: absolute;
top: 0;
right: 0;
display: inline-block;
margin: 0;
padding: 0;
}
.singlesoundcontainer {
width: 100px;
height: 100px;
box-shadow: inset 0px 1px 0px 0px #a4e271;
background: linear-gradient(to bottom, #89c403 5%, #77a809 100%);
background-color: #89c403;
border: 1px solid #74b807;
border-radius: 5px;
display: block;
position: relative;
}
.singlesamplercontrols {
width: 100px;
height: 20px;
background-color: transparent;
border-radius: 5px 5px 0 0;
border: 0.1px solid black;
}
.ssrepeatbutton {
margin-top: 0px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: -4px;
padding: 0px;
background-color: grey;
display: inline-block;
width: 20px;
cursor: pointer;
}
.ssrepeatbutton:hover {
background-color: black;
}
.singlesamplertrigger {
width: 90px;
height: 69px;
cursor: pointer;
padding: 5px;
color: black;
border-radius: 0 0 5px 5px;
display: inline-block;
overflow: hidden;
background-color: transparent;
font-family: Arial;
font-weight: bold;
text-decoration: none;
text-shadow: 0px 1px 0px #528009;
font-size: 11.5px;
line-height: 10px;
border-bottom: 0.1px solid black;
border-left: 0.1px solid black;
border-right: 0.1px solid black;
-webkit-user-select: none;
/* Safari */
-moz-user-select: none;
/* Firefox */
-ms-user-select: none;
/* IE10+/Edge */
user-select: none;
/* Standard */
}
<div class="singlesoundcontainer">
<div class="singlesamplercontrols">
<img class="ssrepeatbutton" id="loop" onClick="repeatbuttonpressed();" src="https://www.bossdj.net/sampledeck/images/repeat-icon.png">
<span id="repeatbuttonpressed" style="display:none;">off</span>
<img class="ssrepeatbutton" id="playpauseorrapidpress" onClick="playmodebuttonpressed();" src="https://www.bossdj.net/sampledeck/images/playpausemode-icon.png">
<span id="playpauseorrapidpressonoff" style="display:none;">off</span>
<input class="ssvolume" type="range" id="ssvolume" min="0" max="1" value="1" step="0.01" onInput="setvolume();">
</div>
<div class="singlesamplertrigger" onClick="playsound();" id="singlesampler">Air Horn (Single)</div>
</div><br />
<!--Below audio element will be hidden in final code-->
<audio id="playerx" style="display: block; width: 280px" src="#" controls></audio>
You should initialise the src of the audio tag only once, and then just toggle the play/pause.
window.addEventListener('DOMContentLoaded', () => {
var audiox = document.getElementById('playerx');
audiox.src = "http://glentertainment.keybit.co.uk/audiop2/22%20Air%20Horn%20Single.mp3";
})
function playsound() {
var audiox = document.getElementById('playerx');
var playmode = document.getElementById('playpauseorrapidpressonoff').innerText;
if (playmode != "off") {
if (audiox.paused) {
audiox.play()
} else {
audiox.pause()
}
} else {
audiox.play();
}
}
Related
I have a toggle switch and everything was working perfectly, but as soon as I deleted and h1 element my switch started acting up. Orginally it would sit perfectly in the center of the slider, but now it is offset and stuck to the top. Once the button is clicked it returns to the position its suppose to be in. As soon as the page is refreshed it goes right back to being offset.
What am I doing wrong?
function SlideRight() {
// Checks to see if the slider is to the left of the div
if (document.getElementById("slider").style.float !== "right") {
// If it is we will float the sliderBtn to the right and change the background of the housing to green
document.getElementById("slider").style.float = "right";
document.getElementById("slideHousing").style.backgroundColor = "#00ff00";
// Toggle dark mode on
document.body.style.backgroundColor = "#595959";
document.getElementById("header").style.color = "#e6e6e6";
document.getElementById("press").style.color = "#e6e6e6";
} else {
// If clicked again the btn will move back to the left side and change the color back to original
document.getElementById("slider").style.float = "left";
document.getElementById("slideHousing").style.backgroundColor = "#f2f2f2";
// Toggle dark mode off
document.body.style.backgroundColor = "#e6e6e6";
document.getElementById("header").style.color = "#000";
document.getElementById("press").style.color = "#000";
}
}
body {
height: 100%;
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
html {
height: 100%;
}
.main {
display: table;
height: 100%;
width: 100%;
border: 1px solid transparent;
}
.container {
display: table-cell;
vertical-align: middle;
border: 1px solid transparent;
}
.slider {
height: 100px;
width: 200px;
border-radius: 50px;
background-color: #f2f2f2;
margin: 0 auto;
border: none;
box-shadow: inset 0 0 7px #000;
}
.slideBtn {
border: 1px solid transparent;
height: 90px;
margin-top: 4px;
margin-left: 5px;
margin-right: 5px;
width: 90px;
border-radius: 50px;
background-color: silver;
box-shadow: 0 0 5px #000;
}
<h1 style="text-align: center;" id="header">Dark Mode</h1>
<div class="main">
<div class="container">
<p style="text-align: center;" id="press">Press button to toggle dark mode.</p>
<div class="slider" id="slideHousing">
<div class="slideBtn" id="slider" onclick="SlideRight()">
</div>
</div>
</div>
</div>
You just need to set the initial value of float for the button.
function SlideRight() {
// Checks to see if the slider is to the left of the div
if (document.getElementById("slider").style.float !== "right") {
// If it is we will float the sliderBtn to the right and change the background of the housing to green
document.getElementById("slider").style.float = "right";
document.getElementById("slideHousing").style.backgroundColor = "#00ff00";
// Toggle dark mode on
document.body.style.backgroundColor = "#595959";
document.getElementById("header").style.color = "#e6e6e6";
document.getElementById("press").style.color = "#e6e6e6";
} else {
// If clicked again the btn will move back to the left side and change the color back to original
document.getElementById("slider").style.float = "left";
document.getElementById("slideHousing").style.backgroundColor = "#f2f2f2";
// Toggle dark mode off
document.body.style.backgroundColor = "#e6e6e6";
document.getElementById("header").style.color = "#000";
document.getElementById("press").style.color = "#000";
}
}
body {
height: 100%;
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
html {
height: 100%;
}
.main {
display: table;
height: 100%;
width: 100%;
border: 1px solid transparent;
}
.container {
display: table-cell;
vertical-align: middle;
border: 1px solid transparent;
}
.slider {
height: 100px;
width: 200px;
border-radius: 50px;
background-color: #f2f2f2;
margin: 0 auto;
border: none;
box-shadow: inset 0 0 7px #000;
}
.slideBtn {
float:left;
border: 1px solid transparent;
height: 90px;
margin-top: 4px;
margin-left: 5px;
margin-right: 5px;
width: 90px;
border-radius: 50px;
background-color: silver;
box-shadow: 0 0 5px #000;
}
<h1 style="text-align: center;" id="header">Dark Mode</h1>
<div class="main">
<div class="container">
<p style="text-align: center;" id="press">Press button to toggle dark mode.</p>
<div class="slider" id="slideHousing">
<div class="slideBtn" id="slider" onclick="SlideRight()">
</div>
</div>
</div>
</div>
I want to add a small player to my site to listen to music. I found a beautiful example that I liked and want to change and finish it a little.
Specifically, I want to add a button here to randomly play tracks.
To start, I add this button to the html:
<button type="submit" id="btn-random">
<i class="fas fa-random"></i>
</button>
Next, I add a check to the next track switching function, if the random button has an active class, then the tracks will play randomly:
else if (to == 'next') {
stop();
if (document.getElementById("btn-random").classList.contains("active")) {
let songs = document.getElementById("sourceUrl").length - 1;
let randomSong = Math.floor(Math.random() * songs) + 1;
} else {
currentSong = (++currentSong)%playlist.length;
}
playpause();
}
Next, it remains to make sure that when you click on the random button, the active class turns on and off. To do this, I make a onclick function for this button and implement it:
<button type="submit" id="btn-random" onclick="random()">
<i class="fas fa-random"></i>
</button>
//
var randomTrack = false;
function random() {
if (randomTrack) {
document.getElementById('btn-random').classList.add("active");
randomTrack = false;
}
else {
document.getElementById('btn-random').classList.remove("active");
randomTrack = true;
}
}
But in the end, when the random button has an active class and I try to switch the song, instead of a random track, the current track plays in a circle.
What could be the problem?
var song = new Audio;
var isStopped = true;
var currentSong = 0;
var playlist = [];
var playlistVisible = false;
var randomTrack = false;
function skip(to) {
if (to == 'prev') {
stop();
currentSong = (--currentSong)%playlist.length;
if (currentSong < 0) {
currentSong += playlist.length;
}
playpause();
}
else if (to == 'next') {
stop();
if (document.getElementById("btn-random").classList.contains("active")) {
let songs = document.getElementById("sourceUrl").length - 1;
let randomSong = Math.floor(Math.random() * songs) + 1;
} else {
currentSong = (++currentSong)%playlist.length;
}
playpause();
}
}
function playpause() {
if (!song.paused) {
song.pause();
document.getElementById("glow").classList.add("disable-animation");
}
else if (playlist.length == 0){
togglePlaylist();
}
else {
if (isStopped) {
song.src = playlist[currentSong];
}
song.play();
songFile = playlist[currentSong].split("/");
songName = document.getElementById("songName");
songName.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
document.getElementById("glow").classList.remove("disable-animation");
isStopped = false;
}
}
function random() {
if (randomTrack) {
document.getElementById('btn-random').classList.add("active");
randomTrack = false;
}
else {
document.getElementById('btn-random').classList.remove("active");
randomTrack = true;
}
}
function stop() {
song.pause();
document.getElementById("glow").classList.add("disable-animation");
song.currentTime = 0;
document.getElementById("seek").value = 0;
isStopped = true;
document.getElementById("songName").innerHTML = "playing track..";
}
function setPos(pos) {
song.currentTime = pos;
}
function mute() {
if (song.muted) {
song.muted = false;
document.getElementById('mute').className = "fa fa-volume-up";
}
else {
song.muted = true;
document.getElementById('mute').className = "fa fa-volume-off";
}
}
function setVolume(volume) {
song.volume = volume;
}
function togglePlaylist() {
if (playlistVisible) {
document.getElementById('playlist').className = "hide";
document.getElementById('player').className = "";
playlistVisible = false;
}
else {
document.getElementById('player').className = "hide";
document.getElementById('playlist').className = "";
playlistVisible = true;
}
}
function addList() {
sourceUrl = document.getElementById('sourceUrl').value;
sourceUrl.split(",").forEach((file) => {
fileUrl = file.trim();
if (fileUrl != "" && playlist.indexOf(fileUrl) == -1) {
parent = document.getElementById('list');
listItem = document.createElement('div');
listItem.setAttribute('class','list-item');
wrapper = document.createElement('div');
wrapper.setAttribute('class','wrap-text');
span = document.createElement('span');
songFile = fileUrl.split("/");
span.innerHTML = songFile[songFile.length - 1].split('.').slice(0, -1).join('.');
wrapper.appendChild(span);
listItem.appendChild(wrapper);
btn = document.createElement('button');
btn.setAttribute('onclick','removeList(this)');
btn.innerHTML = '×';
listItem.appendChild(btn);
parent.appendChild(listItem);
playlist.push(fileUrl);
}
});
document.getElementById('sourceUrl').value = '';
}
function removeList(item) {
index = playlist.indexOf(item.parentElement.firstChild.innerText);
if (index != -1){
playlist.splice(index,1);
item.parentElement.remove();
}
}
song.addEventListener('error', function(){
stop();
document.getElementById("songName").innerHTML = "error loading audio";
});
song.addEventListener('timeupdate', function() {
curtime = parseInt(song.currentTime,10);
document.getElementById('seek').max = song.duration;
document.getElementById('seek').value = curtime;
});
song.addEventListener("ended", function() {
song.pause();
song.currentTime = 0;
document.getElementById('seek').value = 0;
if ((currentSong + 1) >= playlist.length) {
currentSong = 0;
}
else {
currentSong++;
}
stop();
song.src = playlist[currentSong];
playpause();
});
var input = document.getElementById("sourceUrl");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
addList();
}
});
// This area of code is only for preview purposes only
document.getElementById('sourceUrl').value = ["https://www.bensound.com/bensound-music/bensound-summer.mp3",
"https://www.bensound.com/bensound-music/bensound-anewbeginning.mp3",
"https://www.bensound.com/bensound-music/bensound-littleidea.mp3",
"https://www.bensound.com/bensound-music/bensound-cute.mp3",
"https://www.bensound.com/bensound-music/bensound-memories.mp3"];
addList();
document.getElementById("glow").classList.remove("disable-animation");
// Code for preview ends here
* {
box-sizing: border-box;
}
html {
background: #000000;
}
html,
body,
.container {
height: 100%;
margin: 0;
font-family: Arial, Helvetica, sans-serif;
white-space: nowrap;
user-select: none;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.container {
display: flex;
align-items: center;
justify-content: center;
}
.glow {
position: absolute;
width: 300px;
height: 300px;
background: linear-gradient(0deg, #000000, #262626);
border-radius: 50%;
}
.glow::before,
.glow::after {
content: "";
position: absolute;
top: -2px;
left: -2px;
background: linear-gradient(
45deg,
#ebc6df,
#ebc6c9,
#e1c6eb,
#c6c9eb,
#c6e8eb,
#e373fb,
#f787e6,
#cb87f7,
#87a9f7,
#87f7ee
);
background-size: 400%;
max-width: calc(300px + 4px);
max-height: calc(300px + 4px);
width: calc(300px + 4px);
height: calc(300px + 4px);
z-index: -1;
animation: animate 20s linear infinite;
border-radius: 50%;
}
.disable-animation::before,
.disable-animation::after {
animation-play-state: paused;
}
.glow::after {
filter: blur(28px);
}
#player,
#playlist {
width: 243px;
height: 212px;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#songName {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 30px;
}
.playlist-btn {
width: 243px;
margin-top: 30px;
text-align: center;
position: relative;
left: 50%;
transform: translateX(-50%);
}
.hide {
display: none;
}
#list {
height: 118px;
max-height: 118px;
margin-top: 16px;
font-size: 12px;
overflow-x: hidden;
overflow-y: scroll;
color: #fff;
text-align: left;
padding-left: 8px;
border: 2px solid #262626;
border-radius: 5px;
}
.list-item {
line-height: 30px;
height: 30px;
margin-top: 4px;
}
.list-container button {
width: 30px;
padding: 0;
float: right;
margin-right: 4px;
}
.add-list {
padding: 4px 6px;
}
.wrap-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 190px;
display: inline-block;
}
#sourceUrl {
background: none;
padding: 8px;
border: 2px solid #1f1f1f;
border-radius: 47px;
outline: none;
color: white;
height: 30px;
width: 192px;
}
#sourceUrl:active,
#sourceUrl:focus {
border: 2px solid #0088ff;
}
.text {
color: #ffffff;
display: block;
}
button {
background: #000000;
color: #ffffff;
background: linear-gradient(0deg, #000000, #262626);
font-size: 14px;
border: none;
outline: none;
padding: 0px 15px;
width: 55px;
height: 30px;
line-height: 30px;
border-radius: 32px;
}
button:hover {
box-shadow: 0 0 8px 0px #ffffff61;
}
button:active {
box-shadow: inset 0 0 6px 0px #ffffff61;
}
#seek,
#volume {
-webkit-appearance: none;
border: 1px solid #000000;
height: 5px;
vertical-align: middle;
border-radius: 20px;
background-color: #232323;
outline: none;
}
#seek::-webkit-slider-thumb,
#volume::-webkit-slider-thumb {
-webkit-appearance: none;
width: 20px;
height: 20px;
border: 1px solid #000000;
border-radius: 10px;
background: #ffffff;
}
#seek {
display: block;
width: 230px;
}
.scrollbar::-webkit-scrollbar {
max-width: 5px;
max-height: 5px;
}
.scrollbar::-webkit-scrollbar-thumb {
border-radius: 10px;
background: #333;
}
.scrollbar::-webkit-scrollbar-thumb:hover {
box-shadow: inset 0 0 1px 1px #5c6670;
}
.scrollbar::-webkit-scrollbar-track:hover {
border: 1px solid #000000;
border-radius: 20px;
background-color: #232323;
}
#keyframes animate {
0% {
background-position: 0 0;
}
50% {
background-position: 400% 0;
}
100% {
background-position: 0 0;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet" type="text/css">
<div class="container">
<div id="glow" class="glow disable-animation">
<div id="player">
<span class="text">iu player</span>
<br>
<span id="songName" class="text">playing track..</span>
<br>
<div class="playback_controls">
<button onclick="skip('prev')">
<i class="fa fa-fast-backward"></i>
</button>
<button onclick="playpause()">
<i class="fa fa-play"></i><i class="fa fa-pause"></i>
</button>
<button onclick="stop()">
<i class="fa fa-stop"></i>
</button>
<button onclick="skip('next')">
<i class="fa fa-fast-forward"></i>
</button>
</div>
<br>
<div id="seekbar">
<input type="range" oninput="setPos(this.value)" id="seek" value="0" max="">
</div>
<br>
<div class="volume_controls">
<button onclick="mute()">
<i id="mute" class="fa fa-volume-up"></i>
</button>
<input type="range" id="volume" oninput="setVolume(this.value)" min="0" max="1" step="0.01" value="1">
</div>
</div>
<div id="playlist" class="hide">
<span class="text">iu playlist</span>
<div class="list-container">
<div id="list" class="scrollbar"></div>
<div class="add-list">
<input id="sourceUrl" type="text" placeholder="enter audio url" />
<button onclick="addList()">+</button>
</div>
</div>
</div>
<div class="playlist-btn">
<button id="btn-random" onclick="random()">
<i class="fas fa-random"></i>
</button>
<button onclick="togglePlaylist()">
<i id="playlist-btn" class="fa fa-list"></i>
</button>
</div>
</div>
</div>
You are never reading your randomSong variable.
Just set currentSong to Math.floor(Math.random() * playlist.length) in that case:
if (
document.getElementById("btn-random").classList.contains("active")
) {
currentSong = Math.floor(Math.random() * playlist.length);
} else {
currentSong = ++currentSong % playlist.length;
}
playpause();
i'm making a webpage where I have different "pictures" that I want like buttons on and when people like it, the number stays and then they can only like each image once. I found a code that I liked however when I refresh the page, all the likes go away. I want them to stay. I'm not the best at explaining or understanding lol.
Here's the code that I found that I liked, but I want to function as it goes away when I refresh. Function like a "vote" button.
/*
* Love button for Design it & Code it
* http://designitcodeit.com/i/9
*/
$('.btn-counter').on('click', function(event, count) {
event.preventDefault();
var $this = $(this),
count = $this.attr('data-count'),
active = $this.hasClass('active'),
multiple = $this.hasClass('multiple-count');
// First method, allows to add custom function
// Use when you want to do an ajax request
/* if (multiple) {
$this.attr('data-count', ++count);
// Your code here
} else {
$this.attr('data-count', active ? --count : ++count).toggleClass('active');
// Your code here
} */
// Second method, use when ... I dunno when but it looks cool and that's why it is here
$.fn.noop = $.noop;
$this.attr('data-count', ! active || multiple ? ++count : --count )[multiple ? 'noop' : 'toggleClass']('active');
});
html {
background: #f5f5f5;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
body {
margin: 30px auto 0 auto;
width: 450px;
font-size: 75%;
}
h3 {
margin-top: 30px;
font-size: 18px;
color: #555;
}
p { padding-left: 10px; }
/*
* Basic button style
*/
.btn {
box-shadow: 1px 1px 0 rgba(255,255,255,0.5) inset;
border-radius: 3px;
border: 1px solid;
display: inline-block;
height: 18px;
line-height: 18px;
padding: 0 8px;
position: relative;
font-size: 12px;
text-decoration: none;
text-shadow: 0 1px 0 rgba(255,255,255,0.5);
}
/*
* Counter button style
*/
.btn-counter { margin-right: 39px; }
.btn-counter:after,
.btn-counter:hover:after { text-shadow: none; }
.btn-counter:after {
border-radius: 3px;
border: 1px solid #d3d3d3;
background-color: #eee;
padding: 0 8px;
color: #777;
content: attr(data-count);
left: 100%;
margin-left: 8px;
margin-right: -13px;
position: absolute;
top: -1px;
}
.btn-counter:before {
transform: rotate(45deg);
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476, sizingMethod='auto expand');
background-color: #eee;
border: 1px solid #d3d3d3;
border-right: 0;
border-top: 0;
content: '';
position: absolute;
right: -13px;
top: 5px;
height: 6px;
width: 6px;
z-index: 1;
zoom: 1;
}
/*
* Custom styles
*/
.btn {
background-color: #dbdbdb;
border-color: #bbb;
color: #666;
}
.btn:hover,
.btn.active {
text-shadow: 0 1px 0 #b12f27;
background-color: #f64136;
border-color: #b12f27;
}
.btn:active { box-shadow: 0 0 5px 3px rgba(0,0,0,0.2) inset; }
.btn span { color: #f64136; }
.btn:hover, .btn:hover span,
.btn.active, .btn.active span { color: #eeeeee; }
.btn:active span {
color: #b12f27;
text-shadow: 0 1px 0 rgba(255,255,255,0.3);
}
<h3>Basic button</h3>
<p>
<span>❤</span>
<span>❤</span> Love it
</p>
<h3>Button with counter - active/inactive</h3>
<p>
<span>❤</span>
<span>❤</span> Love it
</p>
<h3>Button with counter for people who likes to click</h3>
<p>
<span>❤</span>
<span>❤</span> Love it
</p>
You actually need back-end for this, but this is a quick solution.
NOTE: the code will not work in the snippet but it regularly works
W3: Window localStorage
Mozilla Window.localStorage
let btn = document.querySelector('#like');
let result = document.querySelector('#result');
localStorage.setItem('likes', 0);
result.innerHTML = localStorage.getItem('likes');
btn.addEventListener('click', addLike());
function addLike(){
localStorage.setItem('likes', parseInt(localStorage.getItem('likes')) + 1);
result.innerHTML = localStorage.getItem('likes');
}
<button id="like">LIKE</button>
<p id="result"></p>
to see the local storage, go to DevTools open application tab, see the local storage there and you can manage it manually
I have a Pen, in which I have used jQuery slideToggle() function. But, on running the code, it seems like there is some space left on top, and the slide effect starts after that. What could be the possible reason?
$(() => {
let hidden = true,
eff = 'slide',
effFunc;
let display = () => {
$('.menu-list').toggle();
}
let fader = () => {
$('.menu-list').animate({
opacity: 'toggle'
}, 1000);
}
////////////////////////////////////
// Here is the function that makes the slide effect
let slider = () => {
$('.menu-list').slideToggle(1000);
}
////////////////////////////////////
$('input[name="effect"]').on('click', function() {
if (!hidden) {
effFunc();
hidden = !hidden;
}
eff = $(this).val();
});
$('.menu-head').on('click', function() {
if (eff == 'disp') {
effFunc = display;
} else if (eff == 'fade') {
effFunc = fader;
} else if (eff == 'slide') {
effFunc = slider;
}
effFunc();
hidden = !hidden;
});
});
#import url('https://fonts.googleapis.com/css?family=Roboto|Tajawal|Muli');
body {
margin: 0;
padding: 10px;
cursor: default;
user-select: none;
}
span {
display: inline-block;
box-sizing: border-box;
}
span.menu-head {
padding: 9px 0;
background: #FF872A;
width: 270px;
border-radius: 6px 6px 0 0;
text-align: center;
color: white;
text-shadow: 2px 2px 2px #5A5A5A;
font: 500 16pt Roboto;
}
span.menu-list {
border-radius: 0 0 6px 6px;
border: 0.1px solid #D7D7D7;
background: #D7D7D7;
width: 270px;
overflow: hidden;
display: flex;
flex-direction: column;
display: none;
}
span.menu-item {
width: 270px;
padding: 12px 27px;
color: #2A7AFF;
background: #EAEAEA;
font: 700 16pt Muli;
transition: all 0.7s;
}
span.menu-item:hover {
background: #2A9A3F;
color: #FAFAFA;
}
label.option-label {
position: fixed;
top: 10px;
right: 10px;
background: #9A9A9A;
color: #fff;
width: 25vw;
max-height: 33vh;
padding: 20px 12px;
border-radius: 4px;
box-shadow: -4px 4px 1px #C7C7C7;
}
label.option-label * {
margin: 10px 7px;
font: 600 16pt Tajawal;
}
input[type='radio'] {
transform: scale(1.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='menu-head'>Social Networks</span><br/>
<span class='menu-list'>
<span class='menu-item'>CodePen</span>
<span class='menu-item'>Twitter</span>
<span class='menu-item'>Google</span>
<span class='menu-item'>SoloLearn</span>
</span>
<label class='option-label'>
<label>
<input type='radio' name='effect' value='disp'/> Show / Hide
</label>
<br/>
<label>
<input type='radio' name='effect' value='fade'/> Fade In / Fade Out
</label>
<br/>
<label>
<input type='radio' name='effect' value='slide' checked/> Slide Up / Slide Down
</label>
</label>
it's because the inline-block of .menu-list, add display : block to .menu-list and hide it in th begining with js so it will toggle back to display : block instead of display : inline-blick
$(() => {
let hidden = true,
eff = 'slide',
effFunc;
$('.menu-list').hide();
let display = () => {
$('.menu-list').toggle();
}
let fader = () => {
$('.menu-list').animate({
opacity: 'toggle'
}, 1000);
}
////////////////////////////////////
// Here is the function that makes the slide effect
let slider = () => {
$('.menu-list').slideToggle(1000);
}
////////////////////////////////////
$('input[name="effect"]').on('click', function() {
if (!hidden) {
effFunc();
hidden = !hidden;
}
eff = $(this).val();
});
$('.menu-head').on('click', function() {
if (eff == 'disp') {
effFunc = display;
} else if (eff == 'fade') {
effFunc = fader;
} else if (eff == 'slide') {
effFunc = slider;
}
effFunc();
hidden = !hidden;
});
});
#import url('https://fonts.googleapis.com/css?family=Roboto|Tajawal|Muli');
body {
margin: 0;
padding: 10px;
cursor: default;
user-select: none;
}
span {
display: inline-block;
box-sizing: border-box;
}
span.menu-head {
padding: 9px 0;
background: #FF872A;
width: 270px;
border-radius: 6px 6px 0 0;
text-align: center;
color: white;
text-shadow: 2px 2px 2px #5A5A5A;
font: 500 16pt Roboto;
}
span.menu-list {
border-radius: 0 0 6px 6px;
border: 0.1px solid #D7D7D7;
background: #D7D7D7;
width: 270px;
overflow: hidden;
display: flex;
flex-direction: column;
display: block;
}
span.menu-item {
width: 270px;
padding: 12px 27px;
color: #2A7AFF;
background: #EAEAEA;
font: 700 16pt Muli;
transition: all 0.7s;
}
span.menu-item:hover {
background: #2A9A3F;
color: #FAFAFA;
}
label.option-label {
position: fixed;
top: 10px;
right: 10px;
background: #9A9A9A;
color: #fff;
width: 25vw;
max-height: 33vh;
padding: 20px 12px;
border-radius: 4px;
box-shadow: -4px 4px 1px #C7C7C7;
}
label.option-label * {
margin: 10px 7px;
font: 600 16pt Tajawal;
}
input[type='radio'] {
transform: scale(1.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='menu-head'>Social Networks</span><br/>
<span class='menu-list'>
<span class='menu-item'>CodePen</span>
<span class='menu-item'>Twitter</span>
<span class='menu-item'>Google</span>
<span class='menu-item'>SoloLearn</span>
</span>
<label class='option-label'>
<label>
<input type='radio' name='effect' value='disp'/> Show / Hide
</label>
<br/>
<label>
<input type='radio' name='effect' value='fade'/> Fade In / Fade Out
</label>
<br/>
<label>
<input type='radio' name='effect' value='slide' checked/> Slide Up / Slide Down
</label>
</label>
I have problem with my algorithm in simple game.
Game Rules:
Match color NAME (choose one on the bottom) with COLOR of TEXT (on the top).
If none of the two bottom names match than click NEXT.
So the problem is that first correct match gives in console "GOOD" but second , third and any after, even if there is correct match in console I have firstly always "WRONG" and just after that I have "GOOD".
This is a picture with the problem described
It seems like the script remember past random numbers and match current result with them, because after few matches the score pointer raise very quickly (ex. 20 points in one time).
I will be happy to hear from you how can I fix this.
Thank you for any help !
Here you have link to codepen:
http://codepen.io/anon/pen/bWGGga
"use strict"
/*Start Container*/
/* var startContainer = document.getElementById("start_container");
var letsPlay = document.getElementById("start_game"); */
/* letsPlay.addEventListener("click", openTheGame); */
function openTheGame(){
setInterval(startGame, 3000);
};
openTheGame();
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");
var showColor = document.getElementById("show_color");
//SCORE
var score = document.getElementById("score");
var gameContainer = document.getElementById("game_container");
var gameOverContainer = document.getElementById("game_over_container");
/*Array of Colors*/
var arrCol = ["GREEN", "RED", "YELLOW", "BLUE", "ORANGE", "PURPLE"]
//Array from buttons texts to draw Show Color
var arrShowColor = [];
function startGame(){
/*BUTTONS TEXT & COLOR*/
btn1.addEventListener("click", matchColor1);
btn2.addEventListener("click", matchColor2);
btn3.addEventListener("click", matchColor3);
//draw numbers for buttons texts & colors
var randomBtn1Num = Math.floor(Math.random() * 3);
var randomBtn2Num = Math.floor(Math.random() * 3)+3;
var randomBtn3Num = Math.floor(Math.random() * 6);
//Buttons text (next button always "next")
btn1.innerHTML = arrCol[randomBtn1Num];
btn2.innerHTML = arrCol[randomBtn2Num];
//Buttons Color from random_color class
btn1.className = "random_color" + randomBtn2Num;
btn2.className = "random_color" + randomBtn3Num;
btn3.className = "random_color" + randomBtn1Num;
/*SHOW TEXT & COLOR*/
//Array from buttons texts to draw Show Color
arrShowColor[0] = randomBtn1Num;
arrShowColor[1] = randomBtn2Num;
arrShowColor[2] = randomBtn3Num;
console.log(arrShowColor);
//Show color
var randomShowColorNum = Math.floor(Math.random()*3);
var randomShowColor = arrShowColor[randomShowColorNum];
showColor.className = "random_color" + randomShowColor;
console.log(randomShowColor);
//Show text
var randomShowText = Math.floor(Math.random() * 6);
showColor.innerHTML = arrCol[randomShowText];
/*CLICK BUTTON - IF MATCH COLORS*/
function matchColor1(){
if( randomBtn1Num == randomShowColor) {
console.log("GOOD");
score.innerHTML ++;
} else {
console.log("WRONG");
/*gameContainer.style.display = "none";
gameOverContainer.style.display = "inline-block";*/
}
};
function matchColor2(){
if( randomBtn2Num == randomShowColor) {
console.log("GOOD");
score.innerHTML ++;
} else {
console.log("WRONG");
/*gameContainer.style.display = "none";
gameOverContainer.style.display = "inline-block";*/
}
};
function matchColor3(){
if(randomBtn1Num != randomShowColor && randomBtn2Num != randomShowColor){
console.log("GOOD");
score.innerHTML ++;
} else {
console.log("WRONG");
/*gameContainer.style.display = "none";
gameOverContainer.style.display = "inline-block";*/
}
};
/*Finish startGame*/
};
/*Main Styles*/
body {
background-image: url()
}
h4 {
color: #2626e6;
}
/*Main Container Styles*/
#main_container {
width:100%;
text-align:center;
}
/*Start Container Styles*/
#start_container {
position: relative;
display: inline-block;
width: 400px;
height: 400px;
top: 20px;
background-color: rgb(0, 0, 0);
border-radius: 50%;
box-shadow: 0px 0px 10px 10px black;
}
#start_container button {
}
/*Game Container Styles*/
#game_container {
position: relative;
display: inline-block;
width: 400px;
height: 400px;
top: 20px;
background-color: rgb(0, 0, 0);
border-radius: 50%;
box-shadow: 0px 0px 10px 10px black;
}
.second_level{
transform: rotateY(180deg);
}
.third_level{
transform: rotateX(180deg);
}
/*Score Container*/
#score_container {
display: inline-block;
position: relative;
height: 150px;
width: 150px;
background-color: rgb(0, 0, 0);
top: -40px;
margin-left: -5px;
margin-right: 30px;
border-radius: 50%;
box-shadow: 0px 0px 10px 10px black;
}
#score_container #score {
display: inline-block;
height: 30px;
width: 80px;
color: #ffffff;
margin-left: 0;
margin-right: 0;
}
/*Level Container*/
#time_container {
display: inline-block;
position: relative;
height: 150px;
width: 150px;
background-color: rgb(0, 0, 0);
top: -40px;
margin-left: 30px;
border-radius: 50%;
box-shadow: 0px 0px 10px 10px black;
}
#time_container #time {
display: inline-block;
height: 30px;
width: 80px;
color: #ffffff;
margin-left: 0;
margin-right: 0;
}
/*Random Show Color Style*/
#show_color{
margin-top: 50px;
font-size: 40px;
font-family: sans-serif;
font-weight: 800;
}
/*Random Colors Classes*/
.random_color0{
color: green;
}
.random_color1{
color: red;
}
.random_color2{
color: yellow;
}
.random_color3{
color: blue;
}
.random_color4{
color: orange;
}
.random_color5{
color: purple;
}
/*Buttons Container Styles*/
#game_container #buttons_container {
position: relative;
display: inline-block;
margin:0 auto;
margin-top: 120px;
border-top: 1px solid white;
padding-top: 30px;
}
/*Buttons Style*/
#buttons_container button {
height: 40px;
width: 150px;
font-size: 30px;
font-weight: 800;
border: none;
border-radius: 3px;
background-color: rgb(0, 0, 0);
margin: 3px;
}
#buttons_container button:focus{
outline: 0;
}
#buttons_container button:hover{
cursor: pointer;
}
/*Game Over Container*/
#game_over_container {
display: none;
position: relative;
width: 400px;
height: 400px;
top: 20px;
background-color: rgb(0, 0, 0);
border-radius: 50%;
box-shadow: 0px 0px 10px 10px black;
}
<div id="main_container">
<!-- <div id="start_container">
<button id="start_game">PLAY GAME</button>
</div> -->
<div id="score_container">
<h4>SCORE:</h4>
<div id="score">0</div>
</div>
<div id="game_container">
<div id="show_color_container">
<div id="show_color"></div>
</div>
<div id="buttons_container">
<button class="btn_select" id="btn1">ONE</button>
<button class="btn_select" id="btn2">TWO</button>
<button class="btn_select" id="btn3">NEXT</button>
</div>
</div>
<div id="game_over_container">
<h2 id="game_over">GAME OVER</h2>
</div>
</div>
Inside openTheGame() you're using setInterval which calls startGame() every 3 seconds, which in turn creates (adds) new event handlers every 3 seconds, which call your console.logs etc. Replace setInterval with setTimeout:
function openTheGame(){
setTimeout(startGame, 3000);
};
openTheGame();
EDIT: did not thoroughly check your code, but if you need that function called every 3 seconds, then you need to move the setup of click handlers outside that function.