Play a certain audio track when clicked - php

All the songs have a .song class but it plays the first song on the playlist. It's basically the play button for the whole playlist. I've play around with this for awhile and I can't seem to get it right. It might be the simplest thing too. I have the song populate with php depending on the album. I want people to be able to click a certain song and that song plays.
example: http://mixtapemonkey.com/mixtape?m=637
Also if you know how to toggle between the play and stop button, that would be nice to throw in there too. Thanks!
<script>
jQuery(document).ready(function(){
i=0;
nowPlaying = document.getElementsByClassName('playsong');
nowPlaying[i].load();
$('.play').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.song').on('click', function() {
nowPlaying[i].play();
callMeta();
});
$('.pause').on('click', function() {
nowPlaying[i].pause();
callMeta();
});
$('.next').on('click', function() {
$.each($('audio.playsong'), function(){
this.pause();
});
++i;
nowPlaying[i].load();
nowPlaying[i].play();
callMeta();
})
function callMeta(){
var trackTitle = $(nowPlaying[i]).attr('data-songtitle');
$('.songtitle').html(trackTitle);
var trackArtist = $(nowPlaying[i]).attr('data-songartist');
$('.songartist').html(trackArtist);
}
})

You have to target the audio element inside each .song, now you're always targeting the first one.
To toggle, check if the audio is paused, and play() or pause() accordingly :
$('.song').on('click', function() {
var audio = $('.playsong', this).get(0);
if (audio.paused) {
audio.play();
}else{
audio.pause()
}
callMeta();
});
EDIT:
with a few changes, I'm guessing something like this would work :
jQuery(document).ready(function($){
var audios = $('.playsong');
var audio = audios.get(0);
audio.load();
$('.play').on('click', function() {
callMeta(audio);
});
$('.song').on('click', function() {
audio = $('.playsong', this).get(0);
callMeta(audio);
});
$('.pause').on('click', function() {
audio.pause();
});
$('.next').on('click', function() {
var i = audios.index(audio);
audio = $(audios).get(i+1);
callMeta(audio);
});
function callMeta(elem){
audios.each(function(i,el) {
if (!el.paused) {
el.pause();
el.currentTime = 0;
}
});
elem.load();
elem.play();
$(elem).on('ended', function() {
$('.next').trigger('click');
});
$('.songtitle').html($(elem).attr('data-songtitle'));
$('.songartist').html( $(elem).attr('data-songartist') );
}
});

Just for clarity - you say the songs have class "song", yet your code says "playsong". A typo, perhaps?
The first song always plays because you always play nowPlaying[i], and i=0 - which only changes when $('.next').on('click', function(){}) is called! You need a way to either change i when a song is clicked, or make the HTML more "modular" (I use this loosely) around each song.
Example HTML:
<audio id="coolSong1">
<!-- Sources -->
</audio>
<!-- I'm not sure what you're using as play, pause, next buttons, so I'll use buttons -->
<input type="button" class="play" name="coolSong1" value="play" />
<input type="button" class="pause" name="coolSong1" value="pause" />
<input type="button" class="next" name="coolSong1" value="next" />
Corresponding script:
$(".play").click(function(event) {
document.getElementById(event.target.name).play();
});
$(".pause").click(function(event) {
document.getElementById(event.target.name).pause();
});

Related

Preload audio and apply css during playback

I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>

Create upload status for each file JQuery and AJAX

