I'm an jQuery noob and I'm wondering how fix this issue:
I have an external .js script, let's take reflection.js as example.
Reflection.js creates canvas reflection for every class="reflect" image.
I'm appending a few images trough different JS script that starts when ('document').ready.
Of course reflection.js doesn't work for images created by the script above.
How to avoid that?
I guess I'll need callback (?). Unfortunately I'm not getting idea of callbacks idea even after reading documentation.
[edit]
<script src="js/reflection.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery().ready(function() {
jQuery('#thumbs li').each(function(){
jQuery('.'+id+' a').append('<img src="' + imgURL + '" class="reflect" /></a>');
});
});
</script>
Image loading events do not bubble. You cannot hook into those.
Since your images have the class "reflect" it means you have some control over the source. So I recommend your reflection code publishes an API for you to call.
window.Reflect = function(img) {
...
};
...
var img = $("<img></img");
img.attr({
...
});
Reflect(img);
...
If you do not want to do this then you can poll the document for new images.
(function poll() {
var images = $("img.reflect");
...
images.removeClass("reflect")
setTimeout(poll, 500);
})();
If I understand this correctly, you have 2 functions under "ready" sequence and one script depends on other.
The way how I solved this problem, I have build my own includeJS as well as additional ready-checking layer on top of the one which jQuery has.
https://github.com/atk4/atk4/blob/master/templates/js/start-atk4.js
So my code looks like this:
$(function(){
$.atk4.includeJS('reflection.js');
$.atk4.includeJS('different.js');
$.atk4(function(){
$('.reflect').reflection();
});
});
What happens is, after document is ready, jQuery launches above code. It appends 2 scripts and evaluates them (by adding tag). When evaluation is complete, function atk4.get will execute readiness chain very similar to how jQuery does it.
Related
I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})
I'm creating a Hangman game for a project. I have most of the functionality I need, however I am having one issue. When the last incorrect guess is made, it displays the alert box telling you you've lost, before loading the image. I want the image to load first and then the alert box.
I realize that the issue is with the way the DOM loads elements and that I should create a callback function in jQuery.
This is the line in my code that changes the image, and it works fine until it gets to the last one.
document.getElementById("gallows").src = displayGallows[incorrectGuesses - 1];
I have tried using a Jquery function to get this working but my knowledge of jQuery is pretty much non-existent.
var img = $("gallows");
img.load(function() {
alert("Unlucky, you lost. Better luck next time!");
});
img.src = displayGallows[incorrectGuesses - 1];
I have compared this to many posts I have found online and to my untrained eye, it looks OK. When I was troubleshooting I did realize that the img.src was assigned the correct value but the image didn't appear on my page or didn't fire the alert box.
This led me to believe that it may be an issue with linking to the jquery.js file. I have an HTML page that references the jQuery file in it's head tag.
<head>
<title>Hangman</title>
<link rel="stylesheet" href="base.css"/>
<script src="jquery.js"></script>
<script src="hangman.js"></script>
<script src="home.js"></script>
</head>
The file I am writing my JavaScript and jQuery from is the hangman.js file.
Do I also need to refer to the jquery.js file from the hangman.js file? While reading up on this I found that I may have to do this, so I've tried this:
///<reference path="jquery.js" />
and this
var jq = document.createElement('script');
jq.src = 'jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq);
but to no avail, though I don't really understand the second one, as I found these examples on the internet.
Note that in my home.js file I have simple a simple jQuery function to em-bold the text on a button when you mouseover it and this works OK.
If anyone could help me out or point me in the right direction that would be great.
Your best bet here is probably not to use alert at all; instead, use modern techniques like an absolutely-positioned, nicely-styled div to show your message. Showing that won't get in the way of the browser showing the image once it arrives, whereas alert basically brings the browser to a screeching halt until the user clicks the alert away.
But if you want to use alert:
Your concept of waiting for the load event from the image is fine, but you may want to yield back to the browser ever-so-briefly afterward to give it a chance to display the image.
Not using jQuery, as you don't appear to be using it otherwise:
var img = document.getElementById("gallows");
img.onload = img.onerror = function() {
setTimeout(function() {
alert(/*...*/);
}, 30); // 30ms = virtually imperceptible to humans
};
img.src = displayGallows[incorrectGuesses - 1];
That waits for the load or error event from the image, then yields back to the browser for 30ms before showing the alert.
But if you pre-cache the images, you can make the load event fire almost instantaneously. Most browsers will download an image even if it's not being shown, so if you add
<img src="/path/to/incorrect/guess.png" style="display: none">
...to your page for each of the incorrect guess images, then when you assign the same URL to your #gallows image, since the browser has it in cache, it will load almost instantly. Here's an example using your gravatar and a 30ms delay after load: http://jsbin.com/fazera/1
Firstly, to get an object by ID in jQuery, you have to use #.
var img = $("#gallows");
You can not use src or other "vanilla" properties directly on a jQuery object. You can, however do any of these:
Get the actual element from the jQuery object.
var img = $("#gallows");
img.load(function() { ... }
img[0].src = "image.jpg"; // First element in jQuery object
Use the jQuery method attr (recommended).
var img = $("#gallows");
img.load(function() { ... }
img.attr("src", "image.jpg");
Get the element just like you do now.
var img = document.getElementById("gallows");
img.onload = function() { ... }
img.src = "image.jpg";
please make sure that you have your jQuery code that's within the HEAD tag, inside:
$( document ).ready(function() { ...your jQuery here... });
More info: Using jQuery, $( document ).ready()
Your question: "Do I also need to refer to the jquery.js file from the hangman.js file?"
No, but place <script src="hangman.js"></script> tag in the header after referring to your jQuery file:
<head>
<script src="jquery_version_that_you_are_using.js"></script>
<script src="hangman.js"></script>
<script>
$( document ).ready(function() {
//Your jQuery code here
});
</script>
</head>
I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.
I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.
Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.
Example: http://jsfiddle.net/7TWYC/
Example with loading API in head section: http://jsfiddle.net/s2HkR/
So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.
EDIT:
I've set a bounty to 250 ontop of the 50 I had previously.
Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.
I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.
Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/
-
EDIT 2 ON Gijs ANSWER:
Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.
I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/
When I used this method, I load the API successfuly but the snippets.js file is not loading at all.
Fiddle: http://jsfiddle.net/9HX7N/
I belive what you want is it:
function loadSkyscanner()
{
function loaded()
{
t.skyscanner.load('snippets', '1', {'nocss' : true});
var snippet = new t.skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
}
var t = document.getElementById('sky_loader').contentWindow;
var head = t.document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange= function() {
if(this.readyState == 'complete') loaded();
}
script.onload= loaded;
script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
head.appendChild(script);
}
$("button").click(function(e)
{
loadSkyscanner();
});
It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.
The only restriction is, you need a iframe. But you can hide it using display:none.
A working example
EDIT
Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document.
When a script is loaded in a iframe, document is the iframe document.
There is a solution, but I don't recommend, is really a workaround:
function loadSkyscanner()
{
var t;
this.skyscanner;
var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");
function realWorkaround()
{
var tbody = t.document.getElementsByTagName("body")[0];
var body = document.getElementsByTagName("body")[0];
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
}
function snippetLoaded()
{
skyscanner = t.skyscanner;
var snippet = new skyscanner.snippets.SearchPanelControl();
snippet.setCurrency('GBP');
snippet.setDeparture('uk');
snippet.draw(document.getElementById('snippet_searchpanel'));
setTimeout( realWorkaround, 2000 );
}
var loaded = function()
{
console.log( "loaded" );
t = document.getElementById('sky_loader').contentWindow;
t.onLoadSnippets( snippetLoaded );
}
$("body").append(iframe);
iframe.load(loaded);
}
$("button").click(function(e)
{
loadSkyscanner();
});
Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.
You can see a work example here
The iframe loaded is this
EDIT
Fixed the bug you found and updated the link.
the for loop has gone and added a while, works better now.
while( tbody.children.length != 0 )
{
var temp = tbody.children[0];
tbody.removeChild( temp );
body.appendChild( temp );
}
For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.
So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.
Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).
Here's an almost-working example: http://jsfiddle.net/a8q2s/1/
Here's the steps I took:
override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
Tell Skyscanner to load the module.
Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:
http://jsfiddle.net/a8q2s/3/
(note: this still seems to use a timeout loop internally)
In the skyrunner.js file they are using document.write to make the page blank on load call back... So here are some consequences in your scenario..
This is making page blank when you click on button.
So, it removes everything from page even 'jQuery.js' that is why call back is not working.. i.e main function is cannot be invoked as this is written using jQuery.
And you have missed a target 'div' tag with id = map(according to the code). Actually this is the target where map loads.
Another thing i have observed is maps is not actually a div in current context, that is maps api to load.
Here you must go with the Old school approach, That is.. You should include your skyrunner.js file at the top of the head content.
So try downloading that file and include in head tag.
Thanks
I have a very bare HTML page that loads two JS files. One of these JS files then goes and loads a varying amount of content into the page.
I'm trying to get the equivalent of window.onload for this extra content. Obviously, window.onload actually fires very quickly, when the page is done loading the two JS files.
Any ideas? I know I can go and attach onload events to every image/script/etc on the page, but would rather not...
EDIT. If the callback won't help .load should do the job. I've added it to the example.
In this case you need a call back. Are you using a JavaScript library? if so what library?
In your existing code, after you append to the document you need to call a function that can execute the next bit of code.
something like this.
//FILE 1
$(function () {
$('body').append(someHTMLOrDOMNodes);
//I don't know what your second script does, but you should name this callback something relevant.
$('#idOfNewContent').load(function() {
callback();
});
});
//FILE 2
function callback() {
//next bit of code.
}
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);
}
});