document ready fires too early? - javascript

It is kind of theoretical question as it can't be checked right away. The problem is about the possible reasons why the jQuery code doesn't work, however it is loaded on the page now. Also, it DOES what it has to do right after the page is loaded and I copy-paste this script code from the source of the loaded page into the console.
<body>
<div id="id1">...</div>
<div id="id2">some html code goes here... </div>
<script>
jQuery(document).ready(function() {
var el = jQuery("#id1");
var var1 = el.width();
el.css({'margin-top':'10px','margin-bottom':'20px'});
jQuery("#id2").css('margin-top', var1+'px');
});
</script>
<div>and here... </div>
</body>
P.S. The jQuery library is loaded. There are no errors in the Chrome console. The script is in the body tag.
P.P.S. Can it be because of #id1 (contains ) is loaded from another site so document ready fired earlier? Is that exactly the reason?
Any other possible reasons?
Unfortunately, it is hard to check it right away as the access to that page is limited and takes several steps to update by other persons that can't be accessible right away.
However, the possible solution is needed right away.
Added id1 and id2 into the html code.

use window.onload is most often used within the element to
execute a script once a web page has completely loaded all content.
jQuery(window).load(function () {
var el = jQuery("#id1");
var var1 = el.width();
el.css({'margin-top':'10px','margin-bottom':'20px'});
jQuery("#id2").css('margin-top', var1+'px');
});

Related

Javascript/Jquery execution order issue

I am using external JavaScript to show video player on web page like...
<script src='http://player.field59.com/v3/vp/...........'></script>
Here is my code that cut the HTML code which is generated by above script tag and paste into specific container like <div id='dynamic-video-container'></div>
$(document).ready(function(){
if( $("div.subscriber-hide div.html-content div.bimVideoPlayer").length ) {
var video_content = $('<span>').append($('div.subscriber-hide div.bimVideoPlayer').clone()[0]).remove().html();
}
$('div.subscriber-hide div.html-content').remove();
$("div#dynamic-video-container").html(video_content);
});
I am doing this because I am not able to put external code directly into "<div id='dynamic-video-container'></div>" container.
My issue is this sometimes play functionality of video player is not working may be due to loading sequence of external code and code snippet.
Is there any option by which code snippet will execute when external js becomes fully loaded? Can anyone suggest idea to how to do this?
One more thing external code "<script src='http://player.field59.com/v3/vp/...........'></script>" is added by CMS so I am unable to change this line.
Try this
window.onload = function() {
//your code comes here
}
As window.onload is called after all the content and resources of the page are loaded. Hope this helps.

Notify JS with element Selector Doesn't works 100%

I'm using Notify JS from here :
http://notifyjs.com/
And this is my HTML :
<div>
<p><span class="elem-demo">aaaa</span></p>
<script>
$(".elem-demo").notify(
"Hello Box",
{
autoHide:false
}
);
</script>
</div>
It doesn't work correctly. I can see the arrow, but not the message.
I've check using my browser "inspect element", the class notifyjs-container has "display:none" and when i try change it into "display:inline" via my own css, the message does appear, but without its animation.
Anybody can help ?
Here I attach the image of the small arrow i said earlier :
You need to put the notify setup inside the doc ready, ie:
$(function() {
$(".elem-demo").notify("Hello");
});
What is happening is that the .notify() script is running before the page has fully rendered, so the .elem-demo does not yet exist when $(".elem-demo") tries to find it, so the .notify() has nothing to attach itself to.
$(function() { ...
is shorthand for
$(document).ready(function() { ...
which is jquery's way of saying - don't run this script until the page elements have completely finished loading.
It's generally a good idea to put all your scripts into a ready function like this (multiple $(function() { ... can be called, they don't need to be all in the same one).
More info on the jquery learning page: https://learn.jquery.com/using-jquery-core/document-ready/

Javascript element tag name undefined

So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.

Can someone explain to me how this is possible? (Picture in comments)

So I'm trying to link up my html and javascript files in notepad++, but it isn't working properly.
I wanted to know how it is possible that it writes test, but doesn't remove the div. Can anyone explain this? Thanks in advance!
1, jQuery isn't linked. Meaning, you don't have <script type='text/javascript' src='myjQueryfile.js'></script> in your HTML, you'll want to put it before your script.
2:
Because the element with the ID of blue, doesn't exist yet. The DOM - basically the object of your HTML - has yet to be constructed when your script is run, which in this case is the top of the page, before blue comes into existence. You'll want to use an event to fix this, typically $(function(){ ... }); which will execute your code when the DOM is ready.
Also, document.write just writes code then and there, meaning exactly where the document.write calls is made, the HTML will be outputted.
You should have linked jquery. You're trying to use it without having it linked.
The script is loaded in the head. At the time the script executes the body of the document is not built, so nothing is removed. If you were to use the document.ready callback (and had properly included jQuery) it would work
$(function(){ $("#blue").remove(); });
A plain js version of this is
window.onload = function(){
var b = document.getElementById("blue");
b.parentNode.remove(b);
};
At the time the script runs, only the portion of the document up to the <script> tag has been loaded. You need to delay until the DOM has fully loaded before the script can target the DOM:
document.addEventListener("DOMContentLoaded", function(event) {
$("#blue").remove();
});

Trying to load an API and a JS file dynamically

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

Categories