I am working with the Soundcloud API. A user searches a song or band name and my page returns an output of all the album art associated with each track. I have insert a "play" button for each track; however, the play link (var named "linky") only seems to take on the LAST called track on the page. So EVERY "play" link will only play the last track on the page. How do I make it so that each "play" link will link to its appropriate track?
SC.initialize({
client_id: 'xxxxeditedforprivacyxxxx'
});
function doSearch() {
var searchTerm = document.getElementById('search').value;
// Search soundcloud for artists
SC.get('/tracks', { q: searchTerm}, function(tracks) {
for(track in tracks) {
var img = document.createElement('img');
img.setAttribute("src", (tracks[track]["artwork_url"]));
var title = tracks[track].title.replace("'", "\\\'").replace("\"", "\\\"");
var song = document.createElement('div');
linky = tracks[track].permalink_url;
img.setAttribute("onclick", "showTrackInfo('" + title + "\\n" + "\\n" + tracks[track].label_name + "\\n\\n" + "(click to close)" + "')");
if (tracks[track]["artwork_url"] == null) {
console.log(""); }
else {
var Catalog = document.getElementById('catalog');
Catalog.appendChild(img);
$('div#catalog').append('<img src="http://i.imgur.com/rGdvfl7.png" id="play">');
console.log(linky);
$('img#play').click(function() {
$.get(
'http://soundcloud.com/oembed?' +
'url=' + linky +
'&format=json&maxheight=296'
)
.done(function (response) {
song.innerHTML = response.html;
document.getElementById("soundiframe").appendChild(song);
});
});
}
}
});
};
My console.log(linky); is showing the appropriate, different URLs for each track. But the play button only wants to play the last track that's pulled. Where am I going wrong? Any help appreciated!
It is because of the closure value linky. Since linky is a closure value it will have the last assigned value.
The same problem exists for the variable songs also, since it is used only within the ajax success callback you can move the creation of the element to the callback
You have mix raw dom manipulation which is not recommended if you are using jquery. I've tried to rewrite the code to use jQuery by removing raw dom manipulation.
Also you were creating some dom elements like img and Catelog which were never added to the dom so I've removed it
SC.initialize({
client_id: 'xxxxeditedforprivacyxxxx'
});
$(function(){
$('#catalog').on('click', '.play', function(){
$.get(
'http://soundcloud.com/oembed',{
format:'json',
maxheight:'296',
url:$(this).data('linky')
}
).done(function (response) {
$("#soundiframe").append('<div>' + response.html + '</div>');
});
})
})
function doSearch() {
var searchTerm = document.getElementById('search').value;
// Search soundcloud for artists
SC.get('/tracks', { q: searchTerm}, function(tracks) {
$.each(tracks, function(key, track){
if (track.artwork_url) {
$('#catalog').append('<img src="http://i.imgur.com/rGdvfl7.png" class="play" data-linky="' + track.permalink_url + '" />');
}
})
});
};
Related
I am stuck at a point,its worpress mediauploader. I want to upload images, one function is for one image but I have several upload buttons with unique id so I want only one function for all thats why I created the loop, on click of each button media uploader open up but there is problem saving the selected image, I am not getting that image url in the value. pls help new to jquery and javascript. Tried various methods this is one of them
this is screenshot of thing that I want->here
jQuery(document).ready(function($){
var b = ["#upload-button-1", "#upload-button-2", "#upload-button-3","#upload-button-4","#upload-button-5","#upload-button-6","#upload-button-7","#upload-button-8"];
var d =[".procircle-1", ".procircle-2",".procircle-3",".procircle-4",".procircle-5",".procircle-6",".procircle-7",".procircle-8"];
var j;
var c = ["#grid-image-1", "#grid-image-2", "#grid-image-3","#grid-image-4","#grid-image-5","#grid-image-6","#grid-image-7","#grid-image-8"];
var i;
for(i=0; i<=b.length; i++)
{
for(j=0;j<=c.length;j++){
$(b[i]).on('click',function(e){
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame= wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select',function(){
attachment= mediaUploader.state().get('selection').first().toJSON();
$(c[j]).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
}
}
});
I would suggest doing the following (if you must keep your ids etc):
$(document).on('click', '#upload-button-1, #upload-button-2, #upload-button-3, #upload-button-4, #upload-button-5, #upload-button-6, #upload-button-7, #upload-button-8', function(e) {
var match = e.target.id.match(/(\d+)/g);
e.preventDefault();
if(mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select', function(){
var attachment = mediaUploader.state().get('selection').first().toJSON();
var id = '#grid-image-' + match[1];
$(id).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
This removes the loop and delegates your handler so you only create one click handler rather than one per loop iteration as you are currently, and also creates a single mediauploader select handler. Finally, match the corresponding input with the event target that performed the click. Should work, although you might need to play around with it a bit, and it could definitely be refactored to be nicer. Hope it helps.
I made a little application in JavaScript with the Flickr API. It returns the ten most recent photos of a specific tag.
When Searching for a tag it brings one the photos, everything fine till here. At the next search it keeps the old photos and just adds new ones. It was planned to "delete" the older photos. Visit: https://jsfiddle.net/79uueuso/
var thread = null;
function findTags(input) {
console.log(input);
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
// Get the vaules of the Flickr-API
$.getJSON(flickerAPI, {
tags: input, // input = value of the input text field
tagmode: "all",
format: "json"
})
// get 10 pictures
.done(function (data) {
$.each(data.items, function (i, item) { // put them in a <img> with thumbnail of bootstrap / append them to the <div> with id="images"
$("<img class='img-thumbnail'>").attr("src", item.media.m).appendTo("#images");
if (i === 9) {
return false;
}
});
});
}
// Get the Value of the text input field while you type!
// The function reads the value 500ms after your last typing (.keyup)
$('#tag').keyup(function () {
clearTimeout(thread);
var $this = $(this);
thread = setTimeout(function () {
findTags($this.val())
}, 750);
});
Originally it was like this, Visit: https://jsfiddle.net/ckdr2Lwx/
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "Schloss Heidelberg",
tagmode: "any",
format: "json"
})
.done(function (data) {
$.each(data.items, function (i, item) {
$("<img>").attr("src", item.media.m).appendTo("#images");
console.log("Hallo die " + [i] + ".");
if (i === 9) {
return false;
}
});
});
})();
I solved my problem. I added a function which removes the input value, after that when there is no input value the recent photos will be deleted and the search does not start from scratch. First you have to type something in the input field. Here goes the additional code I used.
// when pressing backspace once, the whole input field gets cleared.
$('html').keyup(function(e){
if(e.keyCode == 8) {
var photo = document.getElementById("tag");
photo.value = "";
var photoDel = $(".img-thumbnail"); // All pictures of the last search will be deleted.
photoDel.remove();
}
});
if(input == ""){ // The search only works now when the input field is not empty-
return false;
}else {
added on top of
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
// Get the vaules of the Flickr-API
I'm trying to dynamically load pictures to a profile page like site from MySQL with PHP and
then add them to an unordered list with javascript. I would like each list item to also have
a like button, which upon clicking calls a javascript function, passing the image name as
its parameter. I've searched and found answers on how to call a function without passing it
any variables, but every time I add the image name to the function call, the console log reads
"undefined".
The pictures show up fine and the imgArray[i] is a string containing the file's name (e.g. photo.jpg)
But
console.log(imgArray[i])
in the onclick function reads undefined. I've also tried
like.setAttribute()
without any results.
function showGallery(imgArray) {
for(var i=0; i < imgArray.length; i++){
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img"),
like = document.createElement("a");
img.src = "user_images/" + imgArray[i];
like.className = "button-like";
li.appendChild(img);
li.appendChild(like);
list.appendChild(li);
like.href = "javascript:void(0);";
like.onclick = function() {
console.log(imgArray[i]);
addLike(imgArray[i]);
};
}
}
function addLike(img) {
console.log("Liking.. " + img);
$.ajax({
url: 'like.php',
type: 'POST',
data: {
'photo': img
},
success: function(likes){
console.log(likes);
}
});
}
The problem is that by the time the click event fires, imgArray[i] doesn't exists.
try doing it like this...
like.href = "javascript:void(0);";
like.imgArray = imgArray[i];
like.onclick = function() {
console.log(this.imgArray);
addLike(this.imgArray);
};
Hope that helps
i need some help with this code. i want to read the current URL, and when the URL contains "#_ThankYou" in it, I want to add a new to an existing on the page and that div contains some javascript that will display an ad from an ad vendor. i have the following but i think i might be caught in an infinite loop. not sure i coded this correctly. anyone have good suggestions?
<script type="text/javascript">
window.eddyCookieCount = 0;
window.eddyNumberAttempts = 0;
window.myInterval = setInterval(function() {
if (window.location.href.indexOf("#_ThankYou") > window.eddyCookieCount) {
jQuery('div.thankyou-container').append('<div>' + vm_load({
"displayId": "12584", // Numeric unique ad display Id
"publisherId": "33927", // Publisher ID
"campaign": "9380", // Numeric Publisher Campaign Id
"maxResults": "3",
"areaofstudy": JSON.parse(jQuery.cookie('CategorySubCategorySpecialty')).CATEGORIES[0].text.replace('Business','1').replace('Criminal Justice & Legal','3').replace('Education','5').replace('Fine Arts & Design','2').replace('Health & Medicine','8').replace('Liberal Arts & Humanities','5').replace('Math, Science & Engineering','9').replace('Public Affairs & Social Sciences','13').replace('Religious Studies','5').replace('Technology','9').replace('Vocational Training',''),
"md": "1"
}) + '</div>');
window.eddyNumberAttempts++;
if (window.eddyNumberAttempts > 60) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
window.eddyNumberAttempts = 0;
}
}
else if (jQuery.cookie('CategorySubCategorySpecialty').length < window.eddyCookieCount) {
window.eddyCookieCount = jQuery.cookie('CategorySubCategorySpecialty').length;
}
}, 50);
</script>
There is no need to do an interval to watch for the hash to be added.
$(window).on('hashchange', function() {
if (window.location.search === "#_ThankYou") {
}
});
In your code, I do not see you ever cancelling the interval when you are in the state when the url is changed so it keeps firing. you need to cancel it.
window.clearInterval(window.myInterval)
It worked for me, where I have to check a token in the URL on view change.
The way I worked is below code, which doesn't seem good to use, but it is worked on selector basis:
$('.nav ul li a').click(function() {
setTimeout(changeurl, 4000);
});
function changeurl(title, newurl) {
if (window.location.hash == '') {
return window.location.hash = '#/dashboard';
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash;
if (history.pushState) {
window.history.pushState({path:newurl},'',newurl);
}
}
Finally, I modified the code as such:
var token = window.location.search;
$(window).on('hashchange', function() {
if (window.location.search === token) {
setTimeout(changeurl, 4000);
}
});
Concerning the following site
Pretty simple, but none the less I seem to be falling at the first hurdle on this.
Using the following code currently to try and obtain a track name and artist from the currently active soundcloud player (of which there are 4 ,with the class SCiframe)
$(function () {
var $iframeElement = document.getElementsByClassName('SCiframe');
var $widgets = SC.Widget(iframeElement);
widgets.bind(SC.Widget.Events.READY, function () {
widgets.bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
widgets.getCurrentSound(function (currentSound) {
$('#trackInfo').append('Current Track: ' + currentSound.get('') + '');
});
});
});
});
for one, the console is registering 'iframeElement is not defined' as an inital error.
But all in all, I cant seem to get any useful data out of this to process.
Where am i going wrong here?
Kindest regards to the community.
You have the variable names incorrect, they have "$" at the begining,
$(function () {
var $iframeElement = document.getElementsByClassName('SCiframe');
var $widgets = SC.Widget($iframeElement);
$widgets.bind(SC.Widget.Events.READY, function () {
$widgets.bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
$widgets.getCurrentSound(function (currentSound) {
$('#trackInfo').append('Current Track: ' + currentSound.get('') + '');
});
});
});
});
EDIT:
getElementsByClassName returns an array of results. So if there is only one iframe with "SCiframe" classname, you should pass first index of $iframeElement as paramater in SC.Widget, try this,
$(function () {
var $iframeElement = document.getElementsByClassName('SCiframe');
var $widgets = SC.Widget($iframeElement[0]);
$widgets.bind(SC.Widget.Events.READY, function () {
$widgets.bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
$widgets.getCurrentSound(function (currentSound) {
$('#trackInfo').append('Current Track: ' + currentSound.get('') + '');
});
});
});
});