I apologize for this rather BASIC question, but I am at whits end here!
I have a javascript function that I want to run when the page loads... simple right? I have tried putting the function in doc readys, window readys, putting it before and after the main function, etc etc. NOTHING seems to work.
Code so far:
function calcme() {
DA FUNCTON
}
$(document).ready(function(){
calcme();
$("input").bind("keyup", calcme);
});
Please note... the keyup bind DOES work, but I need the calcme function to load on page load. Thoughts?
UPDATE: As per request, here is the full fiddle. http://jsfiddle.net/vpsSA/
Problem found: The calcme() function assumes it is called from the context of one of the inputs and uses this.value inside. So, when you call it without any arguments, it obviously fails. This can be solved by trigger the keyup of each of your inputs, instead of calling calcme() directly. See the fiddle below.
Working fiddle: http://jsfiddle.net/vpsSA/1/
In your ready() handler, the bind statement comes after the caclme() call. And as you mentioned the event binding worked. This means:
a) calcme() was definitely executed on load. There is no other way since you've mentioned that the binding statement which comes after the calcme() call worked as expected.
b) calcme() did not throw any JS errors - if so, it would have stopped at the error and the event binding would not have taken place. Maybe it threw a warning, which you'll be able to see in your JS console.
c) Since you haven't provided whats inside calcme(), we can't say for sure. But what it looks like is some sort of condition failure because of which you did not get the expected result from calcme() when running on load. Are you using anything inside calcme() thats initialized after running it on load. I would suggest putting in a debugger; statement as the first line in your ready() handler and tracing it in Firebug or Chrome.
try this:
function calcme() {
try {
//your code
}
catch(e) {
alert('error: ' + e);
}
}
if (typeof $ === undefined)) {
alert('not jquery');
}
$(document).ready(function(){
if (typeof calcme === undefined) {
alert('calcme not exist');
}
else {
calcme();
$("input").bind("keyup", calcme);
}
});
Related
I have a function I need to call from a few different places, the function runs after clicking an 'a' tag or from a submit event, and in all three instances I need to preventDefault but I get the error 'cannot preventDefault of undefined'.
$('a#Link').on('click', supaFunc);
function supaFunc(e) {
e.preventDefault();
// do all the things...
}
Had a look at the documentation but I haven't solved it. I'm sure its to do with context, and I can make this work buy calling an anonymous function in the .on method that works fine, but I'd prefer not repeat this function three times.
jQuery event handlers should always receive the event as their first argument. If it's undefined, I would suspect that you call the handler in a different fashion at some place.
To find out where and how, try changing the code to
function supaFunc(e) {
if (typeof e === 'undefined') {
debugger;
}
e.preventDefault();
}
Now, when the function is called without an argument, the debugger will kick in.
Open the developer tools of your browser and reload / run the page. When the problem occurs, follow the call stack downwards until you find the location where supaFunc was called without an event as an argument.
Example image of the Chrome Developer Tools debugger.
May be <a id="link"></a> does not exist in all three cases, the error seems point to that.
I have the following code:
File 1:
$(document).ready(function () {
addDataTableExts();
}
File 2:
function addDataTableExts() {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This seems to work okay. I now tried to replace this with the following:
File 2:
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
}
This doesn't work.
Is there some reason why it only seems to work if I do this the first way? I thought
that by changing the first line of File 2 then it would cause the code to get
executed without me calling it.
You changed the code from running in the ready event to running immediately. It seems that you are loading your datatable plugin after loading file 2, so the plugin doesn't exist yet when you try to use it.
If you put it back in the ready event, it should work:
File 2:
$(document).ready(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}
});
Note: Events in jQuery are not exclusive, so you can have several ready event handlers in the same page without problems.
"I thought that by changing the first line of File 2 then it would cause the code to get executed without me calling it."
If you actually changed only the first line as shown then you've created a syntax error - you've added an opening ( without a closing ). But simply adding the closing ) won't cause the now anonymous function expression to be executed. If you want the code to get executed without being called from File 1 you need to add extra parentheses () on the end to actually invoke the function.
Also you had a missing closing ) after the } at the end of $.extend(..., though that was also a problem in the first version of your code (and also a problem with the document ready handler in File 1).
(function () {
$.extend($.fn.dataTableExt.oStdClasses, {
sWrapper: 'no-margin last-child'
}); // <-- add missing ); here
})(); // <-- add missing )(); here
But you don't need the containing function at all unless it also wraps other code that you don't show, because that $.extend() statement on its on doesn't have any deleterious effect on the global scope.
Finally, if you do need to run that $.extend() after the page is ready but don't want to have a dependency between your two files you can add a document ready handler directly in File 2. Multiple document ready handlers will all be executed.
I am facing a error in javascript....
when the javascript function calling it is not working but if i set a alert('someting'); within the function then the script is running but if i comment off the alert within the script,
is not working.
what is the solution.......
put you code in try.. catch block and check is there any exception
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
alert(err);
}
Try putting your code in load event:
window.onload = function(){
// your code...
};
Or put your js code at the end of the page.
if you're running with firefox, you won't know whether error occur in this function or not.
When you include the alert your most likely giving elements on the page you are loading time to appear which are probably required for you JS to actually run.
You could try using:
window.onload = function(){
//drop some code in here
}
or you could use jquery and wrap your code into a document.ready function like this:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
You will need to load the latest version of jquery onto your page if you were to you this method.
Ok I have a flex app and I am adding a callback method like this:
private function init():void
{
ExternalInterface.addCallback( "playVideo", playVideo );
}
private function playVideo(videoSource:String):Boolean
{
videoDisplay.source = videoSource;
return true;
}
I am calling it with javascript like this:
function showVideo(video)
{
document.getElementById("video_overlay").style.display = "block";
//alert('no error');
document.getElementById("MiniMacVideoPreview").playVideo('https://www.kranichs.com/instore/minimac/videos/'+video);
}
I get this javascript error:
Object does not support this property
or method.
However if I uncomment and run the alert first. I get no error and it works perfectly.
My first thought was that the alert was buying time until the script could execute, so i tried to run the script inside a setTimeout() but did not work.
Any ideas?
Thanks!
I would try placing your code in something like jquery's
$(window).load function. I have a feeling that you are exactly right. By the time you close the alert, the dom and contents are finished loading and you can make your ExternalInterface callback method.
$(window).load
Otherwise, if you are using swfobject, you could do something like
swfobject.addLoadEvent(function() {
$("#swf_id").get(0).inited(callSomeOtherFunction());
});
I'm experiencing difficulties trying to invoke document.ready( function() {}) in my unit tests. Suppose I have multiple of them in my javascript file, and one of them called inside a named function i.e.
function myFunction() {
$(document).ready(function() {
//...
});
}
How do I actually invoke them in my unit tests so I can actually test them? I'm using JsTestDriver to unit test my javascripts.
Thanks.
If it's a unit test, I'm guessing you check the function outputs when given certain inputs?
Here's my opinion:
You should prepare for the case where document.ready is called and the case where it isn't.
So your unit test should run each function twice - once to simulate a pre-ready call and one to simulate a post-ready call. That is, you should have one run-through where anything that happens on document.ready DOES run, and one run-through where it's just ignored (presumably to be called later on in the lifecycle).
EDIT:
Just reread the question and understood it a bit more. You could just override $(document).ready to do what you want it to (which is NOT to wait for the DOMLoaded event to fire, but instead to run the functions immediately). This snippet will replace the $(document).ready function with a function that does exactly that. It should run before any unit tests.
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
if(postReady && fn) fn();
}
Example test case:
<html><head><title>whatever</title>
<script type="text/javascript" src="/JS/jquery-1.3.2.js"></script>
<script type="text/javascript">
var postReady = true; // or false to ignore the function calls.
jQuery.fn.ready = function(fn)
{
alert("We stole ready!");
if(postReady && fn) fn();
}
$(document).ready(function()
{
alert("The function is called.");
});
</script>
</head><body></body>
</html>
You know document.ready... works so just start with calling the functions within it. Ideally, if you just have an init function called by the ready function then you call one function, it does what you need, and you can continue with your tests.
You can take unit testing too far, in this case you need to ask yourself what you are testing, and why. The JQuery document.ready function works, and work well (you know this because it's been tested by many many people).
I would assume the trick would be to, instead of creating an anonymous function, naming one, and using it.
//So instead of this...
$(document).ready(function() {...});
//Do the following
$(document).ready(my_function);
Then you just test my_function and make sure that it is working. Make sure that you test the functions in the order their going to be loaded for an accurate test.
I suggest you to refactor the code. Even if you find a way to call it, it will be hard to understand for other developers.
Also (IMHO, I am not quite sure) you have to call the ready handlers even after the pages ready event was triggered, because if you "install" the ready() handler, if the document.ready event was already trigger, jquery calls that handler immediately (so it never loses that event, even if your code added a handler too late - that is, way after document.ready was still done).
Couldn't you just create a user my_on_read() event ? Or something the like?
Well, in the end, please just take care of ready() events and handlers that will be installed after the document.ready() is already done :)
Part of the answer to this question can be found here.
Below is the sample code to answer this question based on the above answer:
myFunction();
$.readyList[1]();
The index assumes that there is only 1 document.ready function in the source file. Index 0 refers to something else which I believe is info on the browser.