Problems with SoundManager 2 - javascript

I am trying to implement SoundManager 2 to play snippets of songs on this page.
This is my current JavaScript code:
alert('c!');
soundManager.url = 'http://www.transapine.ch/common/soundmanagerv297a-20120513/swf/soundmanager2.swf';
soundManager.flashVersion = 8; // optional: shiny features (default = 8)
soundManager.useFlashBlock = false; // optionally, enable when you're ready to dive in
/*
Example HTML to make sound snippet:
<div>
<img src="..." height="x" />
</div>
*/
alert('d!');
soundManager.onready(function() {
alert('e!');
var els = $.Elements.getElementsByClassName('sclip');
var a = url = '';
var clips = new Array();
var masterVolume = 100;
for (var i=0; i<els.length; i++) {
a = els[i];
url = a.href;
clips[i] = soundManager.createSound({
id: "clip" + i,
url: url,
volume: masterVolume
});//clips[i] = soundManager.createSound({
$.Events.add(a, "click", function(e) {
e.preventDefault();
clips[i].play();
});//$.Events.add(el, "click", function() {
$.CSS.removeClass(a, 'hidden');// show the button
}//for (var i=0; i<els.length; i++) {
});//soundManager.onready(function() {
And this is the section in the HTML page calling the necessary scripts:
<script src="http://assets.momo40k.ch/common/js/$-min.js" type="text/javascript"></script>
<script type="text/javascript">alert('a!'); //these alerts are for debugging</script>
<script src="http://assets.momo40k.ch/common/soundmanagerv297a-20120513/script/soundmanager2-nodebug-jsmin.js" type="text/javascript"></script>
<script type="text/javascript">alert('b!');</script>
<script src="http://assets.momo40k.ch/common/js/soundclips.js" type="text/javascript"></script>
<script type="text/javascript">alert('f!');</script>
Note: the $ library is a small library I use to even out the browser differences.
I have encountered several problems with this.
1. SWF files
In SoundManager's tutorial it says to use soundManager.url to tell it the location of the SWF files it needs. Whatever value I gave it, it seemed to ignore it, as Firebug gave me the following error:
NetworkError: 404 Not Found - http://www.transalpine.ch/portale/soundmanager2.swf
So I tried putting soundmanager2.swf in http://www.transalpine.ch/portale/, and the error disappeared, so I continued to see if I could get it to work like this.
Note: I have a base tag setting http://www.transalpine.ch/portale/ as the base URL in this section of the site.
Problems 2 and 3 sort of happened at the same time, I only managed to separate them through debugging the script little by little...
2. Script doesn't execute in certain conditions
After that, nothing happened. The two testing buttons I had put on the page weren't appearing as they should be ($.CSS.removeClass(a, 'hidden'); removes the class hidden from the elements, effectively showing them), so I went about working out what was executing and what wasn't in my usual way: alerts!
So I found out that soundclips.js wasn't executing at all, and then I found out that it could execute as long as lines 28-32 (clips[i] = soundManager.createSound({...});) were commented out. That puzzled me: how can something the browser hasn't even read yet prevent from reading that whole file?!
3. soundManager.onready doesn't fire
Having removed those lines, I still had a last problem, though probably it's caused by problem 1: the event soundManager.onready never fires.
Does anyone know what's wrong with my setup, and what's causing all these problems?
I'm guessing 2 and 3 both derive from 1, but I really don't understand 1 nor how 2 can be...
Thank you!

First off the URL should look like this:
soundManager.url = 'http://www.transapine.ch/common/soundmanagerv297a-20120513/swf/';
Everything else should somewhat be fixed now.

Related

JavaScript only being called once in Squarespace

I have some custom JavaScript on my SquareSpace site that manipulates Product titles beyond what you can do with SquareSpace's default style editor. It works when initially loading the page (https://www.manilva.co/catalogue-accessories/) but if you click on any of the categories on the left, the styling resets to the default.
I'm assuming the JavaScript is being overwritten by the SquareSpace style, but I can't figure out why. Perhaps I'm calling the function in the wrong place?
Any suggestions would be helpful.
Thanks!
Current code:
document.querySelectorAll(".ProductList-filter-list-item-link".forEach(i=>i.addEventListener("click", function()
{
var prodList = document.querySelectorAll("h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
var text = prodList[i].innerText;
var index = text.indexOf('-');
var lower = text.substring(0, index);
var higher = text.substring(index + 2);
prodList[i].innerHTML = lower.bold() + "<br>" + higher;
});
The source of your problem is that your template has AJAX loading enabled. There are currently a couple generally-accepted ways to deal with this as a Squarespace developer:
Disable AJAX loading
Write your javascript functions in a
manner that will run on initial site load and whenever an "AJAX load" takes place.
Option 1 - Disable AJAX:
In the Home Menu, click Design, and then click Site Styles.
Scroll down to Site: Loading.
Uncheck Enable Ajax Loading.
Option 2 - Account for AJAX in Your JS
There are a number of ways that developers approach this, including the following, added via sitewide code injection:
<script>
window.Squarespace.onInitialize(Y, function() {
// do stuff
});
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// myFunction2(); , etc...
// Reinit. the fn on each new AJAX-loaded page.
window.addEventListener("mercury:load", myFunction);
})();
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// Reinit. the fn on each new AJAX-loaded page.
new MutationObserver(function() {
myFunction();
// myFunction2(); , etc...
}).observe(document.body, {attributes:true, attributeFilter:["id"]});
})();
</script>
Each of those works for most of the latest (at time of writing) templates most of the time. Each of those have their advantages and disadvantages, and contexts where they do not work as one might expect (for example, on the /cart/ page or other "system" pages). By adding your code within the context of one of the methods above, and ensuring that the code is of course working in the desired contexts and without its own bugs/issues, you will have your code run on initial site load and on each AJAX page load (with some exceptions, depending on the method you use).
Your problem is the page does not reload when clicking a button on the left, just some elements are removed, added and replaced. The changed elements will not be restyled. You will need to re-run your JavaScript after one of those buttons is clicked. Perhaps something like this:
document.querySelectorAll(
".ProductList-filter-list-item"
).forEach(
i=>i.addEventListener(
"click", ()=>console.log("hello")
)
)
where you replace console.log("hello") with whatever resets your formatting.

