how to get soundcloud follower count using JavaScript - javascript

Does anyone know how to put the amount of followers from soundcloud into a JavaScript variable so I can have it ring a notification when I hit 1K follows I have code that I have got from code pen by another user that I have forked
my code is -> here
and if you do not want to go to see it I have included it below
HTML
' <head>
<meta http-equiv="refresh" content="5">
</head>
<div class="card">
<div class="icon">
<i class="fa fa-soundcloud fa-3x"></i>
</div>
<div class="count"></div>
<span>followers</span>
</div>
<audio id="myAudio">
<source src="file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/echoed-ding.mp3" type="audio/mpeg">
</audio>
<p id="demo"></p>
<button onclick="wright()" type="button">wright</button>
<!--
<button onclick="pauseAudio()" type="button">Pause Audio</button>
!-->'
css
#import url(https://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans+Condensed:300);
$primary-font: "Montserrat";
$secondary-font: "Open Sans Condensed";
body {
background-color: #1F282D;
.card {
width: 145px;
height: 187px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
opacity: 0;
transition: .1s opacity;
/*border: 1px solid #fff;
border-radius: 6px;*/
&.visible {
opacity: 1;
}
.icon {
position: relative;
top: .85em;
}
.count {
font-family: $primary-font;
font-size: 4em;
line-height: 1em;
bottom: 0.9em;
}
span {
font-family: $secondary-font;
text-transform: uppercase;
font-size: 1.1em;
letter-spacing: 2px;
bottom: 1.1em;
}
.count, span, .icon i.fa {
position: absolute;
left: 50%;
transform: translateX(-50%);
color: #fff;
}
}
}
javascript
var abbrev = {
1e3: "K",
1e6: "M"
};
aja()
.method("GET")
.url('https://api.soundcloud.com/users/awesomesauce105?consumer_key=8bcccc3476eaa137a084c9f0c041915f')
.on('200', function(res) {
var followersCount = res.followers_count;
Object.keys(abbrev).map(function(k) {
k = +k;
if (followersCount > k) {
var a = followersCount / k,
short = a.toString().length > 3 ? Math.round(a * 10) / 10 : a;
followersCount = short + abbrev[k];
}
});
if (followersCount !== undefined) {
$(".card .count").text(followersCount);
$(".card").addClass("visible");
}
})
.go();
var audio = new Audio('file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3');
function playMyAudio() {
audio.play()
}
var x = document.getElementById("myAudio");
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
function wright(){
document.getElementById("demo").innerHTML = ;
}
My goal is to ring a notification when I hit 1K follows I have a mp3 located on my chromebook at file:///home/chronos/u-95bb3831b1fe3a2c6fb7e71045f629e9434b1484/Downloads/html%205%20up/echoed-ding.mp3
and I am trying to get it to play a couple of times so I can celebrate. I do not know how to check the amount of followers I have so I used code from someone else but since I did not make it I do not know what is happening in the JavaScript department and thus I cannot just figure it out on my own because I normally would just look up how to run a function when a variable hits a certain variable... and in turn would activate the x.play() to play the sound... if you have any suggestions please let me know thanks!

You can use Soundcloud's Javascript SDK to tap into their API from the client. So add this to your HTML:
<script src="https://connect.soundcloud.com/sdk/sdk-3.1.2.js"></script>
<script>
SC.initialize({
client_id: 'YOUR_CLIENT_ID' // edit this with your API credential
})
</script>
Unfortunately, there's no way to receive a "notification" from Soundcloud's API when your followers hit a certain number. Instead, you can write a function that looks up the user periodically, and do something special when the follower count is where you want it. So in your Javascript, something like:
function pollSoundcloud (interval) {
var timer = setInterval(function () {
SC.get('/user/YOUR_USER_ID').then(function (user) {
if (user.followers_count >= 1000) {
clearInterval(timer)
alert('You just reached 1000 followers!') // or do something else
}
})
}, interval)
}
pollSoundcloud(10000) // will check every 10 seconds

Related

JavaScript change image on keypress

