Home dynamic html5 audio playlist with ajax
Reply: 1

dynamic html5 audio playlist with ajax

jedrek
1#
jedrek Published in 2018-02-12 22:53:16Z

I’d like to create a simple html5 audio player that plays songs of a dynamic playlist. I have this page that loads properly and if a link is clicked the song starts to play and When it ends next one in list starts.. all good.

I also have this search function that returns song links from a db via php in a new dynamicly created list on the same page.. that works too. But as soon as one of ”the new” (search results) links are clicked, the song will open in a new browser tab. I’d like it to open in the ”default” player as all other tunes are doing.

What am I missing here? I think something must be misplaced in my code but I cannot figure out what..

Below is my code...

index.php

<html>
<meta name="viewport" content="width=400"> 

<head>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.js'></script>

<style>

#playlist,audio{
    background:#666;
    width:100%;
    padding:5px;
    /*margin:5px;*/
    display: block;
    }
.active a{
    color:#5DB0E6;
    text-decoration:none;
    }
li a{
    color:#eeeedd;
    background:#333;
    padding:5px;
    display:block;
    }
li a:hover{
    text-decoration:none;
    }

</style>

<script>
function searchTrack(str) {
    if (str == "") 
    {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } 
    else 
    {
        if (window.XMLHttpRequest) 
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

xmlhttp.onreadystatechange = function() 
    {
        if (this.readyState == 4 && this.status == 200) 
            {
            document.getElementById("txtHint").innerHTML = this.responseText;
            }
    };
            xmlhttp.open("GET","search.php?q="+str,true);
            xmlhttp.send();
    }

}
</script>



</head>

<script>
$(document).ready(function () {
var audio;
var playlist;
var tracks;
var current;

init();
function init() {
    current = 0;
    audio = $('#audio');
    playlist = $('#playlist');
    tracks = playlist.find('li a');
    len = tracks.length - 1;
    audio[0].volume = 1;
    audio[0].play();
    playlist.find('a').click(function (e) {
        e.preventDefault();
        link = $(this);
        current = link.parent().index();
        run(link, audio[0]);
    });
    audio[0].addEventListener('ended', function (e) {
        current++;
        if (current == len+1) { 
            current = 0;
            link = playlist.find('a')[0];
        } else {
            link = playlist.find('a')[current];
        }
        run($(link), audio[0]);
    });
}
function run(link, player) {
    player.src = link.attr('href');
    par = link.parent();
    par.addClass('active').siblings().removeClass('active');
    audio[0].load();
    audio[0].play();
    }
})

</script>

<body>

<form>
Search: <input type="text" onkeyup="searchTrack(this.value)">
</form>

<br>

<audio id="audio" preload="none" tabindex="0" controls="" type="audio/mpeg" width="100%">
</audio>

<ul id="playlist">

    <div id="txtHint">
        <?php 
            include 'connect.php';
            $sql="SELECT * FROM music ORDER BY RAND() LIMIT 25";
            $result = mysql_query($sql,$conn);

            while($row = mysql_fetch_array($result)) {
                echo '<li><a href="' . $row['location'] . '">' . $row['artist'] . ' - ' . $row['title'] . '</a></li>';
            }
        ?>  
    </div>
<ul>


</body>
</html>

and search.php

<?php
include 'connect.php';

$query = $_GET['query']; //input from search

$sql="SELECT * FROM music WHERE artist LIKE '%".$query."%' OR title LIKE '%".$query."%' LIMIT 25";
$result = mysql_query($sql, $conn) or die (mysql_error());

while($row = mysql_fetch_array($result)) {

echo '<li><a href="' . $row['location'] . '">' . $row['artist'] . ' - ' . $row['title'] . '</a></li>';}

mysql_close($conn);
?>
Niels Bom
2#
Niels Bom Reply to 2018-02-12 23:15:05Z

I think the problem is that this piece of JS:

playlist.find('a').click(function (e) { // etc

..is only executed during init(). So the event binding works, but only for all a elements in li elements that are there from the beginning. Any li's that are added to the page later on do not have that event bound to them.

The solution would be to not bind to the a element or li element but bind to the ul element and then in JS figure out which element inside of the list was clicked and then perform the JS action on that. Then it doesn't matter whether the list item was there from the beginning or was added later.

You should be able to do that because of "bubbling". See here for more info: https://javascript.info/bubbling-and-capturing

Good luck!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314181 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO