JQM .bind function call hangs on a method, but script still completes - javascript

I'm just getting started with Javascript, jQuery, and jQuery Mobile. I'm trying to go through a tutorial online, but I'm getting caught up on the mobileinit event handler. Here is the code:
<script type="text/javascript">
$(document).bind("mobileinit", function() {
Notes.testHelper.createDumyNotes();
Notes.controller.init();
});
</script>
If I put an alert before and right after Notes.testHelper.createDummyNotes(); the alert is called. However, if I put the alert right after Notes.controller.init(), the alert isn't called. I imagine this means the code stopped in that function. However, if I put an alert right before the closing script tag outside of the function, that alert is called--This is what confuses me. How can a method hang and not allow the rest of a function to complete but still let the script complete?
As an interesting aside, I forgot to put the script tags around this .bind function at first, and the html was styled correctly. However, once I put the tags around this function, the html appeared but wasn't styled.
Any suggestions? As I said, I'm new to javascript, so this could be a fundamental misunderstanding of the way the language executes.
Thanks for your help!

The contents of $(document).bind("mobileinit", function() { ... } will be called when the mobileinit event is triggered, which will be AFTER the code between the script tags are read. This is why the alert you placed just before the closing script tag is executed.
If you put alert(1); before the closing tag, and alert(2); after the function() { and alert(3) after the createDumyNotes(), you will probably get 1 and 2 but not 3.
I think you're on the right path in that the error is occurring in the createDumyNotes() function. I suggest you get into that function with some try { ... } catch(e) { ... } and pinpoint where the error is occurring (assuming Notes and Notes.testHelper are valid objects, and Notes.testHelper.createDumyNotes() is an existing function.
EDIT
I just noticed that your function is createDumyNotes() instead of createDummyNotes(). Is this nothing more than a misspelling?

Related

Only part of JQuery executable. When pasted in HTML directly everything works (window.location)

I have a JS file, which works flawlessly, and executes all the code in it.
But I now added the following JQuery:
$("#need2Know").click(function(){
window.location ="URLString";
return false;
});
$("#nice2Know").click(function(){
window.location ="URLString";
return false;
});
When I call this part of the code in the HTML file, the onclick Handling executes as expected.
However, as soon as I paste it in the JS file (above all other code, the remainder of the code still working), the onclick handling does not work anymore.
I use the following JQuery library:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
My JQ file is called after this library.
What is so strange to me is, that the code works in HTML but not in the JS file, although the rest of the code still processes as before...
Any advice on how to fix this, so the click-handling can be performed in the JS?
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call. As the DOM is not loaded yet, no event handlers are attached.
You can solve the problem by one of these methods:
Wrap the code in document-ready handler.
Specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
});
Move the reference to the file to bottom of the <body> element.
Try this code:
$("body").on("click","#nice2Know", function(){
window.location ="URLString";
return false;
});

JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code:
var e = document.getElementById("overlay");
e.parentNode.removeChild(e);
This code is supposed to remove the DOM element, but it doesn't. So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (i.e. the element was successfully removed).
This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue?
Thanks in advance.
EDIT: Thanks for quick replies. Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging).
EDIT 2: I was asked to clarify the code. I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading):
window.addEventListener('DOMContentLoaded', function() {
new QueryLoader2(document.querySelector("body"), {});
});
No errors present (except for a 404 error because of missing image, which has no impact on Javascript).
As Teemu mentioned #overlay more than likely doesn't exist when the code is run.
For a test.. Try wrapping your code in either of these...
Javscript
window.onload = function () { /*your code*/ };
Jquery (if included)
$(document).ready(function () { /* your code*/ });
You should execute your code after the DOM tree has finished loading. One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired.
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
Look at this answer for more information: $(document).ready equivalent without jQuery

Ajax call not running onKeydown

I have this ajax call that's suppose to run when a key is pressed on a specific textbox. Once in the call, it runs a function that fires an alert. But, its doesn't work. Maybe it's cause I wrote the call using an old forum post as reference. Assume, I called the jquery library cause on my test I did but I didn't post it here.
This is what I've tried so far:
<script>
$("#<% =tb.ClientID%>").keydown
(
function ()
{
debugger; alert("hello");
}
);
</script>
<body>
<asp:TextBox Id = "tb" runat = "server"/>
</body>
I'm new to these kind of calls. I'm very familiar with js functions, but I've never done this. Any explanations and suggestions, would be greatly appreciated.
HTML is processed line by line. So when it processes the contents of that script tag, it hasn't yet processed anything further down, such as the body tag or its contents.
Inside the script, you're running $("#<% =tb.ClientID%>"). It'll try to find an element by its ID, but since the body hasn't been processed yet, it will yield no results. With no results, it has nothing on which to set the listener for .keydown.
It's in cases like these that using jQuery's $(document).ready function or its equivalents becomes incredibly important and crucial to the code. $(document).ready accepts a function, and it will wait until the DOM is fully loaded before executing that code. So putting $("#<% =tb.ClientID%>").keydown.... inside of a $(document).ready will ensure that the element has a chance to enter the DOM before the .keydown listener is attached to it.
You can find the docs for $(document).ready() here.

How to check dynamic javascript value with Jquery with IE

I am stuck on this, please help!
I have an external Javascript that inserts code on my page. Among other things it inserts an image wrapped in a div. I do not have control over the script, but I would like to change the image path/url using Jquery.
This is what I have done:
$('.ProductImage img').attr('src',function(index,attr){
return attr.replace('small','original');
});
Works like a charm in all browsers except IE.
When checking the selector with alert(), IE returns %Thumbnail% which is the Javascript variable/object. I have tried wrapping my script in a timeout to allow IE to finish loading but no luck.
Any ideas?
Thanks in advance!
Have you tried wrapping your code inside $(function(){ .. }) so that it will run after the document finished loading?
If your script is not loaded by the time your code gets executed you could try putting the code inside window.onload
window.onload = function(){
replaceImages();
};
function replaceImages(){
$('.ProductImage img').attr('src',function(index,attr){
return attr.replace('small','original');
});
}

JavaScript TinyMCE/jQuery race condition on firefox

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);
}
});

Categories