So I watched a tutorial on YouTube showing me how to make a simple version of the dino-game using JavaScript. I followed that tutorial and afterwards, I decided to add some changes to the code. After changing a few aspects, this is what I have:
// Start check
setTimeout(function startobstacles() {
obstacle.classList.add("animateObstacle")
}, 3000);
// Variable definition
var character = document.getElementById('character');
var obstacle = document.getElementById('obstacle');
var score = 0
var dead = false
// Jump movement
function jump() {
character.classList.add("animateJump");
setTimeout(function() {
character.classList.remove("animateJump");
}, 500);
}
// Check if player lost
var checkDead = setInterval(function() {
var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue("left"));
if (obstacleLeft < 20 && obstacleLeft > 0 && characterTop >= 130) {
obstacle.style.animation = "none";
obstacle.style.diaplay = "none";
dead = true
var check = alert("You lost! Your score was " + score + ".");
if (typeof check == 'undefined') {
location.reload();
}
}
}, 10);
// Scoring system
setInterval(function() {
if (dead == false) {
score += 1;
highScore = window.localStorage.getItem('high_score');
if (score > highScore || highScore == null) {
window.localStorage.setItem('high_score', score);
}
highScore = parseInt(window.localStorage.getItem('high_score'));
document.getElementById("scoreBoard").innerHTML = "Your score: " + score + " | Your personal best: " + highScore;
}
}, 2000)
* {
padding: 0;
margin: 0;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome and Opera */
}
#scoreBoard{
font-family: cursive;
font-size: 16px;
}
#game {
width: 500px;
height: 200px;
border: 1px solid black;
background-image: url("images/background.png");
}
#character {
width: 10px;
height: 50px;
background-color: transparent;
position: relative;
top: 142px;
}
#obstacle {
width: 20px;
height: 20px;
background-color: transparent;
position: relative;
top: 130px;
left: 450px;
}
.animateJump {
animation: jump 0.5s
}
.animateObstacle {
animation: obstacle 2s infinite linear;
}
#keyframes obstacle {
0%{left: 429px;}
100%{left: -429px;}
}
#keyframes jump {
0%{top: 142px;}
50%{top: 100px;}
100%{top: 142px;}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script type="text/javascript">
alert("Welcome to Mouse Run! In this game, your goal is to avoid touching the infected cheese. If you do, you lose! Press \"OK\" to start.")
alert("Use LEFT CLICK to jump!")
</script>
<link rel="icon" href="images/thumbnail.png">
<meta charset="utf-8">
<title>Mouse Run</title>
<link rel="stylesheet" href="style.css">
</head>
<body onclick="jump();" style="background-color: lightblue">
<!-- Main Game -->
<p id="title"></p>
<div id="game">
<div id="character"><img class="noselect" src="images/player.png"></div>
<div id="obstacle"><img class="noselect" src="images/obstacle.png" style="height: 20px; width: 50px;"></div>
</div>
<p id="scoreBoard"></p>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
With all this code, I get something like this:
So right now, the character can only jump. I want to give it the ability to dash. My plan was to make a second image for the mouse and swap between that image when the user presses a certain key to dash. The problem is that I don't really know how to swap images in this situation.
So does anyone know how to do this? If you might, please let me know. Any help is appreciated!
Changing the src of the image should work.
function jump() {
let characterImage = character.getElementsByTagName("IMG")[0];
characterImage.src = "images/player_dash.png"; // Path to the new image (change it to the actual name)
setTimeout(function() {
characterImage.src = "images/player.png";
}, 500);
}
You actually dont need the img tag under character div. You can set the background-image of the character div. And change the background-image on .animateJump style.
See the Snippet below:
// Start check
setTimeout(function startobstacles() {
obstacle.classList.add("animateObstacle")
}, 3000);
// Variable definition
var character = document.getElementById('character');
var obstacle = document.getElementById('obstacle');
var score = 0
var dead = false
// Jump movement
function jump() {
character.classList.add("animateJump");
setTimeout(function() {
character.classList.remove("animateJump");
}, 500);
}
// Check if player lost
var checkDead = setInterval(function() {
var characterTop = parseInt(window.getComputedStyle(character).getPropertyValue("top"));
var obstacleLeft = parseInt(window.getComputedStyle(obstacle).getPropertyValue("left"));
if (obstacleLeft < 20 && obstacleLeft > 0 && characterTop >= 130) {
obstacle.style.animation = "none";
obstacle.style.diaplay = "none";
dead = true
//var check = alert("You lost! Your score was " + score + ".");
if (typeof check == 'undefined') {
location.reload();
}
}
}, 10);
// Scoring system
setInterval(function() {
if (dead == false) {
score += 1;
highScore = window.localStorage.getItem('high_score');
if (score > highScore || highScore == null) {
window.localStorage.setItem('high_score', score);
}
highScore = parseInt(window.localStorage.getItem('high_score'));
document.getElementById("scoreBoard").innerHTML = "Your score: " + score + " | Your personal best: " + highScore;
}
}, 2000)
* {
padding: 0;
margin: 0;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome and Opera */
}
#scoreBoard{
font-family: cursive;
font-size: 16px;
}
#game {
width: 500px;
height: 200px;
border: 1px solid black;
background-image: url("https://i.stack.imgur.com/4gZSc.png");
background-size: 107%;
background-repeat: no-repeat;
}
#character {
width: 10px;
height: 50px;
background-color: transparent;
position: relative;
top: 142px;
}
#character{
background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSr7LnFBd0jsRiAUQ7jqerEKt1CujA3yFJFQA&usqp=CAU");
width: 20px;
background-size:contain;
background-repeat: no-repeat;
}
#obstacle {
width: 20px;
height: 20px;
background-color: transparent;
position: relative;
top: 130px;
left: 450px;
}
#character.animateJump {
animation: jump 0.5s;
background-image: url("https://banner2.cleanpng.com/20180616/vvf/kisspng-disco-dance-silhouette-clip-art-bailando-5b2586082d6d97.6157716515291858001861.jpg");
background-size: contain;
}
.animateObstacle {
animation: obstacle 2s infinite linear;
}
#keyframes obstacle {
0%{left: 429px;}
100%{left: -429px;}
}
#keyframes jump {
0%{top: 142px;}
50%{top: 100px;}
100%{top: 142px;}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script type="text/javascript">
//alert("Welcome to Mouse Run! In this game, your goal is to avoid touching the infected cheese. If you do, you lose! Press \"OK\" to start.")
//alert("Use LEFT CLICK to jump!")
</script>
<link rel="icon" href="images/thumbnail.png">
<meta charset="utf-8">
<title>Mouse Run</title>
<link rel="stylesheet" href="style.css">
</head>
<body onclick="jump();" style="background-color: lightblue">
<!-- Main Game -->
<p id="title"></p>
<div id="game">
<div id="character"></div>
<div id="obstacle"><img class="noselect" src="https://i.stack.imgur.com/XHR5g.png" style="height: 20px;"></div>
</div>
<p id="scoreBoard"></p>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
Look for the comment "Added below lines" and "Added above lines"
You can test it here also.

