How write/replace HTML from a function - javascript

I have an application where (non-IT) users create and maintain product pages (the products are music CDs), so the pages contain usual blurb about the CD and a track-listing.
We want to insert an mp3 music player into each track, but need to keep the in-line 'code' that that usrs add-in as simple as possible e.g <player url:fileRef />
Each instance on the page would then be injected with the ~20 lines of html and the unique fileRef at display time.
What's the best way to do this? Javascript? jquery?
I read that 'document.write' - isnt the answer.
Is document.getElementByClassName("player").innerHTML = "html goes here"; the best way>
I read that .getELementByClassName("player") replaces ALL instances of the class - so how best inject the unique fileRef into each instance.
Your guidance would be most welcome
PS We already have the (html5) mp3 music player, but the html for each instance is ~20 lines.

It's fine if you want to add the class 'player' to each of your elements, but your selector should not be document.getElementsByClassName("player") as that will not differentiate any of the elements from one another. Ideally, you'd have a list of IDs that you could loop over and use to select your individual elements. Something like this could work:
var ids = ["id1", "id2", "id3", "id4"];
var i;
for(i = 0; i < ids.length; i++) {
var player = document.getElementById(ids[i]);
player.innerHTML = getHtmlForPlayer(id[i]); // you'll need to build this
}
Note, I have written this without knowing too much about how your HTML is generated, but it should get you started.

