I need to display list of all songs saved in array. I need to get audio duration for each list element. Can I do it automatically or do I have to add duration to the array myself?
let tracks = [
{
name: "Song 1",
artist: "Monica",
path: "..song1.mp3",
},
{
name: "Song 2",
artist: "Carol",
path: "..song2.mp3"
},
{
name: "Song 3",
artist: "Sam",
path: "..song3.mp3"
},
];
let list = "<ul>";
for (let i = 0; i < tracks.length; i++) {
list += '<li>';
list += '<div class="name">' + tracks[i].name + '</div>';
list += '<div class="artist">' + tracks[i].artist + '</div>';
list += '<div class="duration">XX:XX</div>';
list += 'Download';
list += '</li>';
}
let list = "</ul>";
playlist.innerHTML = list;
You need to add audio element to get the duration and make this element as hidden if you don't want to display it.
You can also use any plugin if you needed.
let tracks = [{
name: "Song 1",
artist: "Monica",
path: "https://download.samplelib.com/mp3/sample-3s.mp3",
},
{
name: "Song 2",
artist: "Carol",
path: "https://download.samplelib.com/mp3/sample-6s.mp3"
},
{
name: "Song 3",
artist: "Sam",
path: "https://download.samplelib.com/mp3/sample-9s.mp3"
},
];
function getDuration() {
var audio = document.getElementsByTagName('AUDIO');
for (let i = 0; i < audio.length; i++) {
let duration = document.querySelector('[id="myAudio' + i + '"]').duration;
console.log(duration);
document.getElementById("duration" + i).innerHTML = duration;
}
}
let list = "<ul>";
for (let i = 0; i < tracks.length; i++) {
list += '<li>';
list += '<div class="name">' + tracks[i].name + '</div>';
list += '<div class="artist">' + tracks[i].artist + '</div>';
list += '<div id="duration' + i + '" class="duration">00:00</div>';
list += 'Download';
// you need to add hidden audio element to get the duration
list += '<audio hidden id="myAudio' + i + '" controls><source src="' + tracks[i].path + '" type="audio/mpeg"> Your browser does not support the audio element.</audio>'
list += '</li>';
}
list += "</ul>";
var playlist = document.getElementById("playListDiv");
playlist.innerHTML = list;
// get duration after the html is loaded
setTimeout(function() {
getDuration();
}, 1000);
<html>
<body>
<div id="playListDiv"></div>
</body>
</html>
You can also add duration in array to avoid extra Audio element
Related
So I got this code to push all items from an array inside the DOM.
How do I make the click event work for each item?
Edit:
let items = {
item1: {
cost: 2200,
owned: 0,
type: "item type",
name: "item1",
desc: "item1 desc.",
img: "img/item1.gif"
},
item2: {
cost: 4400,
owned: 0,
type: "item type",
name: "item2",
desc: "item2 desc.",
img: "img/item2.gif"
},
};
for (let key of Object.keys(items)) {
if (items[key].owned==0) {
var el = document.createElement('div');
var domString = '<div class="item"><div class="w3 h3 bg-center contain" style="background-image:url(' + items[key].img + ')"></div><span>'+ items[key].name +'</span><span>Price: '+ items[key].cost +'</span><span>'+ items[key].desc +'</span></div>';
el.innerHTML = domString;
el.addEventListener('click', function() {
items[key].owned = 1;
console.log(items[key].name + ' ' + items[key].owned);
});
document.getElementById('shop').appendChild(el.firstChild);
}
}
I want to change one item variable on click by the way.
Event listener doesn't work in this code.
Make use of Object keys to assign the id and then add the event listener
for (let key of Object.keys(items)) {
if (items[key].owned==0) {
var el = document.createElement('div');
var domString = '<div id="' + items[key] + '"><div class="w3 h3 bg-center contain" style="background-image:url(' + items[key].img + ')"></div><span>'+ items[key].name +'</span><span>Price: '+ items[key].cost +'</span><span>'+ items[key].desc +'</span></div>';
el.innerHTML = domString;
document.getElementById('shop').appendChild(el.firstChild);
}
}
for (let key of Object.keys(items)) {
document.getElementById(items[key]).addEventListener('click', function() {
items[key].owned = 1
});
}
or you could simply assign the listener on the div element created using document.createElement
for (let key of Object.keys(items)) {
if (items[key].owned==0) {
var el = document.createElement('div');
var domString = '<div id="' + items[key] + '"><div class="w3 h3 bg-center contain" style="background-image:url(' + items[key].img + ')"></div><span>'+ items[key].name +'</span><span>Price: '+ items[key].cost +'</span><span>'+ items[key].desc +'</span></div>';
el.innerHTML = domString;
el.addEventListener('click', function() {
items[key].owned = 1
});
document.getElementById('shop').appendChild(el);
}
}
This question already has answers here:
Why is there "undefined" text in the beginning of my string?
(3 answers)
Closed 4 years ago.
I have a code like this:
var students = [
{
name: 'Mustafa',
track: 'A',
achievements: 5,
points: 500
},
{
name: 'Ersin',
track: 'B',
achievements: 6,
points: 600
},
{
name: 'Ahmet',
track: 'C',
achievements: 7,
points: 700
},
{
name: 'Mehmet',
track: 'D',
achievements: 8,
points: 800
},
{
name: 'Cafer',
track: 'E',
achievements: 9,
points: 900
}
];
var HTML;
var s = 0;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
for (var s = 0; s < students.length; s += 1) {
HTML += '<h2>' + 'Student: ' + students[s].name + '</h2>' ;
HTML += '<p>' + 'Track: ' + students[s].track + '</p>';
HTML += '<p>' + 'Points: ' + students[s].points + '</p>';
HTML += '<p>' + 'Achievements: ' + students[s].achievements + '</p>';
};
print(HTML);
<div id="output"></div>
Unfortunately, only bad-outcome for this code is an "undefined" at the beginning. I would like to get rid of this.
Is it something about my loop or any other detail that i couldn't predict?
var HTML;
You don't explicitly give the variable a value when you initialise it, so it is undefined.
The first time you append to the variable with +=, that value gets implicitly converted to the string "undefined".
Use var HTML = ""; instead.
Initialize HTML to "", you are getting undefined since HTML (since it is not initialized) is undefined
var HTML = ""; //change this line
Demo
var students = [
{
name: 'Mustafa',
track: 'A',
achievements: 5,
points: 500
},
{
name: 'Ersin',
track: 'B',
achievements: 6,
points: 600
},
{
name: 'Ahmet',
track: 'C',
achievements: 7,
points: 700
},
{
name: 'Mehmet',
track: 'D',
achievements: 8,
points: 800
},
{
name: 'Cafer',
track: 'E',
achievements: 9,
points: 900
}
];
var HTML = ""; //change this line
var s = 0;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
for (var s = 0; s < students.length; s += 1) {
HTML += '<h2>' + 'Student: ' + students[s].name + '</h2>' ;
HTML += '<p>' + 'Track: ' + students[s].track + '</p>';
HTML += '<p>' + 'Points: ' + students[s].points + '</p>';
HTML += '<p>' + 'Achievements: ' + students[s].achievements + '</p>';
};
print(HTML);
<div id="output"></div>
Initialize HTML variable with an empty string like this:
var HTML="";
I'm working on a simple aplication based on localStorage and I have a problem with removing an item.
So, I'm adding new items to LS and display them as divs in for loop.
I created an easy "X" button on every card and here is a thing. How can I get an ID/position of this specific card after clicking "X" and pass it to remove function?
I'll present you my code:
// Display activities
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
var actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
for (let i = 0; i < activities.length; i++) {
actCardContainer.innerHTML += '<div class="col-md-4">'+
'<div class="card">' +
'<div class="card-block">' +
'<div id="remove" class="remove">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
const removeButton = document.getElementById("remove");
if (removeButton) {
removeButton.addEventListener("click", removeActivity);
};
};
// Add activity function
var addActivity = function() {
const actInput = document.getElementById("activityInput").value;
// Main activity object
var activity = {
name: actInput
};
if (localStorage.getItem("activitie") == null) {
var activities = [];
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
} else {
var activities = JSON.parse(localStorage.getItem("activitie"));
activities.push(activity);
localStorage.setItem("activitie", JSON.stringify(activities));
}
fetchActivities();
};
// Remove activity function
var removeActivity = function() {
};
const addButton = document.getElementById("addBtn");
addButton.addEventListener("click", addActivity);
I'd be very grateful if you can give me an idea how can I handle this remove function.
I would rewrite fetchActivities as follows
var fetchActivities = function() {
var activities = JSON.parse(localStorage.getItem("activitie"));
const actCountContainer = document.getElementById("actCountContainer");
actCountContainer.innerHTML = "";
actCountContainer.innerHTML += "<div class='col-md-12'>" +
"<p>Your activities ("+activities.length+")";
const actCardContainer = document.getElementById("actCardContainer");
actCardContainer.innerHTML = "";
let items = "";
for (let i = 0; i < activities.length; i++) {
itemsHTML += '<div class="col-md-4">'+
'<div class="card" data-id="' + activities[i].id + '">' +
'<div class="card-block">' +
'<div class="remove" data-id="' + activities[i].id + '">X</div>' +
'<h4 class="card-title">'+ activities[i].name + '</h4>' +
'<ul class="card-text">' +
'<li>Total time spent: 2h 25min 34sec</li>' +
'</ul>' +
'Go to this activity' +
'</div>' +
'</div>' +
'</div>'
}
actCardContainer.innerHTML = items;
// ... for attach event read on
};
Notes:
Do not set the same id if an element appears many times
Set innerHTML once not for each loop iteration
Set unique id for every item (you could generate random numbers for example)
To attach events you would need to do it as follows (taken from question ):
var removeLink = document.querySelectorAll('.remove');
Then you would loop:
for (var i = 0; i < deleteLink.length; i++) {
removeLink[i].addEventListener('click', function(event) {
var acrtivityId = event.currentTarget.getAttribute('data-id');
removeActivity(acrtivityId);
// Use
});
}
Now for the removal you can find current activity in the activity array and remove it. Use find and then splice for example. And save the change array to local storage. On creation assign an id.
I'm trying to use a for-loop to reiterate over the object material and enter the material into a div on my html. Right now I have the code set to accept an array, but I'd like to use an object instead.
var animals = [
{
name:'Aye Aye',
description: 'blue',
img: 'http://cdnimg.in/wp-content/uploads/2015/06/335.jpg?cfaea8',
price:500
}, {
name:'Little Imp',
description:'yellow',
img:'http://cdnimg.in/wp-content/uploads/2015/06/334.jpg?cfaea8',
price:3000
}, {
name:'Long Nose Monkey',
decription:'grey',
img:'http://cdnimg.in/wp-content/uploads/2015/06/492.jpg?cfaea8',
price:5000
}, {
name:'Nicobar Bird',
decription:'purple',
img:'http://cdnimg.in/wp-content/uploads/2015/06/471.jpg?cfaea8',
price: 6
}, {
name:'Slow Loris',
decription: 'brown',
img: 'https://s-media-cache-ak0.pinimg.com/736x/49/09/8f/49098fbc3c9a37fb03034b45e89c5cd4.jpg',
price:90
}, {
name:'Tucan',
decription:'orange',
img: 'http://cdnimg.in/wp-content/uploads/2015/06/526.jpg?cfaea8',
price:100
}, {
name:'Fennec Fox'
decription:'yellow'
img:'http://cdnimg.in/wp-content/uploads/2015/06/526.jpg?cfaea8',
price:500
}, {
name:'Sugar Glider',
description: 'green',
img: 'https://pbs.twimg.com/media/CNd03WIUwAAqKHg.jpg:large',
price:1000000
}
]
function animal() {
// var animalName = ['Aye Aye',
var animalElement = document.getElementById("div0");
for (i=0; i<animalName.length; i++) {
animalElement.innerHTML += '<h2>' + animalName[i]+'</h2>' +'<p>' + animalDescription[i] +'</p>' + '<p>' + animalPrice[i] +'</p>' + '<p>' + animalImage[i] + '</p>';
};
};
animal();
This is a simple solution based off of what you currently have:
function generateAnimals() {
var animalElements = document.getElementById("div0");
var html = '';
for (i = 0; i < animals.length; i++) {
var animal = animals[i];
html += '<h2>' + animal.name + '</h2>'
+ '<p>' + animal.description + '</p>'
+ '<p>' + animal.price + '</p>'
+ '<p>' + animal.image + '</p>';
}
animalElements.innerHTML += html;
}
generateAnimals();
Just be warned that creating elements like this can get messy once things start to become more complex.
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}