addEventListener to div element

I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.

jQuery playlist function error: function undefined

I'm trying to create a .mp3 player to just loop through audio tracks, but I keep getting error on Firebug that the main function I use is undefined, although I do define it. Here is the code:
$(document).ready(function() {
var counter=1;
var nextSong = function(){
if (counter <= 3) {
$('audio').src="audio/audio"+counter+".ogg";
$this.load();
$this.play();
counter++;
}
else {
counter=0;
$('audio').src="audio/audio"+counter+".ogg";
$this.load();
$this.play();
};
};
});
And my markup is simply:
<!DOCTYPE html>
<head>
<title>Dokimastiko Audio Player</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/dokimastiko.js"></script>
</head>
<body>
<audio src="audio/audio1.ogg" controls autoplay onended="nextSong();"></audio>
</body>
Any thoughts?
I debated on whether to give you a full lesson on why your code is pretty bad... And since I have little on my plate at work right now I'll do so... :P
First of all the $this you have there is undefined, so obviously calling a method on it is going to be undefined as well.
You probably copied the code from somewhere, which is fine, but you need to be able to copy is smartly instead of blindly.
.... you changed your code midway of my post, so update:
$(this) is the same as $(document) since that is the context of this within $(document).ready(function() {})
So, nope, still wrong.
So the first modification, it should be:
$('audio').load();
$('audio').play();
But actually that is still wrong. Because $('audio') is a jquery object, and it does not contain the DOM-level methods load and play directly, so you need to get the DOM object:
$('audio').get(0).load();
$('audio').get(0).play();
Now you would be wondering why the .get(0), it's because $('audio') is a collection of all the matches to 'audio', so get(0) would return the first one only.
This is prone to breakage if you decide to add more audio tags to the page, so you should give the audio tag a unique identifier:
<audio src="audio/audio1.ogg" controls autoplay onended="nextSong();" id="audio1"></audio>
And then use the id in your jquery selector:
$('#audio1').get(0).load();
$('#audio1').get(0).play();
This is still abit verbose, but given that you only need to do this, this is the simplest way.
UPDATE:
As per suggested by #JanDvorak here is a example that uses jquery events as well
Fiddle: http://jsfiddle.net/MpBP5/1/
jQuery(document).ready( function($) {
$('#audio1').bind('ended', function(e) {
alert('end');
});
});
I can also keep going on this "lesson", you should try not to define your music urls that abstractly, what if someone just leaves your page on and it hits a file which, for that counter #, doesn't exist?
I would declare an array of files you wish to load:
var library = [
'http://www.archive.org/download/bolero_69/Bolero.mp3',
'http://www.archive.org/download/MoonlightSonata_755/Beethoven-MoonlightSonata.mp3',
'http://www.archive.org/download/CanonInD_261/CanoninD.mp3',
'http://www.archive.org/download/PatrikbkarlChamberSymph/PatrikbkarlChamberSymph_vbr_mp3.zip'
];
var currentIndex = 0;
Then loop through the list:
jQuery(document).ready( function($) {
$('#audio1').bind('ended', function(e) {
currentIndex++;
if (currentIndex > library.length-1) {
currentIndex = 0;
}
this.src = library[currentIndex];
$('#url').html(library[currentIndex]);
});
$('#audio1').attr('src', library[currentIndex]);
$('#url').html(library[currentIndex]);
});
http://jsfiddle.net/MpBP5/3/
If you don't want a fixed list of audio files to play (which you really should), you can generate the array with at least some rules.

JavaScript source file not loading in IE8 Popup