I have a AJAX upload working and all ready to go, there really isnt any information the user can see except a percent and a progress bar. what i want to do is create a div for each file and show progress for each. Do i have to use flash or can i do this all from jquery because i got the ajax part done all thats left is to make the divs for each file and show a progress bar for each. if i were to upload multiple files it would show 1 progress bar that is uploading all the files together, i want to do it seperate for each. so basicly have one form to select multiple files and create a div for each file to show the percent complete of each.
JavaScript:
$('#Submit').click(function(event)
{
if ( !("FormData" in window) ) {
$('#Wrapper').append('<div class="DMsg"><label class="DText">You Are Using An Outdated Browser, Please Upgrade To Google Chrome Or Firefox, If You Dont Most Features Will Not Work. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
else
{
function Upload()
{
event.preventDefault();
event.stopPropagation();
var FInput = $('#Files').val();
if(FInput != '')
{
var Data = new FormData();
var Files = document.getElementById('Files');
for(var I = 0; I < Files.files.length; ++I)
{
var FilesName = Files.files[I].name;
Data.append('File[]', Files.files[I]);
}
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event)
{
if(event.lengthComputable)
{
Percent = event.loaded / event.total;
Progress = document.getElementById('Progress');
Loaded = Math.round(Percent * 100);
$('#Progress').progressbar({
value: Loaded
});
$('#Loaded').text(Loaded + '%');
}
else
{
$('#Progress').text('There Was An Error Getting The Percent');
}
});
Request.upload.addEventListener('load', function(event)
{
});
Request.upload.addEventListener('error', function(event)
{
alert('Upload Failed.');
});
Request.addEventListener('readystatechange', function(event)
{
if(this.readyState == 4)
{
if(this.status == 200)
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">Your Files Have Finished Uploading. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
$('#Loaded').text('100%');
$('#Progress').progressbar({
value: 100
});
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
else
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">There Was An Error In Uploading Your Files. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
}
});
Request.open('POST', 'Upload.php');
Request.setRequestHeader('Cache-Control', 'no-cache');
Progress.style.display = 'block';
Request.send(Data);
}
else
{
$('#Wrapper').append('<div class="DMsg"><label class="DText">Please Select A File / Files. Click Anywhere To Dismiss.</label></div>');
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
var Close = setTimeout(function()
{
$('.DMsg').slideUp('slow', function()
{
$('.DMsg').remove();
});
}, 10000);
}
}
var EachFile = 0
$.each($('#Files')[0].files, function()
{
++EachFile;
Upload();
});
}
});
HTML:
<div id="UForm">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" class="Files" id="Files" name="File[]" />
<input type="submit" name="Submit" class="AB" id="Submit" value="Upload!" />
<div id="Progress"></div>
<div class="Caption"><label id="Loaded"></label></div>
</form>
</div>
Sorry for lots of code.
It shows a big load bar because you are searching for elements with the DMsg class and jquery searches from top-down so it will always find the first loading bar you set.
You need a way to set a different id to each new bar or when you do the
$('#Wrapper').find('.DMsg').hide().slideDown('slow');
find a way to get the last result.

Jquery onblur not working second time

I have build a jQuery PHP based instant search, I have used some fading effect along with onblur event, everything is working fine except when clicking anywhere in body for first time results disappear, but again if hover over to input field to bring result and then clicking in body results do not disappers,
i.e onblur does not work second time.
Please see my code for better understanding and suggest any possible way to do this.
JQuery:
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').keyup(function(){ $('#search-result').fadeIn(400);});
$('#search-input').blur(function(){$('#search-result').fadeOut(400);});
$('#search-input').click(function(){$('#search-result').fadeIn(400);});
$('#search-input').mouseenter(function(){ $('#search-result').fadeIn(400);});
$('#search-input').mouseleave(function(){ $('#search-result').fadeOut(400)});
$('#search-result').mouseenter(function(){ $('#search-result').stop();});
$('#search-result').mouseleave(function(){ $('#search-result').stop();});
});
HTML:
<input name="keyword" type="text" size="50" id="search-input" value = '';" />
<div id="search-result"></div><!--end of search-result-->
Why have you bind so many events to #search-result??
Check below code if it helps you.
<script language="javascript" >
$(document).ready(function () {
$('#search-input').keyup(function(){
var keyword=$(this).val();
$('#search-result').fadeIn(400);
//$('#search-result').html('ajax result data');
$.get('../search/instant-search.php', {keyword: keyword}, function(data){
$('#search-result').html(data);
});
});
$('#search-input').bind('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').bind('focus', function() {
$('#search-result').fadeIn(400);
});
});
</script>
You can try this:
$('#search-input').on('blur', function() {
$('#search-result').fadeOut(400);
});
$('#search-input').on('mouseleave', function() {
// on mouse leave check that input
// is focused or not
// if not focused the fadeOut
if( !$(this).is(':focus')) {
$('#search-result').fadeOut(400);
}
});
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
DEMO
According to comment
$('#search-input').on('focus mouseenter', function() {
$('#search-result').fadeIn(400);
});
$(document).on('click', function(e) {
if(e.target.id != 'search-input' && e.target.id != 'search-result') {
$('#search-result').fadeOut(400);
}
})
DEMO

