I’m making a object oriented jukebox but for some reason my shuffle button is not working when I click on it. It’s supposed to play a random song from my songlist but it’s not working for some reason. Can someone please explain what I’m doing wrong?
// defines the Jukebox object
var Juke = function(songList) {
// the code for what happens when you create a Jukebox object
// goes here
//sets list of songs by a tag elements in html
//initialize songNumber to 0
//initialize currentSong to the songList's songnumber
//initialize timeinsong to 0
this.songList = document.getElementById('playlist').getElementsByTagName('A'),
// the code for playing a song would go here
this.songNumber = 0,
this.currentSong = this.songList[this.songNumber],
this.timeInSong = 0,
//function to play jukebox
this.play = function() {
// if pl
if (document.getElementById('play').classList.contains('fa-play-circle-o')) {
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
document.getElementById('play').classList.remove('fa-play-circle-o');
document.getElementById('play').classList.add('fa-pause-circle-o');
document.getElementById('player').currentTime = this.timeInSong;
var css = '-webkit-transform: rotateX(40deg) rotateY(-1deg) rotateZ(-10deg) rotate(0deg); -webkit-transition: -webkit-transform 2s ease;'; //
document.getElementById('vinyl').setAttribute('style', css)
document.getElementById('player').play();
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
} else {
this.timeInSong = document.getElementById('player').currentTime
document.getElementById('player').pause();
document.getElementById('play').classList.remove('fa-pause-circle-o');
document.getElementById('play').classList.add('fa-play-circle-o');
}
},
this.next = function() {
// creates a new Jukebox object method
// this play the next song in the array and removes the li class and adds to the next element in the array
document.getElementsByTagName('li')[Jukebox.songNumber].classList.remove('highlight')
this.songNumber++;
//incrementing song number by one
if (this.songNumber == this.songList.length) {
// if the song number is equal to the last element in the arrary start from 0
this.songNumber = 0;
}
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
// add highlight to li song number
this.currentSong = this.songList[this.songNumber]
//currrent song is equal to this song number
document.getElementById('player').setAttribute("src", this.currentSong.getAttribute('href'));
if (document.getElementById('play').classList.contains('fa-pause-circle-o')) {
document.getElementById('player').play();
}
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
// setting title of the song to current song name
},
this.stop = function() {
// time of song is -
this.timeInSong = 0;
document.getElementById('seekbar').setAttribute('value', 0);
// adding pause to the player
document.getElementById('player').pause();
// removing pause class
document.getElementById('play').classList.remove('fa-pause-circle-o');
document.getElementById('play').classList.add('fa-play-circle-o');
},
this.previous = function() {
// removing song number highlight class
document.getElementsByTagName('li')[Jukebox.songNumber].classList.remove('highlight');
//decrementing song number by 1
this.songNumber--;
// if song number isless than 0 play the last one
if (this.songNumber <= 0) {
this.songNumber = this.songList.length - 1;
}
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
// adding highlight to current song
this.currentSong = this.songList[this.songNumber]
// current song is this song number
document.getElementById('player').setAttribute("src", this.currentSong.getAttribute('href'));
console.log(document.getElementById('player').getAttribute("src"));
document.getElementById('player').play();
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
// song tittle
},
this.addSong = function() {
// method to add song
var ul = document.getElementById('playlist')
// url
var url = document.getElementById('url').value;
var name = document.getElementById('title').value;
//name is equal to title value
if (url != "" && name != "") {
//i furl and name are not empty
var li = document.createElement('li');
// creting new li element
var atag = document.createElement('a');
atag.setAttribute('href', url);
atag.innerHTML = name;
var but = document.createElement('button');
but.innerHTML = "";
but.setAttribute('onclick', "Jukebox.delete(this)");
// appending user value
li.appendChild(atag);
li.appendChild(but).classList.add('delete', 'fa', 'fa-times');
ul.appendChild(li);
document.getElementById('url').value = '';
document.getElementById('title').value = '';
} else {
alert("Error You haven't Filled in A Form Item")
}
},
this.delete = function(n) {
if (document.getElementById('player').src == n.parentNode.getElementsByTagName('a')[0].getAttribute('href')) {
document.getElementById('player').src = '';
document.getElementById('player').pause();
this.next();
}
n.parentNode.parentNode.removeChild(n.parentNode);
this.songList = document.getElementById('playlist').getElementsByTagName('A');
},
this.preparingToFastForward = function() {
document.getElementById('player').currentTime += document.getElementById('player').currentTime + 100 < document.getElementById('player').duration ? 100 : 0;
},
this.backDatAssUp = function() {
document.getElementById('player').currentTime -= document.getElementById('player').currentTime - 100 > 0 ? 100 : 0;
},
this.listener = function() {
document.getElementById('player').addEventListener("timeupdate", function() {
var currentTime = document.getElementById('player').currentTime;
var duration = document.getElementById('player').duration;
if (currentTime / duration != 1) {
document.getElementById('seekbar').setAttribute('value', currentTime / duration);
var deg = document.getElementById('player').currentTime % 2;
deg = Math.floor(deg % 2) > 0 ? 170 : -170;
console.log(deg)
var css = '-webkit-transform: rotateX(40deg) rotateY(-1deg) rotateZ(-10deg) rotate(' + deg + 'deg); -webkit-transition: -webkit-transform 2s ease;';
document.getElementById('vinyl').setAttribute('style', css)
} else {
Jukebox.next();
}
});
}
}
this.random = function() {
var randomIndex = Math.floor(this.songList.length * Math.random());
this.currentSong = randomIndex;
randomIndex.play();
}
function setVolume() {
var mediaClip = document.getElementById("player");
mediaClip.volume = document.getElementById("volume1").value;
}
var Jukebox = new Juke(document.getElementById('playlist'));
<body onload="Jukebox.listener()">
<input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='1'>
<div class='container'>
<div class='recordPlayer'>
<img id='vinyl' class='recordPic' src='https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRpCviLXje4Wve8WwujEm2luErz6VbuoVFkNW785Kxuap6O1Gpt0eXobRk'>
<img class='recPlayer' src="https://c1.staticflickr.com/3/2260/3694333300_37bd1ff316.jpg">
<img class='recArm' src="arm.png">
<div class='controls'>
<span class='titleTitle'>Currently Playing:<span id='songTitle'></span></span><br>
<audio id='player' src='http://www.archive.org/download/bolero_69/Bolero.mp3'>
</audio>
<progress id="seekbar" value="0" max="1"></progress><br>
<button id='back' class='fa fa-backward' onclick="Jukebox.backDatAssUp()"></button>
<button id='play' class='fa fa-play-circle-o' onclick="Jukebox.play()"></button>
<button id='stop' class='fa fa-stop-circle-o' onclick="Jukebox.stop()"></button>
<button id='previous' class='fa fa-step-backward' onclick="Jukebox.previous()"></button>
<button id='next' class='fa fa-step-forward' onclick="Jukebox.next()"></button>
<button id='back' class='fa fa-forward' onclick="Jukebox.preparingToFastForward()"></button>
<button id='random' onclick="Jukebox.random()"> Rnadom song</button>
</div>
</div>
<div class='listOsongs'>
<ol id="playlist">
<h4>Up Next</h4>
<li>
<a id="song" href="http://www.archive.org/download/bolero_69/Bolero.mp3">
Ravel Bolero
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="http://www.archive.org/download/MoonlightSonata_755/Beethoven-MoonlightSonata.mp3">
Moonlight Sonata - Beethoven
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="http://www.archive.org/download/CanonInD_261/CanoninD.mp3">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="https://cf-media.sndcdn.com/MzhGaP8pde4q.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vTXpoR2FQOHBkZTRxLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0OTAyODI2Mzh9fX1dfQ__&Signature=SyWy~ghuKuTgWmoMWvnGgA~HArGVxjKkiD61UUENA4Ke-aUgivz4ANDUmNW68-AOE-o-7X~MYn8ObL4AonSuVsPz3LbGPQcmxD-3N14qpCFEx3F4zwZh43v1-aDzlypCRtY6IaEzun9NksxbABrqqL~BokIKSH0U6yxJmEmKq98e8PrUO24IcDHiSZZlviYI-bRRtdsFXxM1bxbYh-s32Rkoihj~uxTOGVDwAADwexg5VT2Z8xAuMj2NJ9vMCYkydhmZGOG4G~SQ3lZE3ODyEtD5Vf6myOMGjhWIq9qss~u6eHJbrQ2AB~oon-44WIqEknjWT63NP-O-WyHCBmAf4w__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="https://cf-media.sndcdn.com/zYh4wOY76Fez.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20velloNHdPWTc2RmV6LjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0OTAyODMzMzN9fX1dfQ__&Signature=nIZ6247SDTQ5LY5pGrdvJkxi3wektW8Kp2uRxOlCg3TthYAq6FeYiu0TJJEdQNNPF8y5WCvbJUi4G553RMwn5xLpxkZR0s0f6B0Fw4m~T18zvic1YH~kRxRVy1ropC2NPax4aI9yCWdKpgFmPNKz21lhFIXoa9F6hnIHaQT0jdFv9eNnjv8CN024j5RnfbFaT1vSzu0AnguXqMlm4uJS8XD~XOT1Y62X4qHzCp685Ahf~Lm9LyhECBXK3nrVF~3QIsxwdYp73Epui29eZsd~7LVCeLwQabU4kvXL9ntTZFft9-JiqLZH4pkmWmSTWlN3Dw~c8dVlZQihruYa81qVPg__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
</ol>
The main problem you have is that you had your random function being defined outside the Juke constructor. Inside there's now a different error where you try to call a play method on a number-- but I don't know what you're trying to do there.
// defines the Jukebox object
var Juke = function(songList) {
// the code for what happens when you create a Jukebox object
// goes here
//sets list of songs by a tag elements in html
//initialize songNumber to 0
//initialize currentSong to the songList's songnumber
//initialize timeinsong to 0
this.songList = document.getElementById('playlist').getElementsByTagName('A'),
// the code for playing a song would go here
this.songNumber = 0,
this.currentSong = this.songList[this.songNumber],
this.timeInSong = 0,
//function to play jukebox
this.play = function() {
// if pl
if (document.getElementById('play').classList.contains('fa-play-circle-o')) {
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
document.getElementById('play').classList.remove('fa-play-circle-o');
document.getElementById('play').classList.add('fa-pause-circle-o');
document.getElementById('player').currentTime = this.timeInSong;
var css = '-webkit-transform: rotateX(40deg) rotateY(-1deg) rotateZ(-10deg) rotate(0deg); -webkit-transition: -webkit-transform 2s ease;'; //
document.getElementById('vinyl').setAttribute('style', css)
document.getElementById('player').play();
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
} else {
this.timeInSong = document.getElementById('player').currentTime
document.getElementById('player').pause();
document.getElementById('play').classList.remove('fa-pause-circle-o');
document.getElementById('play').classList.add('fa-play-circle-o');
}
},
this.next = function() {
// creates a new Jukebox object method
// this play the next song in the array and removes the li class and adds to the next element in the array
document.getElementsByTagName('li')[Jukebox.songNumber].classList.remove('highlight')
this.songNumber++;
//incrementing song number by one
if (this.songNumber == this.songList.length) {
// if the song number is equal to the last element in the arrary start from 0
this.songNumber = 0;
}
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
// add highlight to li song number
this.currentSong = this.songList[this.songNumber]
//currrent song is equal to this song number
document.getElementById('player').setAttribute("src", this.currentSong.getAttribute('href'));
if (document.getElementById('play').classList.contains('fa-pause-circle-o')) {
document.getElementById('player').play();
}
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
// setting title of the song to current song name
},
this.stop = function() {
// time of song is -
this.timeInSong = 0;
document.getElementById('seekbar').setAttribute('value', 0);
// adding pause to the player
document.getElementById('player').pause();
// removing pause class
document.getElementById('play').classList.remove('fa-pause-circle-o');
document.getElementById('play').classList.add('fa-play-circle-o');
},
this.previous = function() {
// removing song number highlight class
document.getElementsByTagName('li')[Jukebox.songNumber].classList.remove('highlight');
//decrementing song number by 1
this.songNumber--;
// if song number isless than 0 play the last one
if (this.songNumber <= 0) {
this.songNumber = this.songList.length - 1;
}
document.getElementsByTagName('li')[Jukebox.songNumber].classList.add('highlight');
// adding highlight to current song
this.currentSong = this.songList[this.songNumber]
// current song is this song number
document.getElementById('player').setAttribute("src", this.currentSong.getAttribute('href'));
console.log(document.getElementById('player').getAttribute("src"));
document.getElementById('player').play();
document.getElementById('songTitle').innerHTML = this.currentSong.innerHTML;
// song tittle
},
this.addSong = function() {
// method to add song
var ul = document.getElementById('playlist')
// url
var url = document.getElementById('url').value;
var name = document.getElementById('title').value;
//name is equal to title value
if (url != "" && name != "") {
//i furl and name are not empty
var li = document.createElement('li');
// creting new li element
var atag = document.createElement('a');
atag.setAttribute('href', url);
atag.innerHTML = name;
var but = document.createElement('button');
but.innerHTML = "";
but.setAttribute('onclick', "Jukebox.delete(this)");
// appending user value
li.appendChild(atag);
li.appendChild(but).classList.add('delete', 'fa', 'fa-times');
ul.appendChild(li);
document.getElementById('url').value = '';
document.getElementById('title').value = '';
} else {
alert("Error You haven't Filled in A Form Item")
}
},
this.delete = function(n) {
if (document.getElementById('player').src == n.parentNode.getElementsByTagName('a')[0].getAttribute('href')) {
document.getElementById('player').src = '';
document.getElementById('player').pause();
this.next();
}
n.parentNode.parentNode.removeChild(n.parentNode);
this.songList = document.getElementById('playlist').getElementsByTagName('A');
},
this.preparingToFastForward = function() {
document.getElementById('player').currentTime += document.getElementById('player').currentTime + 100 < document.getElementById('player').duration ? 100 : 0;
},
this.backDatAssUp = function() {
document.getElementById('player').currentTime -= document.getElementById('player').currentTime - 100 > 0 ? 100 : 0;
},
this.listener = function() {
document.getElementById('player').addEventListener("timeupdate", function() {
var currentTime = document.getElementById('player').currentTime;
var duration = document.getElementById('player').duration;
if (currentTime / duration != 1) {
document.getElementById('seekbar').setAttribute('value', currentTime / duration);
var deg = document.getElementById('player').currentTime % 2;
deg = Math.floor(deg % 2) > 0 ? 170 : -170;
console.log(deg)
var css = '-webkit-transform: rotateX(40deg) rotateY(-1deg) rotateZ(-10deg) rotate(' + deg + 'deg); -webkit-transition: -webkit-transform 2s ease;';
document.getElementById('vinyl').setAttribute('style', css)
} else {
Jukebox.next();
}
});
}
this.random = function() {
var randomIndex = Math.floor(this.songList.length * Math.random());
this.currentSong = randomIndex;
randomIndex.play();
}
}
function setVolume() {
var mediaClip = document.getElementById("player");
mediaClip.volume = document.getElementById("volume1").value;
}
var Jukebox = new Juke(document.getElementById('playlist'));
<body onload="Jukebox.listener()">
<input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='1'>
<div class='container'>
<div class='recordPlayer'>
<img id='vinyl' class='recordPic' src='https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRpCviLXje4Wve8WwujEm2luErz6VbuoVFkNW785Kxuap6O1Gpt0eXobRk'>
<img class='recPlayer' src="https://c1.staticflickr.com/3/2260/3694333300_37bd1ff316.jpg">
<img class='recArm' src="arm.png">
<div class='controls'>
<span class='titleTitle'>Currently Playing:<span id='songTitle'></span></span><br>
<audio id='player' src='http://www.archive.org/download/bolero_69/Bolero.mp3'>
</audio>
<progress id="seekbar" value="0" max="1"></progress><br>
<button id='back' class='fa fa-backward' onclick="Jukebox.backDatAssUp()"></button>
<button id='play' class='fa fa-play-circle-o' onclick="Jukebox.play()"></button>
<button id='stop' class='fa fa-stop-circle-o' onclick="Jukebox.stop()"></button>
<button id='previous' class='fa fa-step-backward' onclick="Jukebox.previous()"></button>
<button id='next' class='fa fa-step-forward' onclick="Jukebox.next()"></button>
<button id='back' class='fa fa-forward' onclick="Jukebox.preparingToFastForward()"></button>
<button id='random' onclick="Jukebox.random()"> Rnadom song</button>
</div>
</div>
<div class='listOsongs'>
<ol id="playlist">
<h4>Up Next</h4>
<li>
<a id="song" href="http://www.archive.org/download/bolero_69/Bolero.mp3">
Ravel Bolero
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="http://www.archive.org/download/MoonlightSonata_755/Beethoven-MoonlightSonata.mp3">
Moonlight Sonata - Beethoven
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="http://www.archive.org/download/CanonInD_261/CanoninD.mp3">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="https://cf-media.sndcdn.com/MzhGaP8pde4q.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vTXpoR2FQOHBkZTRxLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0OTAyODI2Mzh9fX1dfQ__&Signature=SyWy~ghuKuTgWmoMWvnGgA~HArGVxjKkiD61UUENA4Ke-aUgivz4ANDUmNW68-AOE-o-7X~MYn8ObL4AonSuVsPz3LbGPQcmxD-3N14qpCFEx3F4zwZh43v1-aDzlypCRtY6IaEzun9NksxbABrqqL~BokIKSH0U6yxJmEmKq98e8PrUO24IcDHiSZZlviYI-bRRtdsFXxM1bxbYh-s32Rkoihj~uxTOGVDwAADwexg5VT2Z8xAuMj2NJ9vMCYkydhmZGOG4G~SQ3lZE3ODyEtD5Vf6myOMGjhWIq9qss~u6eHJbrQ2AB~oon-44WIqEknjWT63NP-O-WyHCBmAf4w__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
<li>
<a href="https://cf-media.sndcdn.com/zYh4wOY76Fez.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20velloNHdPWTc2RmV6LjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0OTAyODMzMzN9fX1dfQ__&Signature=nIZ6247SDTQ5LY5pGrdvJkxi3wektW8Kp2uRxOlCg3TthYAq6FeYiu0TJJEdQNNPF8y5WCvbJUi4G553RMwn5xLpxkZR0s0f6B0Fw4m~T18zvic1YH~kRxRVy1ropC2NPax4aI9yCWdKpgFmPNKz21lhFIXoa9F6hnIHaQT0jdFv9eNnjv8CN024j5RnfbFaT1vSzu0AnguXqMlm4uJS8XD~XOT1Y62X4qHzCp685Ahf~Lm9LyhECBXK3nrVF~3QIsxwdYp73Epui29eZsd~7LVCeLwQabU4kvXL9ntTZFft9-JiqLZH4pkmWmSTWlN3Dw~c8dVlZQihruYa81qVPg__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ">
Canon in D Pachabel
</a>
<button class='delete fa fa-times' onclick="Jukebox.delete(this)"></button>
</li>
</ol>
Related
I ran into a problem with my Counter on website which Im building. I made Counter and it's working perfect, the problem is that it works constantly, not when scrolling to the section where it is located. So I want just make it to start count when it comes section where he is. Hope you guys understand me, and I would be grateful to anyone who wants to help me. Here is my JavaScript code:
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let count1 = 0;
let count2 = 0;
let count3 = 0;
function pacijenata() {
count1 = count1 += 1000;
document.querySelector("#number1").innerHTML = count1 + "+";
if( count1 === 10000 ) {
clearInterval(pacijenti);
}
}
function procenatIzlecenosti() {
count2++;
document.querySelector("#number2").innerHTML = count2 + "%";
if( count2 === 70 ) {
clearInterval(procenat);
}
}
function klinike() {
count3++;
document.querySelector("#number3").innerHTML = count3;
if( count3 === 4 ) {
clearInterval(klinika);
}
}
<section id="brojac">
<div class="counterContainer">
<ul>
<li>
<i class="fas fa-hospital-user"></i>
<p id="number1" class="number">10000</p>
<p>Pacijenata</p>
</li>
<li>
<i class="fas fa-universal-access"></i>
<p id="number2" class="number">70</p>
<p>Procenat izlečenosti</p>
</li>
<li>
<i class="fas fa-clinic-medical"></i>
<p id="number3" class="number">4</p>
<p>Klinike</p>
</li>
</ul>
</div>
</section>
What you need is a way to start the counter when a certain element comes into view:
You can use this custom code for that (adapted from this answer):
const counterSection = document.getElementById("brojac");
let counterStarted = false;
const counterScrolledIntoView = () => {
const docViewTop = window.scrollTop;
const docViewBottom = docViewTop + window.height();
const counterSectionTop = counterSection.offset().top;
const counterSectionBottom = counterSection + counterSection.height();
return ((counterSectionBottom <= docViewBottom) && (counterSectionTop >= docViewTop));
}
Then you need to attach an event listener for scroll events:
document.addEventListener('scroll', () => {
const counterInView = counterScrolledIntoView();
if (!counterStarted && counterInView) {
// The element just got scrolled into view, (re)start the counter
counterStarted = true;
/*
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let count1 = 0;
let count2 = 0;
let count3 = 0;
*/
} else if (!counterInView) {
counterStarted = false;
}
})
let count1 = 0;
let count2 = 0;
let count3 = 0;
var pacijenti = setInterval(pacijenata, 300);
var procenat = setInterval(procenatIzlecenosti, 60);
var klinika = setInterval(klinike, 400);
let scrolldown = false;
document.getElementById('brojac').addEventListener('scroll', function(e) {
scrolldown = true;
if( count1 === 10000 ) { clearInterval(pacijenti); }
if( count2 === 70 ) { clearInterval(procenat); }
if( count3 === 4 ) { clearInterval(klinika); }
setTimeout(function(){ scrolldown = false; },250);
});
function pacijenata() {
if( scrolldown === true ){
count1 += 10;
document.querySelector("#number1").innerHTML = count1 + "+";
}
}
function procenatIzlecenosti() {
if(scrolldown === true){
count2 += 1;
document.querySelector("#number2").innerHTML = count2 + "%";
}
}
function klinike() {
if( scrolldown === true ){
count3 += 1;
document.querySelector("#number3").innerHTML = count3;
}
}
#brojac{
height:100px;
overflow:scroll;
}
<section id="brojac">
<div class="counterContainer">
<ul>
<li>
<i class="fas fa-hospital-user"></i>
<p id="number1" class="number">0</p>
<p>Pacijenata</p>
</li>
<li>
<i class="fas fa-universal-access"></i>
<p id="number2" class="number">0</p>
<p>Procenat izlečenosti</p>
</li>
<li>
<i class="fas fa-clinic-medical"></i>
<p id="number3" class="number">0</p>
<p>Klinike</p>
</li>
</ul>
</div>
</section>
You can use Intersection Observer API to initiate the countdown when your target element is visible or intersected in the view port .
I am trying to create a slideshow. I have created two buttons because I want to do it in two ways. One way is when I press the next button to move to the next image(single image movement) and when I press the slideshow button to make it move along with not pressing a button. I didn't manage to fix it. Please help me if you can.
var img = new Array();
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
if (i < img.length - 1)
i++;
else
i = 0;
document.getElementById("img1").src = img[i];
}
startslideshow() {
id = window.setInterval("Next()", 1000);
var x = document.getElementById("txt").value;
id2 = window.clearTimeout("Cancel()", x * 1000)
}
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
</body>
here is the solution that we have came up with
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
<button onclick="stopslideshow()">stopSlideShow</button>
</body>
var img = new Array();
var cur = 0;
var timer = null;
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
cur = (cur < img.length - 1) ? cur + 1 : 0;
document.getElementById("img1").src = img[cur];
}
function startslideshow() {
timer = setInterval(function() {
Next();
}, 500);
}
function stopslideshow() {
if (timer) {
clearInterval(timer);
timer = null;
}
}
So I currently have slider that the user can dynamically fill upon uploading images. I'm using bootstrap for the slider which requires the first slide to have the class "active" in order to work, however when I try to assign that class to the first slide using
"if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
it doesn't recognize the slide id and assigns null to the value, returning "cannot setAttribute of null".
Any advice?
HTML
<div id="slideshow-container">
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<ul class="carousel-inner" id ="carousel-inner">
</ul>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
JS
window.onload = function() {
$('#_uploadImages').click(function () {
$('#_imagesInput').click();
setTimeout(activeness(), 5000)
});
$('#_imagesInput').on('change', function () {
handleFileSelect();
});
}
function handleFileSelect() {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files; //FileList object
var output = document.getElementById("carousel-inner");
var arrFilesCount = [];
var start = $(output).find('li').length;
var end = start+ files.length;
var nonImgCount = 0;
var slide1 = document.getElementById("slide1")
var display = document.getElementById("displayImg")
for (var i = start; i < end; i++) {
arrFilesCount.push(i); // push to array
}
if(start !== 0){
$(output).find('li > nav > a.prev').first().attr('href','#slide-' + (end-1));
$(output).find('li > nav > a.next').last().attr('href','#slide-'+start);
}
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image')) {nonImgCount++; continue;}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
current_i = arrFilesCount.shift();
if (current_i === 0) {
prev_i = files.length - 1; //This is for the first element. The previous slide will be the last image. (i=length-1)
} else {
prev_i = current_i - 1;
}
if (arrFilesCount.length - nonImgCount === 0) {
next_i = 0;
} else {
next_i = current_i + 1; //This is for the last element. The next slide will be the first image (i=0)
}
display.src = picFile.result
output.innerHTML = output.innerHTML + '<li id="slide-' + current_i + '" class="carousel-item">' + "<img class='d-block w-100' src='" + picFile.result + "'" + "title=''/>" + '</li>'; // TODO: Enter Title
});
//Read the image
picReader.readAsDataURL(file);
}
if ($("#carousel-inner").find('li')) {
var slide1 = document.getElementById("slide-0");
slide1.setAttribute ("class", "active");
}
} else {
console.log("Your browser does not support File API");
}
}
i am new to angular 4 i want to develop a shopping cart functionality with some different render functionality in html. i can't able to find any solution till now.
already tried with jquery append function but it wont work in edit functionality in feature.
Below gif image shows my requirement
if i click any catagory it will directly append to top of the list with selected catagory.
Then if i click another catagory for same person it will apply after i click apply button
component.html
<ul class="selected-friends" id="appendtext">
</ul>
<ul class="list-friends" id="listFriends">
<div *ngFor="let data of result" [attr.id]="'FriendList' + data.id" #item>
<li class="checkedCatagory">
<div class="sf-left">
<h3>{{data.fullName}}</h3>
<span id="appendCatagoryList"></span>
</div>
<div class="sf-right">
<div class="edit-con sf-icon" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<i class="fa fa-list" aria-hidden="true"></i>
</div>
<div class="del-con sf-icon" [attr.id]="'#list' + data.id" (click)="delete(data.id)">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</div>
</div>
</li>
<!-- Main List started -->
<li class="mainlistname" data-toggle="collapse" [attr.data-target]="'#list' + data.id">
<label class="catagory_list" [attr.for]="data.id"><input type="checkbox" [attr.id]="data.id" [attr.value]="data.id">
{{data.fullName}}</label>
</li>
<ul class="sub-friends-list collapse" [attr.id]="'list'+data.id">
<p class="mainlistname">Assign Category to this participant</p>
<p class="checkedCatagory">Edit or Assign another category to this participant</p>
<li *ngFor="let catagoryDetail of catagoryList">
<label class="catagory_list">
<input type="checkbox" class="catagory_list_checkbox" (click)="resize(data.id, catagoryDetail.id);addToCart(data.id,catagoryDetail.id,data.fullName,catagoryDetail.title)" [value]="catagoryDetail.id" [attr.id]="'catagoryId'+catagoryDetail.id">
<span [attr.id]="'catagoryName'+catagoryDetail.id">{{catagoryDetail.title}}</span>
<span class="pull-right fnt-16">AED</span>
<span class="pull-right fnt-16" id="'fee'+catagoryDetail.id">{{catagoryDetail.fee}}</span>
<!-- <p>18-99 Years Male/Female</p> -->
<p *ngIf="catagoryDetail.gender === 1">{{catagoryDetail.ageMinMale}}-{{catagoryDetail.ageMaxMale}} Years Male</p>
<p *ngIf="catagoryDetail.gender === 2">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Female</p>
<p *ngIf="catagoryDetail.gender === 3">{{catagoryDetail.ageMinFemale}}-{{catagoryDetail.ageMaxFemale}} Years Male/Female</p>
</label>
<span class="checkedCatagoryhidden">
<p *ngFor="let catagorySelected of catagoryList" [attr.id]="'catagorySelected'+catagorySelected.id">
{{catagorySelected.title}} :
<span *ngIf="catagorySelected.gender === 1">{{catagorySelected.ageMinMale}}-{{catagorySelected.ageMaxMale}} Years Male</span>
<span *ngIf="catagorySelected.gender === 2">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Female</span>
<span *ngIf="catagorySelected.gender === 3">{{catagorySelected.ageMinFemale}}-{{catagorySelected.ageMaxFemale}} Years Male/Female</span>
<span class="pull-right fnt-16">AED {{catagorySelected.fee}}</span>
</p>
</span>
</li>
<li class="checkedCatagory" class="apply checkedCatagory quantity">
<span class="quantity_catagory">Qty: <span [attr.id]="'sectionquantity'+data.id"></span></span>
<span class="catagory_amount">Total: AED <span [attr.id]="'sectionprize'+data.id"></span></span>
<button class="btnapplyqnty">Apply</button>
</li>
</ul>
</div>
</ul>
component.ts
addToCart(id, catagoryId, fullName, catTitle){
var currentUserObj = <any>{};
var self = this;
var sum;
currentUserObj[id] = {};
currentUserObj[id].participantid = id;
currentUserObj[id].participantName = fullName;
// console.log(fullName)
this.cart.cartItems[id] = {};
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
var totalPrize = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
var currentCatagoryName = jQuery('.catagory_list input:checked+#catagoryName'+catagoryId).text();
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryName'].push(jQuery(this).next('').text());
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
currentUserObj[id].participantTotalPrize = sum;
console.log('sum',sum)
this.saveCart();
} else {
var currentCategoryId;
currentUserObj[id]['categoryInfo'] = [];
currentUserObj[id]['categoryName'] = [];
currentUserObj[id]['categoryFee'] = [];
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
currentCategoryId = jQuery(this).val();
currentUserObj[id]['categoryName'].push(jQuery(this).next().text());
currentUserObj[id]['categoryInfo'].push(currentCategoryId);
currentUserObj[id]['categoryFee'].push(Number(jQuery(this).next().next().next().text()));
});
sum = currentUserObj[id]['categoryFee'].reduce(this.add, 0);
currentUserObj[id].participantTotalPrize = sum;
currentUserObj[id].quantity = currentUserObj[id]['categoryInfo'].length;
this.cart.cartItems[id] = currentUserObj[id];
if(currentUserObj[id].quantity === 0) {
console.log("completed delete", this.cart.cartItems[id])
delete self.cart.cartItems[id];
}
this.saveCart();
}
}
add(a, b) {
return a + b;
}
saveCart() {
if (window.localStorage) {
console.log("tfgb",this.cart);
sessionStorage.setItem('cart',JSON.stringify(this.cart));
}
}
resize(id, catagoryId) {
let navObj = this;
var appendSelectedCatagory = document.getElementById('appendtext');
jQuery(appendSelectedCatagory).prepend(jQuery('#FriendList'+id));
if(jQuery("#catagoryId"+catagoryId).is(":checked")) {
this.displaySelectedList(id, catagoryId);
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize);
jQuery('#sectionquantity'+id).html(navObj.quantity);
})
})
} else {
this.eventChecked -= 1;
var totalPrize = 0;
navObj.quantity = 0;
jQuery('#list'+id).find('.catagory_list input:checked').each(function(){
var currentCategoryId = jQuery(this).val();
navObj.eventRegistrationService.getEventCatagoriesList(navObj.eventId)
.subscribe((res)=>{
for(let i in res.data){
var catList = res.data[i];
if(catList.id == currentCategoryId){
totalPrize += catList.fee
navObj.quantity += 1;
}
}
jQuery('#sectionprize'+id).html(totalPrize)
jQuery('#sectionquantity'+id).html(navObj.quantity)
})
})
this.checkedCatagory.pop(catagoryId);
let checkBoxList = '#appendtext #list'+id;
if(jQuery(checkBoxList+' :checkbox:checked').length == 0){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
sessionStorage.removeItem(id);
}
}
}
displaySelectedList(id, catagoryId){
this.eventChecked += 1;
let getselectList = sessionStorage.getItem('selectedFriends');
jQuery('#appendCatagoryList').append(jQuery('#catagorySelected'+catagoryId))
}
delete(id){
jQuery('#listFriends').append(jQuery('#FriendList'+id));
jQuery("#FriendList"+id+ " input[type='checkbox']").prop("checked", false);
console.log('asdasdsa',id);
//this.quantity = 0;
sessionStorage.removeItem(id);
}
Trying to Add and Remove class to click dynamic Buttons, means this button <button class="one"></button> get class dynamically like this: <button class="one text1">text1</button>
So if button one has class .text1 and by click this add class .hide to list item <li class="text1"> like <li class="text1 show">
Same for button two <button class="two"></button> and by click add class <li class="text2 show">
Note: when click button two, then should remove class .show and add new class .hideto button one.
Main HTML:
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>
Script:
$('.label a').each(function() {
var $this=$(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function(){
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function(){
if(clses.indexOf($(this).attr('class')) === -1){
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if(ind === liInd){
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
See Example on Fiddle
I have tried this by add/remove class by click function, but problem is Buttons get class dynamically from List items, so I'm not able to target button.
Any suggestion for other way to do this by JS/ Jquery?
Here is an alternative solution
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
if (txt != '') {
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
}
});
$('button').click(function () {
if ($(this).attr('class')[0] == 'all') {
showAll();
return false; // end this function
}
var allCls = $(this).attr('class').split(' ');
$('li').each(function () {
if (allCls.indexOf($(this).find('a').text()) > -1) {
$(this).closest('li').removeClass('show').addClass('hide');
} else {
$(this).closest('li').removeClass('hide').addClass('show');
}
});
});
function showAll() {
$('li').removeClass('hide').addClass('show');
}
Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/
DEMO
$('.label a').each(function () {
var $this = $(this);
$this.closest('li').addClass($this.text());
});
// Combine This
$('button').each(function () {
var liInd = 0;
var cl = '';
var txt = '';
var clses = [];
var ind = $('button').index($(this)) + 1;
$('li').each(function () {
if (clses.indexOf($(this).attr('class')) === -1) {
clses.push($(this).attr('class'));
liInd = liInd + 1;
}
if (ind === liInd) {
cl = $(this).attr('class');
txt = $(this).find('a').text();
return false; //break
}
});
$('button:nth-child(' + ind + ')').addClass(cl);
$('button:nth-child(' + ind + ')').text(txt);
});
$(document).on('click', 'button',function(e){
var textClass = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('text') === 0;
}).join();
console.log(textClass);
$('li').removeClass('show').addClass('hide')
$('li').each(function(){
if($(this).hasClass($.trim(textClass))){
$(this).removeClass('hide').addClass('show');
} else {
$(this).removeClass('show').addClass('hide');
}
})
})
.show{display:list-item;}
.hide{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="main-id">
<button class="one"></button>
<button class="two"></button>
<ul>
<li>
<!--List 1-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 2 is Same-->
<div class="label">
text1
</div>
</li>
<li>
<!--List 3 is different-->
<div class="label">
text2
</div>
</li>
</ul>
</div>