I try get the mp3 flash player to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.
After trying to find out I found this in the reference code:
<!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->
How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?
That syntax, with the <script> tag with the "event" and "for" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object. Here, it adds a FSCommand event handler to the myFlash object. This is needed because code running inside the Flash object may want to run JavaScript in the browser. To do this, the Flash object will invoke the FSCommand event handler, passing the JavaScript to run as the arguments to the event.
With this player, the name of a JS listener object is passed in the FlashVars param to the player. It then uses FSCommands from ActionScript to modify that listener object, with an occasional call to a method on that listener when it's other properties have been modified. I suppose that IE isn't able to run the JS code using this method until the FSCommand handler has been added to the Flash player object, which is why that code exists. Modify it to use the ID of your Flash object and you should be in good shape.
Maybe this is more about embedding flash dynamically.
I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, only document.write worked. But document.write can't really be used after the page has loaded, unless it is targeted in an iframe or some other devil worship mechanism.
What's good tho, is that IE doesn't distinguish between assigning an event handler in this bastard script tag or programatically. This means that:
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
in IE directly translates to:
function foo(command, args){
eval(args);
}
var ie_sucks = document.getElementById('myFlash');
ie_sucks.attachEvent("FSCommand", foo);
And... in the end we have that:
var ie_sucks = document.getElementById('comebacker_audio');
ie_sucks.attachEvent("FSCommand", function(command, args) {eval(args);});
and if that not work for you, try to check your html for inserting object. Example here:
http://kb2.adobe.com/cps/415/tn_4150.html
;)
Thanks everyone for the above. I'll just drop a few lines that were handy for me.
To re-use code across browsers, do:
<script type="text/javascript">
function mySwf_DoFSCommand(command, args) {
// do stuff
}
</script>
<!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="mySwf">
mySwf_DoFSCommand(command, args);
</script>
<![endif]-->
Related
What is the correct JavaScript way to replacement <body onload="init();">, bearing in mind that we no-longer have need to support very old browsers.
In my case I want to add a onClick event to all tags and would like to keep the Javascript separate to my HTML page.
window.onload = init();
Started off with this but found the global document object is not available inside init(), this seems to be it seems to be a timing issue. Did it work better in older browsers?
document.addEventListener("DOMContentLoaded", init, false);
Seems to be a more modern reliable way but is this supported by all modern browsers?
Then there is the suggestion to just put the init() at the bottom of the page but that is obviously getting back to having the Javascript direct in the HTML.
<script type="text/javascript">init();</script>
Is there a definitive way I should be running my init code?
I think what you want is $(function(){}), or $(document).ready(...), as Marc B mentioned. That seems to accomplish what you're asking for, unless I'm misunderstanding your question. The jQuery API backs this up.
The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate.
Most simple method is adding a script tag at the end of body with a self invoking anonymous function:
<body>
<!-- content here -->
<script type="text/javascript">
(function() {
//Run init code here
})();
</script>
</body>
For external js files:
<body>
<!-- content here -->
<script src="main.js" type="text/javascript"></script>
</body>
main.js file:
(function() {
//Run init code here
})();
Now that the problem of the extra brackets has been solved the final solution which I am just about to test is:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init);
} else {
window.onload = init;
}
I know JQuery can do this with it's .ready event but some of these pages are very small pages of Ajax content and I would prefer to avoid the overhead of JQuery if it is not necessary.
I'm working with a legacy frames website that was just moved into an iFrame.
Assuming I have the following function:
<script language = "javascript">
function myFunction(){
<!-- no console.log in IE 7 (my required target browser) -->
alert('sup, yo?');
}
</script>
and the following hyperlink triggering the function:
click me
before the move into an iFrame this worked ok. Once the website was moved into the iframe, clicking the link in IE (not FF or Chrome), I would get the ever-so-helpful error:
Line: 1
Object expected
Once I removed the target="_top" attribute the function would work, so I don't need help solving the problem, but my question is:
What is IE doing with the target attribute when calling a javascript function to invoke this behavior? I don't have other versions of IE installed, is this current behavior in 8+ as well?
Thanks.
It does not make sense to try to understand the behavior. You're using a technique that is not well defined and is not used by developers nowadays.
Instead of href="javascript:myFunction();, just use onclick="myFunction(); return false" or even better, set the handler from JS like the following
<a href="pageForUsersWithoutJs.html" id="my-link" >click me</a>
<script type="text/javascript">
// This is old school, but works for all browsers, you should use a library instead
document.getElementById('my-link').onclick = function() {
// Do your thing
return false; // so the link isn't followed
};
</script>
I'm trying to do something fairly simple, but for the reason of me probably not being good enough to search documentation, I can't get this to work.
I have a functioning inline JS that looks like this:
<A title="Wolfram IP Calc" href="javascript:txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5');%20if(txt)%20window.open('http://www.wolframalpha.com/input/?i='+txt);void(O);">Compute!</A>
For various reasons, I'm trying to seperate the JS, and this is where I hit a snag.
I've created the following test page that gives me the error Uncaught TypeError: Cannot call method 'addEventListener' of null:
<HTML> <HEAD profile="http://www.w3.org/2005/10/profile"> <script type="text/javascript">
var compute = document.getElementById('compute');
compute.addEventListener('click', computeThatThing, false);
function computeThatThing() {
txt=prompt('Enter%20IP%20address,%20e.g.%2010.20.30.40/29','1.2.3.4/5');
if(txt) {
window.open('http://www.wolframalpha.com/input/?i='+txt);
}
}
</script></HEAD>
<BODY>
<A title="Wolfram IP Calc" id="compute" href="javascript:void(O);">Test</A>
</BODY>
</HTML>
The only thing I've been able to find that points to a problem like that is that addEventListener can't work with <A> but should handle <IMG> (which suits me fine as I'm going to pour this on some images), so I tried adding the following to no avail:
<img id="compute" src="http://products.wolframalpha.com/images/products/products-wa.png" />
Thanks in advance for pointing out what I'm doing wrong. It is probably glaringly obvious, but I have close to zero experience with JS and I have gone mostly by cargo culting when I've needed it until now.
Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...
element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.
MDN
Solutions:
Put the scripts in the bottom of the page.
Call the attach code in the load event.
Use jQuery library and it's DOM ready event.
What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...
ready docs
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag.
window.onload vs document.onload
What is the best unobtrusive way of invoking something after the page is being loaded in plain JavaScript? Of course in jQuery I would use:
$(document).ready(function(){...});
but I am not sure about the most reliable approach in plain js.
Clearly
window.onload = ...
is not proper solution, because it would overwrite previous declaration.
What I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like:
window.onload = function(divId){
var div = document.getElementById(divId);
div.innerHTML = "<iframe src='someUrl' .. >";
}
EDIT:
Apologies for not including all necessary details.
The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code. That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change URL of an iframe or I would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.
//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );
//For IE:
document.attachEvent( "onreadystatechange", someFunction);
`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.
See:
https://developer.mozilla.org/en/DOM/element.addEventListener
Also definitly worth looking at how jQuery does it:
http://code.jquery.com/jquery-1.7.js Search for bindReady.
Use window.addEventListener and the events load or DOMContentLoaded:
window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});
object.addEventListener('event',callback) will insert an event listener into a queue for that specific object event. See https://developer.mozilla.org/en/DOM/element.addEventListener for further information.
For IE5-8 use window.attachEvent('event',callback), see http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. You can build yourself a little helper function:
function addEventHandler(object,szEvent,cbCallback){
if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
return false;
if(!!object.addEventListener){ // for IE9+
return object.addEventListener(szEvent,cbCallback);
}
if(!!object.attachEvent){ // for IE <=8
return object.attachEvent(szEvent,cbCallback);
}
return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});
Note that DOMContentLoaded isn't defined in IE lesser 9. If you don't know your recipient's browser use the event load.
Just put your script include at the very end of the document, immediately before or after the ending </body> tag, e.g.:
(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>
All of the markup above the script will be accessible via the usual DOM methods (reference). Obviously, not all ancillary resources (images and such) will be fully loaded yet, but presumably that's why you want to avoid the window load event (it happens so late).
The only real purpose of ready-style events is if you don't control where the script gets included (e.g., libraries) or you need to have something execute prior to the page load and something else after the page load, and you want to avoid having two HTTP requests (e.g., for two different scripts, one before load and one after).
I have a website with a form that uses TinyMCE; independently, I use jQuery. When I load the form from staging server on Firefox 3 (MacOS X, Linux), TinyMCE doesn't finish loading. There is an error in Firefox console, saying that t.getBody() returned null. t.getBody(), as far as I understand from TinyMCE docs, is a function that returns document's body element to be inspected for some features. Problem doesn't occur when I use Safari, nor when I use Firefox with the same site running from localhost.
Original, failing JavaScript-related code looked like this:
<script type="text/javascript" src="http://static.alfa.foo.pl/json2.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.ui.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({ mode:"specific_textareas", editor_selector:"mce", theme:"simple", language:"pl" });
</script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.jeditable.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.tinymce.js"></script>
<script type="text/javascript" charset="utf-8" src="http://static.alfa.foo.pl/foo.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ });
</script>
I tried changing script loading order, moving tinyMCE.init() call to the <script/> tag containing $(document).ready() call—before, after, and inside this call. No result. When tinyMCE.init() was called from within $(document).ready() handler, the browser did hang on request—looks like it was too late to call the init function.
Then, after googling a bit about using TinyMCE together with jQuery, I changed tinyMCE.init() call to:
tinyMCE.init({ mode:"none", theme:"simple", language:"pl" });
and added following jQuery call to the $(document).ready() handler:
$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });
Still the same error. But, and here's where things start to look like real voodoo, when I added alert(i); before the tinyMCE.execCommand() call, alerts were given, and TinyMCE textareas were initialized correctly. I figured this can be a matter of delay introduced by waiting for user dismissing the alert, so I introduced a second of delay by changing the call, still within the $(document).ready() handler, to following:
setTimeout('$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });',1000);
With the timeout, TinyMCE textareas initialize correctly, but it's duct taping around the real problem. The problem looks like an evident race condition (especially when I consider that on the same browser, but when server is on localhost, problem doesn't occur). But isn't JavaScript execution single-threaded? Could anybody please enlighten me as to what's going on here, where is the actual problem, and what can I do to have it actually fixed?
The browser executes scripts in the order they're loaded, not written. Your immediate scripts -- tinyMCE.init(...) and $(document.ready(...)); -- can execute before the files finish loading.
So, the problem is probably network latency -- especially with 6 separate scripts (each requiring a different HTTP conversation between the browser and server). So, the browser is probably trying to execute tinyMCE.init() before tiny_mce.js has finished being parsed and tinyMCE is fully defined.
If don't have Firebug, get it. ;)
It has a Net tab that will show you how long it's taking all of your scripts to load.
While you may consider the setTimeout to be duct taping, it's actually a decent solution. Only problem I see is that it assumes 1 second will always fix. A fast connection and they could see the pause. A slow connection and it doesn't wait long enough -- you still get the error.
Alternatively, you might be able to use window.onload -- assuming jQuery isn't already using it. (Can anyone else verify?)
window.onload = function () {
tinyMCE.init(...);
$(document).ready(...);
};
Also, was that a direct copy?
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ }
</script>
It's missing the ) ending ready:
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ })
</script>
Missing punctuation can cause plenty of damage. The parser is just going to keep reading until it finds it -- messing up anything in between.
Since this is the first page which came in google when I asked myself the same question, this is what i found about this problem.
source
There's a callback function in tinyMCE which is fired when the component is loaded and ready. you can use it like this :
tinyMCE.init({
...
setup : function(ed) {
ed.onInit.add(function(ed) {
console.log('Editor is loaded: ' + ed.id);
});
}
});
If you are using jquery.tinymce.js then you don't need tiny_mce.js because TinyMCE will try to load it with an ajax request. If you are finding that window.tinymce (or simply tinymce) is undefined then this means that the ajax is not yet complete (which might explain why using setTimeout worked for you). This is the typical order of events:
Load jquery.js with a script tag (or google load).
Load TinyMCE's jQuery plugin, jquery.tinymce.js, with a script tag.
Document ready event fires; this is where you call .tinymce(settings) on your textareas. E.g.
$('textarea').tinymce({ script_url: '/tiny_mce/tiny_mce.js' })
Load tiny_mce.js this step is done for you by TinyMCE's jQuery plugin, but it could happen after the document ready event fires.
Sometimes you might really need to access window.tinymce, here's the safest way to do it:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
alert(tinymce);
}
});
TinyMCE will go so far as to create a tinymce.Editor object and execute the setup callback. None of the editor's events are triggered and the editor object created for the document is not added to tinymce.editors.
I also found that TinyMCE's ajax call was interfering with my .ajaxStop functions so I also used a setTimeout:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
setTimeout(function () {
$(document).ajaxStart(function(e) {/* stuff /});
$(document).ajaxStop(function(e) {/ stuff */});
}, 0);
}
});