using jQuery you can use something like
$("player").each(function(){
var id = $(this);
var url = $(this).prop("url");
$.get(url, function(data){
$(id).html(data);
}
}
Note that this is untested, i would go for span/div with a class="player", and the use of data-url tags.
<span class="player" data-url="url"></span>
then change the $("player") to $(".player")

Related

How to make selection on drop down list (DynamicForm) using JavaScript in SmartClient?

Here is a drop down list in SmartClient: http://www.smartclient.com/#dropdownGrid.
I want to make a selection using JavaScript. Like, I run some JavaScript in console, and the drop list will select a specific item.
I did some research, found a code snap to do this (the code is in Java, but I think there should be similar functions in JavaScript):
Record rec = perdomainGrid.getRecordList().find("domaine_id", domaine_id);
perdomainGrid.selectSingleRecord(rec);
If I want to make selection, first I need to obtain perdomainGrid object. In my above giving link, the drop down list id in GWT is exampleForm (can be seen in dropDownGrid.js tab). I try to get the object by:
var form = isc.DynamicForm.getById("exampleForm");
form does exist, but there is no getRecordList() function on it, there is selectSingleRecord() function on it though.
I try to check form's class by form.className, its value is normal. I don't know what does that mean.
I'm kind of confused now. Could somebody help me on this?
isc_SelectItem_5 has a function called pickValue(), it takes one parameter SKU. This function can be used to select item.
var itemName = "Letter Tray Front Load Tenex 200 Class Blk #23001";
var data = isc_SelectItem_5.optionDataSource.cacheData;
var targetSKU = data.find(function(e) {
if (e.itemName == itemName) {
return e;
}
}).SKU;
isc_SelectItem_5.pickValue(targetSKU);

Google App Script , find file's parent id if exist in a Sheets

I'm trying to find (in a Google Sheets list of file Id) file's parent ID in a loop, until it's present in another Google Sheets. All is ok for the first parent but it doesn't work when i'm trying to get 2nd or 3rd parent's generation higher. My fileParent is "undefined" , i don't know why cause row 3 my var file return the correct first parent ID.
`
//all var are initialized before
var files = DriveApp.getFileById(*My File ID*);
var myFiles = files.getParents()
var file = myFiles.next().getId();
for(var rowRef in tab_ref){
if(file != tab_ref[rowRef][9]){
while(tab_ref[rowRef][9] != file && files.hasNext()){
var fileParent = DriveApp.getFolderById(file);
files = fileParent.getParents();
file = files.next().getId();
}
if(tab_ref[rowRef][9] == id_file){
sheet_files.activate();
sheet_files.getActiveCell().offset(2,10).setValue(file);
}
}
}
I'm not sure this is the easiest way to find what your looking but I think it is a way to do it. I use these sorts of loops to build directory trees for access to all sorts of hierarchical data and I also incorporate JQuery jstree to create an easy to use UI for anybody that's use to navigating on a computer. So here's the code. If your not familiar with this kind of coding it may take you a while to figure it out. Have fun with it. I incorporated comments that refer to a parentsArray[]. The parentsArray[] could be used as kind of stack where you push and pop current folder names onto and off of the stack in order to keep track of your current path or parental ancestry of folders.
function traverseFolder(folderObj)
{
//parentsArray[parentsArray.length-1] is the immediate parent of the current folderObj.
//Put folderObj name, size info here
//Push folderobj name on to parentsArray
var subs = folderObj.getFolders();
var files = folderObj.getFiles();
if(files)
{
while(files.hasNext())
{
var fi = files.next();;
//Put file name,size,info here
//parentsArray[parentsArray.length-1] is the immediate parent of all of these files
//parentsArray[0]/parentsArray[1].../parentsArray[parentsArray.length-1] is the path to this file.
}
}
while (subs.hasNext())
{
traverseFolder(subs.next());
}
//Pop last folderobj off of the parentsArray
}

onClick replace /segment/ of img src path with one of number of values

No idea what I'm doing or why it isn't working. Clearly not using the right method and probably won't use the right language to explain the problem..
Photogallery... Trying to have a single html page... it has links to images... buttons on the page 'aim to' modify the path to the images by finding the name currently in the path and replacing it with the name of the gallery corresponding to the button the user clicked on...
example:
GALLERY2go : function(e) {
if(GalleryID!="landscapes")
{
var find = ''+ findGalleryID()+'';
var repl = "landscapes";
var page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var i = page.indexOf(find);
var j = find.length;
page = page.substr(0,i) + repl + page.substr(i+j);
document.body.innerHTML = page;
var GalleryID = "landscapes";
}
}
},
There's a function higher up the page to get var find to take the value of var GalleryID:
var GalleryID = "portfolio";
function findGalleryID() {
return GalleryID
}
Clearly the first varGalleryID is global (t'was there to set a default value should I have been able to find a way of referring to it onLoad) and the one inside the function is cleared at the end of the function (I've read that much). But I don't know what any of this means.
The code, given its frailties or otherwise ridiculousness, actually does change all of the image links (and absolutely everything else called "portfolio") in the html page - hence "portfolio" becomes "landscapes"... the path to the images changes and they all update... As a JavaScript beginner I was pretty chuffed to see it worked. But you can't click on another gallery button because it's stuck in a loop of some sort. In fact, after you click the button you can't click on anything else and all of the rest of the JavaScript functionality is buggered. Perhaps I've introduced some kind of loop it never exits. If you click on portfolio when you're in portfolio you crash the browser! Anyway I'm well aware that 'my cobbled together solution' is not how it would be done by someone with any experience in writing code. They'd probably use something else with a different name that takes another lifetime to learn. I don't think I can use getElement by and refer to the class/id name and parse the filename [using lots of words I don't at all understand] because of the implications on the other parts of the script. I've tried using a div wrapper and code to launch a child html doc and that come in without disposing of the existing content or talking to the stylesheet. I'm bloody lost and don't even know where to start looking next.
The point is... And here's a plea... If any of you do reply, I fear you will reply without the making the assumption that you're talking to someone who really hasn't got a clue what AJAX and JQuery and PHP are... I have searched forums; I don't understand them. Please bear that in mind.
I'll take a stab at updating your function a bit. I recognize that a critique of the code as it stands probably won't help you solve your problem.
var currentGallery = 'landscape';
function ChangeGallery(name) {
var imgs = document.getElementsByTagName("img") // get all the img tags on the page
for (var i = 0; i < imgs.length; i++) { // loop through them
if (imgs[i].src.indexOf(currentGallery) >= 0) { // if this img tag's src contains the current gallery
imgs[i].src = imgs[i].src.replace(currentGallery, name);
}
}
currentGallery = name;
}
As to why I've done what I've done - you're correct in that the scope of the variables - whether the whole page, or only the given function, knows about it, is mixed in your given code. However, another potential problem is that if you replace everything in the html that says 'landscape' with 'portfolio', it could potentially change non-images. This code only finds images, and then replaces the src only if it contains the given keyword.

Way of loading dynamic content onload with Javascript

On my page I load some tracks in a music player ( http://dev.upcoming-djs.com ) on page load.
Which is working fine.
However when people go to the following URL: http://dev.upcoming-djs.com/track/1/artist/title I would like to load another track in the player on page load.
Currently the JS code for the player is:
var tracks = [];
tracks.push({'url':trackurl, 'title':trackurl});
$('.upcoming-player-container').theplayer({
links: tracks // contains an array with url's
});
Which is static.
What would be the best way (not meant to be subjective, just don't know how to rephrase it) of making it dynamic.
I was thinking of adding some hyperlinks in a (hidden) container on the page which I retrieve with JS.
Is this a good way to do it? (Since I think Google might add the text to the search results).
Or perhaps there is a better way of doing it?
Assuming that the player will play the tracks in order, here's some code that will shift the track specified by the URL /track/##/artist/title to the front of the playlist, presumably playing it first on page load:
var tracks = [],
trackMatch
trackPlay;
tracks.push({'url': trackurl,'title': trackurl});
// tracks.push etc...
// find the track number
trackMatch = window.location.href.match(/track\/(\d+)/i);
// if found store as integer
if (trackMatch) {
trackPlay = parseInt(trackMatch[1], 10);
}
// if found move selected track to front of tracks array
if (trackPlay) {
tracks = [tracks[trackPlay - 1]]
.concat(tracks.slice(0, trackPlay - 1))
.concat(tracks.slice(trackPlay));
}
$('.upcoming-player-container').theplayer({
links: tracks // contains an array with url's
});

Get object by its `id` in an AIR windowedApplication

There may be a better way of doing this...so please suggest if there is.
I've got some javascript that calls an AIR function. This AIR functions creates a new HTML element and adds it to the "Stage" like so:
// guid is the ID given to the new window (HTML element) by javascript
private function createNewWindow(guid:String):void {
var frame:HTML = new HTML();
frame.id = guid;
addElement(frame);
}
Now I've also got a function that sets the location of the frame based on its id...this is where I'm struggling.
// set the location of the window referenced by it's id (guid)
private function setLocation(guid:String, location:String):void {
// psuedocode. Obviously it won't work.
stage.getById(guid).location = location;
}
So, how do I "get" my HTML element based on its ID?
Short answer, you don't. This isn't javascript, this is a OO language and as such, you need to change your thought process. What are you trying to do? Create several html windows within an air application? If you want to have an id based approach, you're going to need to store the id and the pointer to the component in an data structure (like a dictionary).
private var _components:Dictionary = new Dictionary();
this._components['someId'] = someComponent;
And from there you can add a function that just saves/returns the components. I'm not entirely sure what's your approach and what you're trying to accomplish, but my gut tells me you're not doing something right.

Categories