I have an issue where the JavaScript source file is loading in popup for IE6, Chrome, Firefox, Safari and Opera. But the same source file is not loading up in IE8.
As a result of this the HTML is not being replaced in the Popup and I am getting an error in IE8 popup saying tinyMCE is not defined
I have referred to Formatting this JavaScript Line and solved issue on all browsers except IE8.
The JavaScript function is as follows:
function openSupportPage() {
var features="width=700,height=400,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes";
var winId=window.open('','',features);
winId.document.open();
winId.document.write('<html><head><title>' + document.title + '</title><link rel="stylesheet" href="../css/default.css" type="text/css">\n');
var winDoc = winId.document;
var sEl = winDoc.createElement("script");
sEl.src = "../js/tiny_mce/tiny_mce.js";/*TinyMCE source file*/
sEl.type="text/javascript";
winDoc.getElementsByTagName("head")[0].appendChild(sEl);
winId.document.write('<script type="text/javascript">\n');
winId.document.write('function inittextarea() {\n');
winId.document.write('tinyMCE.init({ \n');
winId.document.write('elements : "content",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('mode : "exact",\n');
winId.document.write('theme : "advanced",\n');
winId.document.write('readonly : true,\n');
winId.document.write('setup : function(ed) {\n');
winId.document.write('ed.onInit.add(function() {\n');
winId.document.write('tinyMCE.activeEditor.execCommand("mceToggleVisualAid");\n');
winId.document.write('});\n');
winId.document.write('}\n');
winId.document.write('});}</script>\n');
window.setTimeout(function () {/*using setTimeout to wait for the JS source file to load*/
winId.document.write('</head><body onload="inittextarea()">\n');
winId.document.write(' \n');
var hiddenFrameHTML = document.getElementById("HiddenFrame").innerHTML;
hiddenFrameHTML = hiddenFrameHTML.replace(/&/gi, "&");
hiddenFrameHTML = hiddenFrameHTML.replace(/</gi, "<");
hiddenFrameHTML = hiddenFrameHTML.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML);
winId.document.write('<textarea id="content" rows="10" style="width:100%">\n');
winId.document.write(document.getElementById(top.document.forms[0].id + ":supportStuff").innerHTML);
winId.document.write('</textArea>\n');
var hiddenFrameHTML2 = document.getElementById("HiddenFrame2").innerHTML;
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/&/gi, "&");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/</gi, "<");
hiddenFrameHTML2 = hiddenFrameHTML2.replace(/>/gi, ">");
winId.document.write(hiddenFrameHTML2);
winId.document.write('</body></html>\n');
winId.document.close();
}, 300);
}
Additional Information:
Screen shot of the page
Rendered HTML
Original JSPF
please help me with this one.
Why are you using actual DOM functions to add the <script> tag that includes tinymce.js but everything else is using document.write?
I think that's also where your problem lies, as <head> is within <html>, which is not yet closed where you want to append said <script> tag.
Otherwise, you could use the existing <script> tag in the popup to add the code that includes the required external javascript file. If that makes any sense.
So, basically I'm saying, try it the same way as everything else is in your script, using document.write.
(quick addition) I'm not saying this is the 'best' way to do this, I would recommend creating an actual page instead of dynamically creating one in the popup. But in this scenario, I think what I wrote earlier might solve the problem you are having.

JavaScript behaving weirdly, opening an drop/drag item only 'alert' is put

I have Drag/Drop functionality in my page embedded using YAHOO.js which is initalized at load of the page. When 'alert' is put in the init function, the Drag/Drop is working otherwise
it is not. Using Firebug I had debugged the code and seen when init function is called but not looping through the function when no alert is put.
This function should work when ALT key is pressed. I am using velocity template engine over JavaScript.
Sample code:
<script type="text/javascript" language="JavaScript">
var myLogger;
var dd1, ddTrashCan; // draggable div objs
#if ($displayOptions.isDoDragDropJavaScript())
YAHOO.util.Event.addListener(window, "load", DD_TestInit);
#end
function display(data) {
var output = "<div>" + data.text + "</div>";
element.innerHTML=output;
}
function DD_TestInit() {
#if ($showLoggerDiv)
initLogger();
#end
//display("date");
initDragObjects();
}
function logMsg(strMsg) {
if (myLogger)
myLogger.debug(strMsg);
}
function initDragObjects() {
//alert('---');
if (dd1) dd1.unreg();
if (ddTrashCan) ddTrashCan.unreg();
YAHOO.util.DDM.mode = YAHOO.util.DDM.POINT;
YAHOO.util.DDM.clickTimeThresh = 10;
## init constant drag objects, draggable div and droppable trash, resp.
dd1 = new lineSched_Draggable("dragDiv1");
ddTrashCan = new lineSched_Droppable("TrashCan");
}
What I had found is whenever I put an alert or call any window.open() this works fine.
Any clue whats happening here.
There is timer event which is delaying the process.My feeling is that this is a timing issue. The page is not fully in place when on load. The alert slows the process down, essentially the page is in place by the time the user clicks Ok on the alert. Clearly, we can’t deploy the app with an alert. But, we can look into different places to put the initialization. We can try to place it the same place I added the timing, when the page receives the last table. The page should be fully formed at this point and the function should work properly.

Categories