CSS style shows after refresh and then goes invisible with Knockout

So I have a new notification style ring and green circle with unread notifications in it this circle only is visible when you have new notifications.
when page is refreshed even if you dont have a notification the circle is visible for a second and then goes invisible
If there is a new notification still when refreshed circle shows up empty or with zero and then goes invisible and then with correct number
HTML:
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
CSS:
.unseen-notification-show {
content: '';
display: block !important;
position: absolute;
top: -10px;
right: -8px;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
self.searchModel = new AuthorizedSearchViewModel();
self.Header = ko.observable(new HeaderModel());
self.UnSeenMessagesCount = ko.observable(0);
self.Messages = ko.observableArray();
self.CanShowRemindProfile = ko.observable(false);
self.Remind = ko.observable(new RemindModel());
self.LoadUserInformation = function () {
$.post('/User/GetUserInfoForDashboardHeader',
function (response) {
InitTawkChat(response);
self.Header(new HeaderModel(response));
if ($('#accountId').length > 0) {
$('#accountId').html(response.accountId);
}
}, "json").done(function () { console.warn("loaderOff"); });
};
self.GetRemindProfile = function () {
self.CanShowRemindProfile(false);
$.post('/User/GetRemindProfile', function (result) {
if (result) {
self.CanShowRemindProfile(true);
self.Remind(new RemindModel(result));
}
});
};
self.GetMessages = function () {
$.post('/Messages/GetAll', {
page: 1,
pageSize: 4
}, function (result) {
var notifications = [];
_.map(result.Notifications, function (item) {
notifications.push(new MessageModel(item));
});
self.Messages(notifications);
self.UnSeenMessagesCount(result.UnseenNotifications);
});
};
Remove !important from display property in your css and let knockout inline handle display.
function viewModel(){
var self = this;
self.UnSeenMessagesCount = ko.observable();
self.initData = function(){
//dummy setTimeout for your ajax get.
setTimeout(function(){
self.UnSeenMessagesCount(4);
},1000);
}
}
var vm = new viewModel();
vm.initData();
ko.applyBindings(vm);
.unseen-notification-show {
content: '';
display: block;
position: absolute;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
Sounds like some loading issues. Try moving your css from being loaded in the top of the HTML, to be loaded in the bottom/footer.
What you want to do, is to hide the circle until the result is loaded (either 0 or 1,2,3,4.. and so on. Depending on the number of notifications).
In your div you got this line style="display:none"> which hides the circle. Thats good!
Now you should make sure that the style for .unseen-notification-show which contains display: block !important; that shows the circle - Should not be run before the calculation of the number to show is done.
One way could be to place the file that loads your css to the bottom of the HTML (like moving your <link rel="stylesheet" href="test.css" />). Or another way is to only use css for the hiding and then use javascript/jQuery for showing the cirle.
If this didn't help - then please provide the code you use to generate the number.
I think the issue is due to
self.UnSeenMessagesCount = ko.observable(0);
so when your modal is getting created it is initialized with value 0. So when you refresh the page initially it is 0 but when self.getMessage is called it updates your value.

Countdown with setInterval going too fast

could someone help me, I would like to know how to make it so the countdown doesn't go faster every time I click? I assume clear interval but not sure what I need to put. Thanks
var cD = 100;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
}
}
$(".countdown-trigger").click(function(){
cD = 100;
setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>
The issue is because you never clear the previous timeout on each successive click, hence after 3 clicks you have three timers all decrementing the value every 10ms.
To fix this call clearTimeout() when cD hits 0. Also note that you would need a mechanism to prevent starting multiple intervals while the previous one is still running, or else you'll have the same issue. To do that you can use a boolean flag. Try this:
var cD = 100, interval, running = false;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(('00' + cD).slice(-2) + "s");
} else {
clearInterval(interval);
running = false;
}
}
$(".countdown-trigger").click(function() {
if (running)
return;
cD = 100;
running = true;
interval = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
<div class="countdown-trigger"></div>
var cD = 100;
var myOtherVar;
function countDown() {
if (cD > 0) {
cD -= 1;
$(".countdown").html(cD +"s");
} else {
clearInterval(myOtherVar);
}
}
$(".countdown-trigger").click(function(){
cD = 100;
myOtherVar = setInterval(countDown, 10);
});
.countdown-trigger {
height: 50px;
width: 100px;
background-color: blue;
}
.countdown {
font-family: "Teko", sans-serif;
font-size: 100px;
line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
</div>
<div class="countdown-trigger">
</div>
You're right. You just need to clear your interval. Every time you click the area it sets up another set of events that occur every 10ms & that is why it continues to get faster & faster.

audio pause not working, global - local variable issue?

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";}
}

Timer is not counting down in Fixed position

I am developing one game app in HTML5 for android devices. In that game I am using simple count down method with setInterval method and I am displaying that counter in timer div. When I make div element position is fixed then count down is not running whenever I touched the screen then only count down starts and stops. BUT this is running good in absolute position, I don't want to make that div as absolute. I have tried all the possibilities, No luck
Please any one help me to resolve this problem
Here is my code
HTML:
<div id="time">
<p id="txt2"></p>
</div>
CSS:
#time {
right: 150px;
top: 11px;
z-index: 999;
position: fixed;
font-size: 30px;
color: rgb(0, 0, 0);
font-weight: bold;
font-size: 30px;
color: #FFFFFF;
}
JS:
function timedCount(){
sec = 119 - c;
document.getElementById("txt2").innerHTML = sec;
c=c+1;
tt=setTimeout(function(){
timedCount()
},10000);
}
function doTimer(){
//alert("TImer starts");
if (!timer_is_on){
timer_is_on=1;
timedCount();
}
}
function stopCount(){
//alert("Timer stops");
clearTimeout(tt);
timer_is_on=0;
//c = 0;
}
Please check this one I refered http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_stop
Try this one with jquery
<!DOCTYPE html>
<html>
<head>
<style>
#time {
right: 150px;
top: 11px;
z-index: 999;
position: fixed;
font-size: 30px;
color: rgb(0, 0, 0);
font-weight: bold;
font-size: 30px;
color: red;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var c=1, timer_is_on = 0, tt;
$(document).ready(function(){
doTimer();
function doTimer() {
if (!timer_is_on){
timer_is_on=1;
timedCount();
}
}
function timedCount() {
var sec = 119 - c;
$("#txt2").html(sec);
//alert(c);
c = c + 1;
tt = setTimeout(function () {
timedCount()
}, 10000);
}
function stopCount() {
//alert("Timer stops");
clearTimeout(tt);
timer_is_on = 0;
//c = 0;
}
});
</script>
</head>
<body>
<div id="time">
<p id="txt2"></p>
</div>
</body>
</html>
Check this link

Categories

Resources