Trying to redirect browser tab if coincidence in title - Tampermonkey - redirect

Im trying to search a word in the title or Body of the tab and if coincidence, redirect to another page, using Tampermonkey, this is the code that I found:
// ==UserScript==
// #name Auto Cerrar
// #namespace http://tampermonkey.net/
// #version 0.1
// #description try to take over the world!
// #author You
// #match *://*/*
// #icon *
// ==/UserScript==
// Your code here...
(function() {
var blacklist = ["potato", "onion", "put other text here"],
re = new RegExp(blacklist.join('|'), "i");
if (re.test(document.body.textContent)) {
window.open("https://www.google.com","_self");
alert("Coincidence Found!")
}
})();
Thanks for the help

Related

Google Sheets - Create PDF and Send Email (Different PDFs to Different Emails)

I have a Google Sheet that updates information based on an Athlete Name that is in a specific cell (A24 in the "Dashboard" worksheet). Once the athlete name changes (e.g., A24 changes to a different athlete name), the information on the "Dashboard" worksheet changes to reflect the data for that athlete.
I have a list of athlete names (athleteList) and athlete emails (emails). Essentially, I want the script to do the following in a loop:
Update athlete name to athlete[i] in athlete list
Create PDF of the "Dashboard" worksheet (which is now updated to be athlete[i])
Send email of that PDF to athlete[i] (e.g., using their email, which is email[i]).
I'm new to Google Apps Script so I hope this makes sense... I'm very close. The emailing works fine with the code below, but the PDFs being created are not the right ones for the people receiving the emails. Any assistance would be appreciated. Thank you!
Link to editable sheet (different URL and GID than code): https://docs.google.com/spreadsheets/d/1Amkc1tDgLgaNxKCos95vsZEaxdyd67Xcdtfc4NEQT60/edit?usp=sharing
APPS SCRIPT CODE CODE:
//Google Sheets URL Edit (Athletes Sheet Name)
//Google Sheets URL Edit (Dashboard Sheet Name)
//Google Sheets URL Export (Dashboard Sheet Name)
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/");
var ssAthletes = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/").getSheetByName("Athletes");
var ssDashboard = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit/").getSheetByName("Dashboard");
var ssDashboardExport = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?/").getSheetByName("Dashboard");
var lastRow = ssAthletes.getLastRow()-1; //Define last Row
var athleteList = ssAthletes.getRange(2,1,lastRow).getValues(); //get list of Athletes (Starting at row 2, column 1)
var athleteEmails = ssAthletes.getRange(2,2,lastRow).getValues();
//THIS FUNCTION EMAILS as PDF
function emailSpreadsheetAsPDF() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
// This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
// Add the link to your spreadsheet here
// or you can just replace the text in the link between "d/" and "/edit"
// In my case is the text: 17I8-QDce0Nug7amrZeYTB3IYbGCGxvUj-XMt8uUUyvI
// const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit");
// We are going to get the email address from the cell "E2" from the "Lists" sheet
// Change the reference of the cell or the name of the sheet if it is different
const value = ss.getSheetByName("Lists").getRange("E2").getValue();
const email = value.toString();
for (var i = 0; i < athleteList.length; ++i) {
athleteName = athleteList[i];
}
// Subject of the email message
const subject = 'Your Report';
// Email Text. You can add HTML code here - see ctrlq.org/html-mail
const body = "Hey " + athleteName + "! Great work today. Here is your report for " + Date();
// Again, the URL to your spreadsheet but now with "/export" at the end
// Change it to the link of your spreadsheet, but leave the "/export"
const url = 'https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=letter' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=680445839'; // the sheet's Id. Change it to your sheet ID.
// You can find the sheet ID in the link bar.
// Select the sheet that you want to print and check the link,
// the gid number of the sheet is on the end of your link.
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// Generate the PDF file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// Send the PDF file as an attachement
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard" + Date() + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
})}
//THIS FUNCTION EMAILS MULTIPLE PEOPLE as PDF -- WORK IN PROGRESS!!!
function emailSpreadsheetAsPDFMulti() {
DocumentApp.getActiveDocument();
DriveApp.getFiles();
// This is the link to my spreadsheet with the Form responses and the Invoice Template sheets
// Add the link to your spreadsheet here
// or you can just replace the text in the link between "d/" and "/edit"
// In my case is the text: 17I8-QDce0Nug7amrZeYTB3IYbGCGxvUj-XMt8uUUyvI
// const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/edit");
// We are going to get the email address from the cell "E2" from the "Lists" sheet
// Change the reference of the cell or the name of the sheet if it is different
const emails = ss.getSheetByName("Athletes").getRange(2,2,lastRow).getValues();
const emailsString = emails.toString();
// for (var i = 0; i < athleteList.length; ++i) {
// athleteName = athleteList[i];
// }
for (var i = 0; i < emails.length; ++i) {
athleteEmail = emails[i];
athleteName = athleteList[i];
}
// Again, the URL to your spreadsheet but now with "/export" at the end
// Change it to the link of your spreadsheet, but leave the "/export"
const url = 'https://docs.google.com/spreadsheets/d/1z15EwpuITPnmqPAIwHdxyV6DFDGMLBWKCxpDCQrGtBw/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf
'&size=letter' + // paper size letter / You can use A4 or legal
'&portrait=true' + // orientation portal, use false for landscape
'&fitw=true' + // fit to page width false, to get the actual size
'&sheetnames=false&printtitle=false' + // hide optional headers and footers
'&pagenumbers=false&gridlines=false' + // hide page numbers and gridlines
'&fzr=false' + // do not repeat row headers (frozen rows) on each page
'&gid=680445839'; // the sheet's Id. Change it to your sheet ID.
// You can find the sheet ID in the link bar.
// Select the sheet that you want to print and check the link,
// the gid number of the sheet is on the end of your link.
// Cycle through athletes
for (var i = 0; i < athleteList.length; i++) {
var output = [];
ssDashboard.getRange('A24').setValue(athleteList[i][0]);
output.push([athleteList[i][0]]);
Utilities.sleep(10000);
// Generate the PDF file
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// Subject of the email message
const subject = 'Report'
var athletename = athleteList[i][0];
// Email Text. You can add HTML code here - see ctrlq.org/html-mail
const body = "Hey " + athletename + "! Great work today. Here is your report for " + Date();
console.log(output);
console.log(response);
console.log(body);
console.log(athletename);
console.log(emails[i]);
// Send the PDF file as an attachement
GmailApp.sendEmail(emails[i], subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard" + Date() + ".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
})}}'''
I think you almost got it. This is how I would do it.
Please don't forget to update the Id of the spreadsheet
function updateInfo(){
// I get the emails from the Athletes sheet, hope is ok, otherwise you can point in to another range
var athleteSheet = SpreadsheetApp.getActive().getSheetByName("Athletes");
var athleteList = athleteSheet.getRange("A2:B"+athleteSheet.getLastRow()).getValues();
for (i=0;i<athleteList.length;i++){
var name = athleteList[i][0];
var email = athleteList[i][1];
SpreadsheetApp.getActive().getSheetByName("Dashboard").getRange("A24").setValue(name);
SpreadsheetApp.flush(); // this is important for the changes in the spreadsheet to take place
sendInfo(name, email); // then I send the emails
}
}
Now I used a very similar function to yours and send the files
function sendInfo(name, email){
// change the id (this is the id of my file, a copy of yours)
var ss = SpreadsheetApp.openById('1uftGO8ACoQTE8LtjURjIG2g5G-x3B-taIobVxzvJA2E');
var sheet = ss.getSheetByName("Dashboard");
var ssId = ss.getId();
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+ ssId +'/export?'
+ 'exportFormat=pdf&format=pdf'
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=true' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='+sheet.getSheetId(); // the sheet's Id
var headers = {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
}
// request export url
var response = UrlFetchApp.fetch(url, { headers: headers });
var blob = response.getBlob();
const subject = 'Your Report';
const body = "Sent via Generate Dashboard Report from Google Form and print/email it";
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Dashboard.pdf",
content: blob.getBytes(),
mimeType: "application/pdf"
}]
});
DriveApp.createFile(blob.setName(name+".pdf"))
}
By the way, nice work you have done with those spreadsheets.

hide ul when user clicks anywhere site

my code is :
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajaxname.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item) {
// change input value
$('#country_id').val(item);
// hide proposition list
$('#country_list_id').hide();
}
and i wana hide ul (country_list_id) when user click on anywhere ?
and im not good in ajax :(
so any one can edit this code
Assuming you just want to hide the id when the user click basically anything.
Then here.
$(document).on("click", () => {
$('#country_list_id').hide();
})

How to use the numericRefinementList to set allowed distances?

I would like to be able to use the numericRefinementList to allow users to pick the distance from themselves an item can be? This would be using the IP geo-location feature or inputting the geo-location from browser if available.
Less than 50km
50 - 100km
100 - 150km
More than 150km
https://community.algolia.com/instantsearch.js/documentation/#numericrefinementlist
This is unfortunately not something you can do with the numericRefinementList but you can probably build a custom widget setting the aroundRadius depending on the link you've clicked on:
function radiusList(options) {
if (!options.container) {
throw new Error('radiusList: usage: radiusList({container, ...})');
}
var $container = $(options.container);
if ($container.length === 0) {
throw new Error('radiusList: cannot select \'' + options.container + '\'');
}
return {
init: function(args) {
// event delegation: set the aroundRadius of the underlying link
$(document).on('click', '.radius-link', function(e) {
e.preventDefault();
args.helper.setQueryParameter('aroundRadius', +$(this).data('radius'));
args.helper.search();
});
},
render: function(args) {
// FIXME: display the list of radius links
var html = '<ul>';
html += '<li>< 100km</li>';
html += '</ul>';
$container.html(html);
}
};
}
And then you use it with:
search.addWidget(radiusList({container: '#my-radius-list'}));

How add mandatory dropdown field in Touch UI

I added "required" as "true" but it is not working. "required" as "true" only works for text field.
As per below document, I do not see any option to add mandatory field from dropdown.
http://docs.adobe.com/docs/en/aem/6-0/author/assets/managing-assets-touch-ui/managing-asset-schema-forms.html
How is it possible to achieve this?
Use $.validator.register to register custom validators.
I have written a detailed blog post on writing custom validators: http://www.nateyolles.com/blog/2016/02/aem-touch-ui-custom-validation.
I have made a comprehensive Touch UI validation library available on GitHub that fixes the issue you described where the "required" property doesn't work for several Granite UI fields as well as other functionality. See https://github.com/nateyolles/aem-touch-ui-validation.
Essentially, you need to modify the field's HTML to include an HTML input that can be validated by either overlaying the foundation component or using JavaScript to modify the DOM when the dialog opens. A hidden input is not eligible for validation, so you need to add a text input hidden by CSS. Use JavaScript to update the "hidden" field when the component action is updated. For example, a color is chosen in the color picker.
Then you register the custom validator against the non-visible text input. Pass in the selector of the non-visible text field and the function that does the actual validation. Also pass in functions for show and clear that show and hide the error message/icon.
The following example is for the color picker taken from the library I linked to above:
/**
* Validation for Granite Touch UI colorpicker.
*
* Additional properties for granite/ui/components/foundation/form/colorpicker
* are:
*
* {Boolean}required
* Is field required
* defaults to false
*
* <myColorPicker
* jcr:primaryType="nt:unstructured"
* sling:resourceType="granite/ui/components/foundation/form/colorpicker"
* fieldLabel="My colorpicker"
* name="./myColorPicker"
* required="{Boolean}true"/>
*/
var COLORPICKER_SELECTOR = '.coral-ColorPicker',
$.validator.register({
selector: '.marker-colorpicker',
validate: function(el) {
var field,
value,
required;
field = el.closest(".coral-Form-field");
value = el.val();
required = field.data('required');
if (required && !value) {
return Granite.I18n.get('Please fill out this field.');
} else {
el.setCustomValidity(null);
el.updateErrorUI();
}
},
show: function (el, message) {
var fieldErrorEl,
field,
error,
arrow;
fieldErrorEl = $("<span class='coral-Form-fielderror coral-Icon coral-Icon--alert coral-Icon--sizeS' data-init='quicktip' data-quicktip-type='error' />");
field = el.closest('.coral-Form-field');
el.add(field)
.attr('aria-invalid', 'true')
.toggleClass('is-invalid', true);
field.nextAll('.coral-Form-fieldinfo')
.addClass('u-coral-screenReaderOnly');
error = field.nextAll('.coral-Form-fielderror');
if (error.length === 0) {
arrow = field.closest('form').hasClass('coral-Form--vertical') ? 'right' : 'top';
fieldErrorEl.clone()
.attr('data-quicktip-arrow', arrow)
.attr('data-quicktip-content', message)
.insertAfter(field);
} else {
error.data('quicktipContent', message);
}
},
clear: function(el) {
var field = el.closest('.coral-Form-field');
el.add(field)
.removeAttr('aria-invalid')
.removeClass('is-invalid');
field.nextAll('.coral-Form-fielderror').tooltip('hide').remove();
field.nextAll('.coral-Form-fieldinfo').removeClass('u-coral-screenReaderOnly');
}
});
/**
* Create hidden field to validate against and click event handler when a
* Granite UI dialog loads.
*/
$(document).on('foundation-contentloaded', function(e) {
var $dialog,
$radioGroups;
$dialog = $(e.target);
$radioGroups = $dialog.find(COLORPICKER_SELECTOR);
$radioGroups.each(function() {
var $radioGroup,
required,
$marker,
$button;
$radioGroup = $(this);
required = $radioGroup.data('required');
if (required) {
$marker = $radioGroup.find('input[type="hidden"]');
$button = $radioGroup.find('.coral-ColorPicker-button')
/* Change to text as hidden is not validated */
$marker.attr('type', 'text');
$marker.addClass('marker-colorpicker');
$marker.attr('aria-required', 'true');
/* revalidate once the button color has changed */
$button.on('stylechange', function(){
$marker.trigger('change');
});
}
});
});
AFAIK, In touch ui dialogs you can apply such validation via jquery. One thing you can try. Create a clientlib folder under component with categories cq.authoring.dialog . Then add the below js snippet as per normal process :
(function (document, $, ns) {
"use strict";
$(document).on("click", ".cq-dialog-submit", function (e) {
e.stopPropagation();
e.preventDefault();
var $form = $(this).closest("form.foundation-form"),
title = $form.find("[name='authoringMode']").val(),
message, clazz = "coral-Button ";
if(!title){
ns.ui.helpers.prompt({
title: Granite.I18n.get("Invalid Input"),
message: "Please Check Values",
actions: [{
id: "CANCEL",
text: "CANCEL",
className: "coral-Button"
}
],
callback: function (actionId) {
if (actionId === "CANCEL") {
}
}
});
}else{
$form.submit();
}
});
})(document, Granite.$, Granite.author);
One thing here you need to change is $form.find("[name='authoringMode']") here name is the property and authoringMode is the value of select box in my dialog. as shown.
Here it will check at dialog submit time whether there is value in drop down and will not let author to submit the dialog till drop-down is blank.
Here is the reference.
http://experience-aem.blogspot.in/2015/02/aem-6-sp2-touch-ui-dialog-before-submit.html

Get artwork_url from Soundcloud API and show album covers in custom SC/SM2 player

I've been trying to sort out how artwork_url can be used from soundclouds API in order to output each cover into this custom player, and have each appropriate thumb next to its own track in the playlist?
I understand that I need to use the artwork_url property, however I do not understand how this is achieved, nor how to integrate it into this particular custom player plugin.
Any code examples in particular and/or help is highly appreciated!
Note: Also would be nice to be able to control the "size" of the artwork as well through other means then just CSS.
Best
EDIT #1
I switched the Soundcloud Custom Player on Heroku since after I was able to get it up and running I discovered it to have a much faster load time in contrast to the original player I cited above (even though that one is still quite awesome)...
Im still posed with the same task now however as before - How to add album art to the script and output accordingly?
Pasted below is the Heroku player:
// # SoundCloud Custom Player
// Make sure to require [SoundManager2](http://www.schillmania.com/projects/soundmanager2/) before this file on your page.
// And set the defaults for it first:
soundManager.url = 'http://localhost:8888/wp-content/themes/earpeacerecords/swf';
soundManager.flashVersion = 9;
soundManager.useFlashBlock = false;
soundManager.useHighPerformance = true;
soundManager.wmode = 'transparent';
soundManager.useFastPolling = true;
// Wait for jQuery to load properly
$(function(){
// Wait for SoundManager2 to load properly
soundManager.onready(function() {
// ## SoundCloud
// Pass a consumer key, which can be created [here](http://soundcloud.com/you/apps), and your playlist url.
// If your playlist is private, make sure your url includes the secret token you were given.
var consumer_key = "915908f3466530d0f70ca198eac4288f",
url = "http://soundcloud.com/poe-epr/sets/eprtistmix1";
// Resolve the given url and get the full JSON-worth of data from SoundCloud regarding the playlist and the tracks within.
$.getJSON('http://api.soundcloud.com/resolve?url=' + url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(playlist){
// I like to fill out the player by passing some of the data from the first track.
// In this case, you'll just want to pass the first track's title.
$('.title').text(playlist.tracks[0].title);
// Loop through each of the tracks
$.each(playlist.tracks, function(index, track) {
// Create a list item for each track and associate the track *data* with it.
$('<li>' + track.title + '</li>').data('track', track).appendTo('.tracks');
// * Get appropriate stream url depending on whether the playlist is private or public.
// * If the track includes a *secret_token* add a '&' to the url, else add a '?'.
// * Finally, append the consumer key and you'll have a working stream url.
url = track.stream_url;
(url.indexOf("secret_token") == -1) ? url = url + '?' : url = url + '&';
url = url + 'consumer_key=' + consumer_key;
// ## SoundManager2
// **Create the sound using SoundManager2**
soundManager.createSound({
// Give the sound an id and the SoundCloud stream url we created above.
id: 'track_' + track.id,
url: url,
// On play & resume add a *playing* class to the main player div.
// This will be used in the stylesheet to hide/show the play/pause buttons depending on state.
onplay: function() {
$('.player').addClass('playing');
$('.title').text(track.title);
},
onresume: function() {
$('.player').addClass('playing');
},
// On pause, remove the *playing* class from the main player div.
onpause: function() {
$('.player').removeClass('playing');
},
// When a track finished, call the Next Track function. (Declared at the bottom of this file).
onfinish: function() {
nextTrack();
}
});
});
});
// ## GUI Actions
// Bind a click event to each list item we created above.
$('.tracks li').live('click', function(){
// Create a track variable, grab the data from it, and find out if it's already playing *(set to active)*
var $track = $(this),
data = $track.data('track'),
playing = $track.is('.active');
if (playing) {
// If it is playing: pause it.
soundManager.pause('track_' + data.id);
} else {
// If it's not playing: stop all other sounds that might be playing and play the clicked sound.
if ($track.siblings('li').hasClass('active')) { soundManager.stopAll(); }
soundManager.play('track_' + data.id);
}
// Finally, toggle the *active* state of the clicked li and remove *active* from and other tracks.
$track.toggleClass('active').siblings('li').removeClass('active');
});
// Bind a click event to the play / pause button.
$('.play, .pause').live('click', function(){
if ( $('li').hasClass('active') == true ) {
// If a track is active, play or pause it depending on current state.
soundManager.togglePause( 'track_' + $('li.active').data('track').id );
} else {
// If no tracks are active, just play the first one.
$('li:first').click();
}
});
// Bind a click event to the next button, calling the Next Track function.
$('.next').live('click', function(){
nextTrack();
});
// Bind a click event to the previous button, calling the Previous Track function.
$('.prev').live('click', function(){
prevTrack();
});
// ## Player Functions
// **Next Track**
var nextTrack = function(){
// Stop all sounds
soundManager.stopAll();
// Click the next list item after the current active one.
// If it does not exist *(there is no next track)*, click the first list item.
if ( $('li.active').next().click().length == 0 ) {
$('.tracks li:first').click();
}
}
// **Previous Track**
var prevTrack = function(){
// Stop all sounds
soundManager.stopAll();
// Click the previous list item after the current active one.
// If it does not exist *(there is no previous track)*, click the last list item.
if ( $('li.active').prev().click().length == 0 ) {
$('.tracks li:last').click();
}
}
});
});
EDIT #2
So I strangely was able to work something out... I have no clue if its semantically correct however...
$.getJSON('http://api.soundcloud.com/resolve?url=' + url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(playlist){
// I like to fill out the player by passing some of the data from the first track.
// In this case, you'll just want to pass the first track's title.
$('.title').text(playlist.tracks[0].title);
$('.album_art').attr('src', playlist.artwork_url);
// Loop through each of the tracks
$.each(playlist.tracks, function(index, track) {
// Create a list item for each track and associate the track *data* with it.
$('<li>' + '<img src="' + playlist.artwork_url + '">' + track.title + '</li>').data('track', track).appendTo('.tracks');
// * Get appropriate stream url depending on whether the playlist is private or public.
// * If the track includes a *secret_token* add a '&' to the url, else add a '?'.
// * Finally, append the consumer key and you'll have a working stream url.
url = track.stream_url;
(url.indexOf("secret_token") == -1) ? url = url + '?' : url = url + '&';
url = url + 'consumer_key=' + consumer_key;
// ## SoundManager2
// **Create the sound using SoundManager2**
soundManager.createSound({
// Give the sound an id and the SoundCloud stream url we created above.
id: 'track_' + track.id,
url: url,
// On play & resume add a *playing* class to the main player div.
// This will be used in the stylesheet to hide/show the play/pause buttons depending on state.
onplay: function() {
$('.player').addClass('playing');
$('.title').text(track.title);
},
onresume: function() {
$('.player').addClass('playing');
},
// On pause, remove the *playing* class from the main player div.
onpause: function() {
$('.player').removeClass('playing');
},
// When a track finished, call the Next Track function. (Declared at the bottom of this file).
onfinish: function() {
nextTrack();
}
});
});
EDIT #3
Below is the HTML and CSS markup that works with the player for better clarification...
HTML
<div class='title'></div>
<a class='prev'>Previous</a>
<a class='play'>Play</a>
<a class='pause'>Pause</a>
<a class='next'>Next</a>
</div>
CSS
/*
-------------------------------------------------------------------------
Soundcloud Player
-------------------------------------------------------------------------
*/
#sticky_header #sticky_content .player {
height: 570px;
overflow: hidden;
}
#sticky_header #sticky_content .tracks {
}
#sticky_header #sticky_content .tracks li {
cursor: pointer;
height: 40px;
text-align: left;
}
#sticky_header #sticky_content .tracks li img.album_art {
width: 40px;
height: 40px;
border-radius: 5px;
margin-right: 15px;
}
#sticky_header #sticky_content .title {
}
#sticky_header #sticky_content .prev {
}
#sticky_header #sticky_content .play {
display: block;
}
#sticky_header #sticky_content .playing .play {
display: none;
}
#sticky_header #sticky_content .pause {
display: none;
}
#sticky_header #sticky_content .playing .pause {
display: block;
}
#sticky_header #sticky_content .next {}
to get an image you can use this code:
//get element by id from your iframe
var widget = SC.Widget(document.getElementById('soundcloud_widget'));
widget.getCurrentSound(function(music){
artwork_url = music.artwork_url.replace('-large', '-t200x200');
$('#song1').css('background', 'url(\"'+artwork_url+'\") ');
});
normaly you get a link with "-large" at the end and the size is 100x100. If you want other sizes you have to change the end with ".replace" like I did. A list with available sizes can you find here:
https://developers.soundcloud.com/docs/api/reference#tracks
(my size 200x200 is not listed but works. Maybe there are more sizes like every hundred px.)
at the moment the code works only for the actual playing song. For me it's not a solution, because i need all images from my playlist.
Here's where iterating over the tracks retrieved from the API happeninng:
// Loop through each of the tracks
$.each(playlist.tracks, function(index, track) {
// Create a list item for each track and associate the track *data* with it.
$('<li>' + track.title + '</li>').data('track', track).appendTo('.tracks');
Inside of the iterator function you can now access track.artwork_url and possibly set it as a background image or perhaps background for some element, maybe something like:
$('<li><img src=" + track.artwork_url + "></img>' + track.title + '</li>').data('track', track).appendTo('.tracks');
I hope this helps.
UPD. In your updated code, you should refer to track.artwork_url instead of playlist – then you'll get each track's individual artwork.