jquery click function inside form submit function

I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});

Javascript handling multiple IDs

I'm completely new in javascript. The problem is, I have multiple textarea and div which 'echo'-ed out via PHP with ID (for example textarea_1,textarea_2...), and I wanna do something like, when the textarea is on focus, only that particular textarea which being focussed will slide down and expand.
Html
<textarea id="comment_textarea_1"></textarea>
<div id="button_block_1"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2"></textarea>
<div id="button_block_2"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
Javascript
$(document).ready(function () {
var $this = $(this);
var $textareaID = $this.attr("id").replace("comment_textarea_");
var $buttonblockID = $this.attr("id").replace("button_block_");
var $cancelID = $this.attr("id").replace("cancel_");
var $textarea = $('#'+$(textareaID));
var $button = $('#'+$(buttonblockID));
var $cancel = $('#'+$(cancelID));
$textarea.focus(function(){
$textarea.animate({"height": "85px",}, "fast" );
$button.slideDown("fast");
return false;
});
$cancel.click(function(){
$textarea.animate({"height": "18px",}, "fast" );
$button.slideUp("fast");
return false;
});
});
Thank you!
I explained it in the code. Try this.
$(document).ready(function () {
// select all the textareas which have an id starting with 'comment_textarea'
var $textareas = $("textarea[id^='comment_textarea']");
$textareas.on("focus",function(){
// now $(this) has the focused element
$(this).animate({"height": "85px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideDown("fast");
});
$textareas.on("focusout",function(){
// now $(this) has the focused out element
$(this).animate({"height": "18px",}, "fast" );
// find the button block of this div and animate it
$("div[id^='button_block']",$(this)).slideUp("fast");
});
});
I believe I understand what you're attempting. Please let me know if the following is the effect you're after:
$("[id^='comment_textarea_']").on({
focus: function(){
$(this).stop().animate({ height: '85px' }, 750).next().slideDown();
},
blur: function(){
$(this).stop().animate({ height: '20px' }, 250).next().slideUp();
}
});​
Fiddle: http://jsfiddle.net/pwype/2/
I'm confused. The above answers are concentrating on using ID's... The last time I checked this is one of the main reasons we have the class attribute?
For example:
$(document).ready(function()
{
$('.comment-textarea').focus(function()
{
$(this).animate(
{
'height' : '85px'
}, 'fast');
$(this).next('.button-block').slideDown('fast');
}).blur(function()
{
$(this).animate(
{
'height' : '18px'
}, 'fast');
$(this).next('.button-block').slideUp('fast');
});
});
And the HTML:
<textarea id="comment_textarea_1" class="comment-textarea"></textarea>
<div id="button_block_1" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_1">Cancel</button></div>
<textarea id="comment_textarea_2" class="comment-textarea"></textarea>
<div id="button_block_2" class="button-block"><button type="submit">Submit</button><button type="submit" id="cancel_2">Cancel</button></div>
And a little fiddle to show it working:
http://jsfiddle.net/ngYMh/

Categories