I think I'm over-complicating things for a beginner but all I wanted to do was add addEventListener at once to four of my buttons.
Then pass on that event, to a new function which checks which button fired the event. After which, corresponding function is called for each button.
Thing goes good up until here. Everything works fine, I can even get console to log message from every function but, everything else but, audio doesn't pause.
Audio plays fine but doesn't pause, I'm thinking global - local variable issue but upon checking in DevTools, console.log says same audio is being passed to my pause function but still doesn't pause it. Didn't want to take this last resort but been working on this since yesterday, any insight would be great.
var audioBar = document.getElementsByClassName("audioBar");
var playerBtn = document.getElementsByClassName("playerBtn");
var prev = document.getElementById('prev');
var play = document.getElementById('play');
var pause = document.getElementById('pause');
var pause = document.getElementById('stop');
var next = document.getElementById('next');
var seek = document.getElementById("seek");
var eListener;
for (var i = 0; i < playerBtn.length; i++) {
playerBtn[i].addEventListener("click", whichButton, true);
eListener = playerBtn[i];
}
function whichButton(eListener) {
var whichID = eListener.target.parentElement.id;
var whichClass = eListener.target.className;
event.preventDefault();
switch (whichID) {
case "prev":
// event.preventDefault();
prevIt();
break;
case "play":
// event.preventDefault();
playIt();
break;
case "stop":
// event.preventDefault();
stopIt();
break;
case "next":
// event.preventDefault();
nextIt();
break;
default:
event.preventDefault();
}
var passenger; //Declaring passenger on global scale within whichButton
function playIt() {
// var currentSong;
function audio(src) { //constructor for audio for future efficiency
var currentSong = new Audio(src);
this.src = src;
this.play = function () {
currentSong.play();
};
this.pause = function () {
currentSong.pause();
};
this.stop = function () {
currentSong.pause();
currentSong.currentTime = 0
};
// return currentSong;
}
passenger = new audio(songs[0].file); //The passenger that's been playing around.
if (whichClass === "fa fa-play fa-2x") {
event.target.className = "fa fa-pause fa-2x";
// console.log(whichClass);
console.log("playing it");
passenger.play();
console.log(passenger); //Checking which passenger is being played
} else {
event.target.className = "fa fa-play fa-2x";
// console.log(whichClass);
console.log("pausing it"); // << This works great!
passenger.pause(); // << But this does not
}
// return passenger;
}
console.log(passenger); //Same passenger as the above one
function stopIt() {
passenger.stop(); //passing Same passenger to stop function but does not do it.
passenger.pause();
passenger.currentTime = 0;
console.log("stopping it");
}
function nextIt() {
console.log("next one");
}
}
audioPlayerContainer {
background: -webkit-linear-gradient(top, #494949 0%, #434242 31%, #393838 55%, #242323 83%, #1b1a1a 100%, #161515 100%, #0b0b0b 100%);
/*background: -webkit-linear-gradient(top, #cc4b56 0%, #c01f2c 31%, #c01f2c 55%, #c01f2c 83%, #c01f2c 100%, #ac1b27 100%, #991823 100%);*/
border: #c01f2c solid 4px;
border-top: #fff solid 1.5px;
width: 100%;
height: 50px;
position: fixed;
bottom: 0;
/*padding: 5px 50px 5px 0;*/
}
.relativeWrapper {
position: relative;
height: 100%;
box-sizing: border-box;
}
.audioBar {
display: inline-block;
background: #c01f2c;
width: 15%;
height: 100%;
font-size: 2rem;
line-height: 1rem;
text-align: center;
box-sizing: border-box;
float: left;
}
.audioBar h6 {
top:50%;
transform: translateY(-50%);
position: relative;
line-height: 1.1rem;
}
.fa-music {
font-size: 2rem;
float: left;
margin: 0 0 0 15%;
}
.aPCController {
display: inline;
float: left;
color: #f2f2f2;
margin-left: 2%;
width: 15%;
height: 35px;
/*padding-top: 0.25%;*/
top: 50%;
transform: translateY(-50%);
position: relative;
/*background: #f4c5c4;*/
}
.aPCController a {
color:#fff;
}
.aPCController a~a {
margin-left: 15px;
}
.seekWrapper {
position: relative;
float: left;
background: #2f2f2f;
height: 35px;
top: 50%;
transform: translateY(-50%);
}
.seek {
width: 55%;
/*display: inline-block;*/
}
.seekWrapper input {
/*For div*/
display: block;
font-size: 0px;
background: #c01f2c;
/*width: 50%;*/
height: 100%;
/*For input*/
-webkit-appearance: none;
width: 100%;
cursor: pointer;
}
.seekWrapper input::-webkit-slider-thumb {
-webkit-appearance: none;
border: 2px solid #000;
/*border-radius: 25%;*/
background: #fff;
width: 15px;
height: 35px;
margin-top: -1px;
}
span #title {
text-align: center;
vertical-align: middle;
color: #fff;
/*display: inline;*/
}
.vol {
width: 10%;
margin-left: 1%;
}
canvas {
top: 50%;
-webkit-box-shadow: inset 0 0 10px #000000;
box-shadow: inset 0 0 10px #000000;
}
<div class="audioPlayerContainer wrapper">
<div class="relativeWrapper">
<!--<div class="audioBar"></div>-->
<div class="audioBar">
<h6><i class="fa fa-music fa-2x"></i>audio </br> bar</h6>
</div>
<div class="aPCController"> <a class="playerBtn" id="prev" href="" title=""><i class="fa fa-step-backward fa-2x"></i></a>
<a class="playerBtn" id="play" href="" title=""><i class="fa fa-play fa-2x"></i></a>
<a class="playerBtn" id="stop" href="" title=""><i class="fa fa-stop fa-2x"></i></a>
<a class="playerBtn" id="next" href="" title=""><i class="fa fa-step-forward fa-2x"></i></a>
</div>
<!--<div id="seekWrapper"><p id="seek"><span id="title">some random title</span></p></div>-->
<div class="seekWrapper seek" id="seekWrapper">
<input type="range" id="seek" value="0" max=""><span class="_label"><p>RadioHead - Creep</p></span>
</div>
<div class="seekWrapper vol" id="volWrapper">
<input type="range" id="vol" value="0" max="10">
</div>
<!--<canvas id="previous" width="50px" height="50px" onmouseover=""></canvas>
<canvas id="play" width="50px" height="50px" onmouseover=""></canvas>
<canvas id="next" width="50px" height="50px" onmouseover=""></canvas>-->
</div>
</div>
Let me know if any other details is needed. Thanks!
Edit:
The only case where I got the passenger to stop or pause was when I passed the passenger parameter straight away to stopIt function like this, which further makes me believe this is the case of global/local variable dispute. But for a novice, I can't see anything. Researched a lot, tried a lot, still to no avail.
passenger = new audio(songs[0].file); //The passenger that's being playing around.
if (whichClass === "fa fa-play fa-2x"){
event.target.className = "fa fa-pause fa-2x";
// console.log(whichClass);
console.log("playing it");
passenger.play();
stopIt(passenger); // <<<<<Only if I do this, it stops
}
else {
event.target.className = "fa fa-play fa-2x";
// console.log(whichClass);
console.log("pausing it"); // << This works great!
passenger.pause(); // << But this does not
}
// return passenger;
}
function stopIt(stopThis){
stopThis.stop();
stopThis.pause();
stopThis.currentTime = 0;
console.log("stopping it");
}
This way it pauses/stops but it stops as soon as the passenger starts playing, without click on stop button, as the function is being called by playIt function not the click Event.
So don't know what to do.
before playing any audio/video file you have to load it first.
eg,
this.play = function(){
currentSong.load();
currentSong.play();
};
May this will solve your problem.
the main issue here is, whichButton is not the same object that is shared between the various play buttons as event listener, thus when you put the passenger outside, it would be truly global, also there were other little issues, fixed them in the demo:
fiddle demo
function whichButton(eListener) {
var whichID = eListener.target.parentElement.id;
var whichClass = eListener.target.className;
event.preventDefault();
event is undefined... This will cause javascript error.
A little late on this, but I figured I need to write what I did with this.
Like mido22 suggested, I was having troubles with my passenger, so had to change it all. I had to rewrite most of the things.
Anyways, it's pretty messy, not working on this project so didn't care for presentation. Finished this long time back but forgot to come back to stackoverflow. Came here today to seek an answer to different query.
If anyone's interested, please let me know how I can make this code better.
var audioBar = document.getElementsByClassName("audioBar"),
playerBtn = document.getElementsByClassName("playerBtn"),
prev = document.getElementById('prev'),
play = document.getElementById('play'),
pause = document.getElementById('pause'),
pause = document.getElementById('stop'),
next = document.getElementById('next'),
seek = document.getElementById("seek"),
vol = document.getElementById("vol"),
songInfo = document.getElementById("songInfo").querySelectorAll("p"),
eListener;
for(var i=0; i<playerBtn.length; i++){
playerBtn[i].addEventListener("click", whichButton, true);
eListener = playerBtn[i];
}
var audio = new Audio(),
factor = (seek.clientWidth/audio.duration) * parseFloat(audio.currentTime) / (seek.clientWidth/100);
audio.src = function (){songs[0].file};
vol.value = 5;
function progress(){
seek.value = 0;
seek.value = (seek.clientWidth/audio.duration) * parseFloat(audio.currentTime) / (seek.clientWidth/100);
songInfo[0].textContent = songs[0].artist + " - " + songs[0].title;
songInfo[1].textContent = String(audio.currentTime).toTime() + " | " + String(audio.duration).toTime();
if(audio.ended || audio.paused) {play.childNodes[0].className = "fa fa-play fa-2x";}
}
function volChange(){ vol.value = event.target.value; audio.volume = vol.value/10; }
function seekupdate(){ seek.value = event.target.value; audio.currentTime = seek.value/(seek.clientWidth/audio.duration) * (seek.clientWidth/100) }
audio.addEventListener("timeupdate", progress);
seek.addEventListener("input", seekupdate);
vol.addEventListener("input", volChange);
function whichButton(eListener){
var whichID = eListener.target.parentElement.id,
whichClass = eListener.target.className;
event.preventDefault();
if(!(audio.paused) && whichID === "stop") {audio.pause(); audio.currentTime = 0;}
if((audio.paused) && whichClass === "fa fa-play fa-2x") {audio.play(); event.target.className = "fa fa-pause fa-2x";}
if(!(audio.paused) && whichClass === "fa fa-pause fa-2x") {audio.pause(); event.target.className = "fa fa-play fa-2x";}
}
Related
Hello I am trying to build a simple chatbot and I want the chat screen to scroll down when new messages arrive. I tried somewhat everything but wont work. Here is my HTML code:
<div id="conv" class="chat-body">
<div class="chat-bubble you">Hallo, wie kann ich Ihnen helfen?</div>
<div id="custo"></div>
<!-- <div id="custo"> <span id = "heart"><i class="fa fa-heart-o" aria-hidden="true" ></i> </span> </div> -->
<div id="berbot"></div>
<div id="bouncers" class="chat-bubble you">
</div>
</div>
Here is my javascript code:
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '...';
wisdomText.locked = true;
// send it to the Lex runtime
var params = {
botAlias: '$LATEST',
botName: 'Chatbotwebpage',
inputText: wisdom,
userId: lexUserId,
sessionAttributes: sessionAttributes
};
showRequest(wisdom);
lexruntime.postText(params, function(err, data) {
if (err) {
console.log(err, err.stack);
showError('Error: ' + err.message + ' (see console for details)')
}
if (data) {
// capture the sessionAttributes for the next cycle
sessionAttributes = data.sessionAttributes;
// show response and/or error/dialog status
showResponse(data);
}
// re-enable input
wisdomText.value = '';
wisdomText.locked = false;
});
}
// we always cancel form submission
return false;
}
function showRequest(daText) {
var firstconversationDiv = document.getElementById('custo');
var requestPara = document.createElement("P");
requestPara.className = 'chat-bubble you';
requestPara.appendChild(document.createTextNode(daText));
firstconversationDiv.appendChild(requestPara);
firstconversationDiv.scrollTop = firstconversationDiv.scrollHeight;
}
function showError(daText) {
var conversationDiv = document.getElementById('berbot');
var errorPara = document.createElement("P");
errorPara.className = 'lexError';
errorPara.appendChild(document.createTextNode(daText));
conversationDiv.appendChild(errorPara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
function showResponse(lexResponse) {
var conversationDiv = document.getElementById('custo');
var responsePara = document.createElement("P");
responsePara.className = 'chat-bubble me';
if (lexResponse.message) {
responsePara.appendChild(document.createTextNode(lexResponse.message));
responsePara.appendChild(document.createElement('br'));
}
// if (lexResponse.dialogState === 'ReadyForFulfillment') {
// responsePara.appendChild(document.createTextNode(
// dati));
// // TODO: show slot values
// } else {
// responsePara.appendChild(document.createTextNode(
// dati));
// }
conversationDiv.appendChild(responsePara);
conversationDiv.scrollTop = conversationDiv.scrollHeight;
}
CSS code:
.chat-screen .chat-body {
padding: 25px;
display: inline-block;
width: 350px;
min-height: 382px;
max-height: 382px;
background: white;
overflow-y:auto;
overflow: scroll;
scroll-behavior: auto;
overflow-x: hidden;
}
.chat-screen .chat-body .chat-bubble.you {
background-image: linear-gradient(to right, #7292d4, #5681d7, #336cdc, #1156e1, #034cdd);
color: #fff;
border-radius: 0 15px 15px 15px;
float: left;
align-self: flex-start;
display: table;
border-color: 2px #030303;
}
.chat-screen .chat-body .chat-bubble.me {
background-image: linear-gradient(to right, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF, #FFFFFF);
color: black;
border-radius: 15px 0px 15px 15px;
float: right;
align-self: right;
display: table;
}
The other issues I have:
chat messages will only align left or right after the second or third message arrives.
I am trying to add an instagram heart feature as a like button. I have copy pasted the code from this link: https://codepen.io/bneupane/pen/KMKzZZ
and added the html code into my div like this:
<div id="custo"> <span id = "heart"><i class="fa fa-heart-o" aria-hidden="true" ></i> </span> </div>
but when I do this, the javascript does not create the i class heart inside the div automatically and I do not know how to do it right.
Thank you in advance.
I coded a game for 2 people:
Initialization is done with player1 ()
with the displayScore () function I can reiterate the score as much as I want (here everything is fine)
but when I switch to the other player with the changePlayer (player) function, the event goes well with player2 I can also reiterate but the concern is that the first player continues to play while my functions and variables are well partitioned
the problem comes from the event of the first which continues despite my stopPropagation () which I did not forget to report.
Where's the problem I've been on for a day and a half.
I join the two files html and js and also css
Thank you in advance,
cordially.
jeu de dés
<body>
<div id="launchGame">
<h1>NEW GAME</h1>
</div>
<div id="players">
<div id="player_1"><h2>PLAYER 1</h2><span id="score_player_1">Score :</span></div>
<picture><img id="dice">img</picture>
<div id="player_2"><h2>PLAYER 2</h2><span id="score_player_2">Score :</span></div>
</div>
<div id="current_score">
<div id="current_score_1"><p>current<span id="round_player_1"></span></p></div>
<div id="controls_game">
<h3 id="roll_dice"><img src="images/re_game.png">ROLL DICE</h3>
<h3 id="hold"><img src="images/charge_score.png">HOLD</h3>
</div>
<div id="current_score_2"><p>current<span id="round_player_2"></span></p></div>
</div>
</body>
(function(){
window.addEventListener("DOMContentLoaded", function() {
const launch = document.getElementById("launchGame");
const rollDice = document.getElementById("roll_dice");
function currentPlayer(player) {
const hold = document.getElementById("hold");
if (player.getElementsByTagName("img").length < 1) {
player.firstChild.style.position = "relative";
var currentPlayer = new Image();
currentPlayer.src = "images/current_player.png";
currentPlayer.setAttribute("class", player.getAttribute("id"));
currentPlayer.style.position = "absolute";
player.firstChild.appendChild(currentPlayer);
} else {
player.getElementsByTagName("img")[0].style.visibility = "visible";
}
changePlayer(player);
rollDice.addEventListener("click", function(e) {
e.stopPropagation();
displayScore(player);
}, {capture:false, once: false, useCapture: true});
}
function player1() {
let player1 = document.getElementById("player_1");
currentPlayer(player1);
}
function player2() {
let player2 = document.getElementById("player_2");
currentPlayer(player2);
}
function changePlayer(player) {
hold.addEventListener("click", function(e) {
e.stopPropagation();
player.getElementsByTagName("img")[0].style.visibility = "hidden";
if (player.getAttribute("id") === "player_1") {
console.log(player.getAttribute("id"));
player2();
} else if (player.getAttribute("id") === "player_2") {
console.log(player.getAttribute("id"));
player1();
}
}, {capture:false, once:true, useCapture: true});
}
function displayScore(player) {
let scoreDice = getScoreDice();
let scorePlayer = document.getElementById("round_" +
player.getAttribute("id"));
scorePlayer.textContent = scoreDice();
}
function getScoreDice() {
var result = 0;
var faceDice = Math.floor(Math.random()*7);
if ((faceDice > 0) && (faceDice < 7)) {
result = faceDice;
} else {
result = faceDice+1;
}
function innerGetScoreDice() {
return result;
}
return innerGetScoreDice;
}
launch.addEventListener("click", player1(), {capture:false, once:true});
});
})()
body {
margin: 0;
padding: 0;
background-color: silver;
background: linear-gradient(to left, white, white 50%, rgb(228, 227, 227) 50%, rgb(228, 227, 227));
text-align: center;
color: gray;
}
h1 {
width: 40%;
margin: 1% auto 5%;
font-size: 1.5rem;
}
h1::before {
content: "⊕ ";
font-size: 2rem;
align-items: center;
color: tomato;
}
h2 {
height: 30px;
line-height: 30px;
}
h3 {
margin: 7% 0;
}
span {
display: block;
margin-top: 50%;
}
img {
max-width: 10%;
vertical-align: middle;
margin-right: 3%;
}
#players, #final_score, #current_score, #current_score_1, #current_score_2, #controls_game {
display: flex;
}
#players, #final_score, #current_score {
flex-direction: row;
justify-content:space-evenly;
align-items: center;
}
#players {
justify-content:space-around;
margin: 1% 1% 10%;
}
#current_score_1, #current_score_2 {
border-radius: 20%;
padding: 2% 4%;
background-color: tomato;
color: white;
}
#controls_game {
flex-direction: column;
max-width: 33%;
}
In function changePlayer(player), isn't variable 'hold' undefined ?
No
The variable hold is defined and ok
All variables are ok
Problems is in event of first players
Bubble or capture
I don't now whats this
I tried using media queries as usual but i dont know what I'm doing wrong.
this is how it looks on desktop:
[Desktop]: https://i.stack.imgur.com/rIQbK.png
and here is what it looks on mobile :
[Mobile]: https://i.stack.imgur.com/Y0JLP.jpg
.
when i comment out the .css file the margins disapear. i dont really know which #media queries to use here.
i want it to be same as the desktop.
triend to change the position and manually adjusting the margins. but nothing works well, first post here. i couldnt find answers on the internet for all day long, hope you could help! thank you in advance..
(it is on top of a video)
// function([string1, string2],target id,[color1,color2])
consoleText(['נשבר לכם המסך?', 'הטלפון נפל למים?', 'הטלפון אינו נטען?'], 'text', ['white', 'red', 'black']);
function consoleText(words, id, colors) {
if (colors === undefined) colors = ['#fff'];
var visible = true;
var con = document.getElementById('console');
var letterCount = 1;
var x = 1;
var waiting = false;
var target = document.getElementById(id)
target.setAttribute('style', 'color:' + colors[0])
window.setInterval(function () {
if (letterCount === 0 && waiting === false) {
waiting = true;
target.innerHTML = words[0].substring(0, letterCount)
window.setTimeout(function () {
var usedColor = colors.shift();
colors.push(usedColor);
var usedWord = words.shift();
words.push(usedWord);
x = 1;
target.setAttribute('style', 'color:' + colors[0])
letterCount += x;
waiting = false;
}, 1000)
} else if (letterCount === words[0].length + 1 && waiting === false) {
waiting = true;
window.setTimeout(function () {
x = -1;
letterCount += x;
waiting = false;
}, 1000)
} else if (waiting === false) {
target.innerHTML = words[0].substring(0, letterCount)
letterCount += x;
}
}, 120)
window.setInterval(function () {
if (visible === true) {
con.className = 'console-underscore hidden'
visible = false;
} else {
con.className = 'console-underscore'
visible = true;
}
}, 400)
}
#myVideo {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
#myVideo video {
position: absolute;
left: 50%;
top: 50%;
min-width: 100%;
min-height: 100%;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
z-index: 0;
}
.console-container {
font-size:4em;
text-align:center;
height:200px;
width:600px;
display:block;
position:absolute;
color:white;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
text-shadow:
2px 2px #ffffff,
4px 4px #000000;
}
<section class="banner embed-responsive-item">
<video autoplay muted loop id="myVideo">
<source src="https://mobilefixexperts.com/wp-content/uploads/2018/01/mobile-repair-experts-video.mp4"
type="video/mp4">
</video>
<div style='direction: rtl;' class='console-container float-end'><span id='text'></span>
<div class='console-underscore' id='console'>_</div>
</div>
<a id="a" class="btn btn-primary btn-lg float-end" href="#" role="button">צור קשר</a>
<!-- <h2 class="float-end display-1" style='direction: rtl;'>מה תרצו לתקן היום?</h2>
<a id="a" class="btn btn-primary btn-lg float-end" href="#" role="button">צור קשר</a> -->
</section>
the css code is :
.console-container {
font-size:4em;
text-align:center;
height:200px;
width:600px;
display:block;
position:absolute;
color:white;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
text-shadow:
2px 2px #ffffff,
4px 4px #000000;
}
This is a common problem I have faced it too.
The thing that is doing this is the large text, you may see that the website starts messing up when the large text touches the right side of the screen. So, the solution to tackle this problem is to make that text responsive means it should not touch the side it should become smaller so you can do like:
#media screen and (max-width: 425px) { //Note where it starts happening
#text {
font-size: 3em; //small than what it was before
}
}
If I understand the question you wannt to remove the margin on mobile/small screens?
This css will do it:
#media screen and (max-width:500px) { body{margin:0;} }
Add position: relative; to your banner class and then you can use the media query you want.
.banner{
position: relative;
}
I'm trying to make a game of little rabbit's farm. My level of programming is a beginner.
Why is addRabbit() code starts to work after the page is loaded? I wrote it to work after click to "Buy Rabbit" button
Why rabbits are not shown at the page near the "Sell Rabbit" and "Buy Rabbit" buttons?
I know that I have a lot of issues here as far as I'm a beginner. Could I ask you to mention any of them?
// VARIABLES
// variables for modal of chosing rabbits
const chooseModal = document.querySelector(".choose-modal");
const selectRabbitBtn = document.querySelector(".choose-rabbit-btn");
const rabbitSelects = document.querySelectorAll("input[type=radio]");
let chosenRabbitUrl = "img/rabbit1.png";
// start screen
const startScreenDiv = document.querySelector(".story-modal");
const rabbit = document.querySelector("img.rabbit");
const buyRabbitBtn = document.querySelector(".buy-btn");
// EVENT LISTENERS
selectRabbitBtn.addEventListener("click", chooseTheRabbit);
// FUNCTIONS
function chooseTheRabbit(e){
e.preventDefault();
for (let rabbit of rabbitSelects) {
if (rabbit.checked) {
chosenRabbitUrl = `img/${rabbit.id}.png`;
break;
}
}
chooseModal.style.display = "none";
startScreen();
}
function startScreen() {
startScreenDiv.style.display = "block";
rabbit.src = chosenRabbitUrl;
}
class RabbitGame {
constructor() {
this.rabbitsCount = parseInt(document.querySelector(".rabbits-count").innerText, 10);
this.rabbitsCountSpan = document.querySelector(".rabbits-count");
this.rabbitsShowDiv = document.querySelector(".rabbits-count-show");
this.coinsCount = parseInt(document.querySelector(".coins-count").innerText, 10);
this.coinsCountSpan = document.querySelector(".coins-count");
this.sellRabbitBtn = document.querySelector(".sell-btn");
this.myRabbits = [{age: 0, src: chosenRabbitUrl, width: 50}];
};
// function, that shows rabbits on the page, that the owner have
// adult rabbits should be bigger, little rabbits smaller
showRabbits() {
// rabbit.src = chosenRabbitUrl
this.myRabbits.forEach((rabbit) => {
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`});
};
// function that adds a rabbit, if the owner doesn't have any coin, rabbits eat him
addRabbit() {
console.log("Hello");
if (this.coinsCount > 1) {
// remove 1 coin
this.coinsCount -= 1
console.log(this.coinsCount);
// show 1 coin less
this.coinsCountSpan.innerText = this.coinsCount
// add 1 for rabbits age
// if the rabbit is older than 4, make him bigger on screen
this.myRabbits.forEach((rabbit) => {
rabbit.age +=1;
if (rabbit.age > 3) {
rabbit.width = 70
}
})
// add 1 more rabbit to array
this.myRabbits.push({age: 0, src: chosenRabbitUrl, width: 50});
// show 1 more rabbit
this.rabbitsShowDiv.innerHTML += `<img src="${rabbit.src}" width="${rabbit.width}">`
}
};
// функция, которая продает кролика, если он взрослый
// если нет взрослых кроликов, выводит предупреждение, что нет взрослых кроликов
}
const rabbitGame = new RabbitGame();
rabbitGame.showRabbits;
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
/* GENERAL */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h3 {
background-color: rgb(108, 165, 55);
width: 400px;
height: 30px;
padding: 5px;
color: white;
text-align: center;
}
button {
padding: 5px 20px;
background-color: rgb(194, 89, 89);
color: white;
text-transform: uppercase;
border: none;
font-weight: bold;
}
button:hover {
background-color: rgb(172, 79, 84);
}
/* END OF GENERAL */
/* CHOOSE RABBIT MODAL & RULES MODAL */
.choose-modal,
.rules-modal {
display: flex;
justify-content: center;
margin-top: 20px;
}
.choose-modal > div {
display: flex;
flex-direction: column;
}
input[type="radio"] {
opacity: 0;
}
label > img:hover {
border-bottom: 1px solid rgb(199, 199, 199);
}
ul {
list-style: none;
margin: 10px;
}
li {
margin-bottom: 5px;
}
.button-div {
display: flex;
justify-content: center;
}
/* END OF CHOOSE RABBIT MODAL & RULES MODAL */
/* START SCREEN */
/* .story-modal {
display: none;
} */
.story-modal {
background-image: url("img/neighbour.jpg");
background-size: cover;
height: 100vh;
position: relative;
}
img.rabbit {
position: absolute;
height: 40%;
top: 60%;
left: 50%;
overflow: hidden;
}
.story-modal > h3 {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 5%;
}
.img-overlay {
width: 100%;
height: 100%;
background: rgba(61, 61, 61, 0.3);
}
.story-modal > button {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
top: 13%;
}
/* END OF START SCREEN */
/* MAIN GAME */
.main-game {
display: flex;
}
/* END OF MAIN GAME */
<div class="choose-modal">
<div>
<div class="choose-modal-header">
<h3>Please, choose the rabbit</h3>
</div>
<div>
<label for="rabbit1"><input type="radio" id="rabbit1" name="rabbits" value="rabbit1"><img src="img/rabbit1.png" width="100" alt="rabbit1"></label>
<label for="rabbit2"><input type="radio" id="rabbit2" name="rabbits" value="rabbit2"><img src="img/rabbit2.png" width="100" alt="rabbit2"></label>
<label for="rabbit3"><input type="radio" id="rabbit3" name="rabbits" value="rabbit3"><img src="img/rabbit3.png" width="80" alt="rabbit3"></label>
</div>
<div class="button-div">
<button type="submit" value="Choose" class="choose-rabbit-btn">Choose</button>
</div>
</div>
</div>
<div class="story-modal">
<div class="img-overlay"></div>
<h3>Your pretty neighbour gave you a rabbit</h3>
<img alt="rabbit" src="#" class="rabbit">
<button>Rules</button>
</div>
<div class="rules-modal">
<div>
<h3>Rules of game</h3>
<div>
<ul>
<li>Buy grass to feed the rabbits</li>
<li>Sell adult rabbits</li>
<li>Buy new little rabbits</li>
</ul>
</div>
<div class="button-div">
<button>Play</button>
</div>
</div>
</div>
<div class="main-game">
<div class=" navbar">
<p><img src="img/coin.png" height="20"> Coins <span class="coins-count">10</span></p>
<p class="name-of-gamer">Anonymous</p>
<p><img src="img/rabbit.png" height="20"> Rabbits <span class="rabbits-count">3</span></p>
</div>
<div class="rabbits-count-show"></div>
<div>
<button class="sell-btn">Sell Rabbit</button>
<button class="buy-btn">Buy Rabbit</button>
</div>
</div>
Changing the line
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit());
to
buyRabbitBtn.addEventListener("click", rabbitGame.addRabbit);
(simply removing those parenthesis) should work. When you add the parenthesis, a function gets called, and that's not what you want. When the button is clicked the eventlistener call the your function itself. as of your second problem you have to add parenthesis to the function to get called thus executing the code inside it.
NOTE: Do not post unnecessary files to a question. Try find the location that error could possibly occur. BTW, CSS has no contributing factor to a error in js code. sometimes html does. I know as a beginner it's hard to find the areas causing the error but it gets easier over time.
I am experiencing an issue where the progress bar is behind, if you click THIS LINK and go to the second song you will see that the progress bar is all messed up. If anyone has a solution please help! This is an image of what the problem is. Also this is all the coding I think necessary to solve the problem.
var timer;
var percent = 0;
var audio = document.getElementById("audioPlayer");
audio.addEventListener("playing", function(_event) {
var duration = _event.target.duration;
advance(duration, audio);
});
audio.addEventListener("pause", function(_event) {
clearTimeout(timer);
});
var advance = function(duration, element) {
var progress = document.getElementById("progress");
increment = 10 / duration
percent = Math.min(increment * element.currentTime * 10, 100);
progress.style.width = percent + '%'
startTimer(duration, element);
}
var startTimer = function(duration, element) {
if (percent < 100) {
timer = setTimeout(function() {
advance(duration, element)
}, 100);
}
}
#timeline {
width: 50%;
height: 4px;
background: rgba(0, 0, 0, .3);
margin-top: 27px;
float: left;
margin-left: 10px;
border-radius: 15px;
background-color: blue;
}
/*Grabable Playhead*/
#playhead {
cursor: pointer;
width: 18px;
height: 18px;
border-radius: 50%;
margin-top: -10.9px;
background: black;
}
.progress {
height: 5px;
background: black;
transition: width .1s linear;
}
<audio id="audioPlayer" preload="true" ontimeupdate="initProgressBar()">
<source src="https://tunechestmusic.000webhostapp.com/sleepy.mp3">
</audio>
<div id="wrapper">
<!--Audio Player Interface-->
<div id="audioplayer">
<button id="pButton" class="play"></button>
<div id="timeline">
<div class="progress" id="progress"></div>
<div id="playhead"></div>
</div>
</div>
</div>
It looks like you're missing some key things to make it work
The first thing is that your play button doesn't actually do anything. Try adding an event to handle the clicking of the play button and play the audio
var playButton = document.getElementById('pButton');
playButton.addEventListener('click', e => { audio.play(); });
The second issue I see is that your audio tag is supposed to call initProgressBar but that function doesn't exist.
<audio id="audioPlayer" preload="true" ontimeupdate="initProgressBar()">
I added a placeholder function for you to fill in. If you don't need this function, remove it from the HTML.
function initProgressBar() {
// TODO: What goes here?
}
After you add the click event in, the audio plays when clicked and the progress bar makes the correct progress. However, your circle doesn't move with the progress. I'm assuming you just haven't gotten that part yet.
var timer;
var percent = 0;
var audio = document.getElementById("audioPlayer");
var playButton = document.getElementById('pButton');
playButton.addEventListener('click', e => { audio.play(); });
function initProgressBar() {
// TODO: What goes here?
}
audio.addEventListener("playing", function(_event) {
var duration = _event.target.duration;
advance(duration, audio);
});
audio.addEventListener("pause", function(_event) {
clearTimeout(timer);
});
var advance = function(duration, element) {
var progress = document.getElementById("progress");
increment = 10 / duration
percent = Math.min(increment * element.currentTime * 10, 100);
progress.style.width = percent + '%'
startTimer(duration, element);
}
var startTimer = function(duration, element) {
if (percent < 100) {
timer = setTimeout(function() {
advance(duration, element)
}, 100);
}
}
#timeline {
width: 50%;
height: 4px;
background: rgba(0, 0, 0, .3);
margin-top: 27px;
float: left;
margin-left: 10px;
border-radius: 15px;
background-color: blue;
}
/*Grabable Playhead*/
#playhead {
cursor: pointer;
width: 18px;
height: 18px;
border-radius: 50%;
margin-top: -10.9px;
background: black;
}
.progress {
height: 5px;
background: black;
transition: width .1s linear;
}
<audio id="audioPlayer" preload="true" ontimeupdate="initProgressBar()">
<source src="https://tunechestmusic.000webhostapp.com/sleepy.mp3">
</audio>
<div id="wrapper">
<!--Audio Player Interface-->
<div id="audioplayer">
<button id="pButton" class="play">Play</button>
<div id="timeline">
<div class="progress" id="progress"></div>
<div id="playhead"></div>
</div>
</div>
</div>