Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
very new to JS and just playing around with examples I have written from a book.
With the code below - why are my functions not being executed? I am calling them and the syntax is correct. If I place document.addEventListener ("DOMContentLoaded" , init , false) ;
then the init() function will execute but not the test() function.
I am also confused as to where the document.addEventListener should be placed normally and exactly what it means with regards to the init function. Should the init() function always be called first? What normally goes in an init()function?
Thanks in advance. Code below ;
function init() {
var panel = document.getElementById("panel");
panel.innerHTML = "Hello World";
}
function test() {
var panel = document.getElementById("panel");
panel.innerHTML = "See ya";
}
init();
test();
You are probably executing the functions before the DOM elements have been loaded. The page is read from top to bottom. If the function executes before the HTML is read, the element won't exist.
Many developers make the script the last element in the body to avoid this.
Or use an onload handler, like this
window.onload = function () {
init();
test();
}
The functions do not need to be defined in the handler
EDIT. It is also true that you are writing data to the same element, so only the second function will have a result you can see. You can write to a separate element, or do as one answer suggests and add the data together.
It sounds like the methods are being called, but they are raising errors because they are called before the DOM is finished loading. Under normal circumstances, script like this will be executed as soon as the browser reaches it, so if this happens before the DOM is loaded (which is usually the case), the calls to document.getElementById() will fail because the document hasn't been loaded.
You're close with your call to document.addEventListener ("DOMContentLoaded" , init , false); - this tells the browser to call init when the DOM has been loaded. However, you're only calling init in this case, so test() doesn't get called.
I would suggest removing your inline calls to init(); and test();, then adding the following:
function onLoaded(){
init();
test();
}
and then calling onLoaded from your event listener:
document.addEventListener ("DOMContentLoaded" , onLoaded , false);
Related
This question already has answers here:
window.onload vs $(document).ready()
(17 answers)
Closed 6 years ago.
we are building off a battleship game in github.
Battleship
Here user, is prompted with his name and position of his ships and based on the answer, output is displayed on a textarea called domsole.
Domsole = (function($) {
var output;
var init = function(outname) {
output = $('#'+outname);
output.attr('disabled', 'disabled');
};
var ask = function(question) {
write(question);
var text = prompt(question);
write('> ' + text);
return text;
};
var write = function(text) {
output.append(text + "\n");
output.scrollTop(9999999999);
};
return {
ask: ask,
init: init,
write: write
};
})(jQuery);
$(document).ready(function() {
Domsole.init('domsole_out');
});
However, the all the prompts are asked before the page is loaded.
some of the prompts are
this.name = Domsole.ask("What's your name, Playa?");
Domsole.write("Alright, " + this.name + " you shall be.");
........
......
var coord = Domsole.ask("Where would you like to take a shot? Valid input is: x, y");
These code that calls Domsole.write and Domsole.ask are also in document.ready.
Here all the prompts are asked before anything is displayed on the screen? How to resolve this issue?
It's a good habit to put your JS script tags at the end of the body, so that all your HTML loads first.
The browser engine loads HTML and JS in the order they appear in the document, but it's better to take ownership of that load order. One possible event order is:
domsole.js loaded.
battleship.js loaded.
index.html document ready event.
Game starts here.
No JS code should have executed before that last step. So make sure that your prompts are not called prior to that point.
It seems that you don't understand the execution flow of your application. There is no possible way that these questions are displayed before the page is loaded unless you have another call to the init function that you have not mentioned. The output variable will be undefined until the init method is called and would therefore lead to javascript errors if ask was called before init is called. It seems that you are mistaking "loading" for "rendering". If you want to ensure that rendering of the page has been completed before your code is executed than you should use a timeout of around 50ms to call your initialization functions. Any modifications to the page triggered in jquery's ready event will not be displayed until after the event processing is completed. By calling the setTimeout function within the ready event handler you can delay processing until after the rendering of ready event handlers are completed.
I am using Javascript with the window.onload and window.onbeforeunload functions.
In the onbeforeunload I want to run a code that removes an element from an existing list by iterating through the list via a method, but the method doesn't get executed.
When I use the same method in onload, everything works fine.
I think the code doesn't get executed in the onbeforeunload because the browser is already closed by then and that causes that the method doesn't get executed.
I think I need to do something Sychronous, do you guys have tips on how I can solve this?
// working
window.onload = function()
{
MethodA();
};
// not working
window.onbeforeunload = function()
{
MethodA();
};
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I want return the var "Page" in a Jquery function :
var Page ;
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
return Page = 'Crea_Bouton';
});
alert(Page); //does not work
But its does not work.
The goal is not to make an alert of the var Page.
In a other page i have : if(Page == 'Crea_Bouton') { //Action }
So, Page must be a global var
Can you help me, please?
There's several issues here. First of all, Page and page are two different variables, but let's assume you've named them the same - your code still won't work.
The problem is, your event handler is not run immediately, it's only run when the double click occurs. Defining page outside of the event doesn't make any sense in this context. What happens is it hits var page; first, then it registers an event (but DOES NOT run the event function), then alerts an empty variable (because the event has not been triggered yet).
When you do trigger the dblclick event, that alert doesn't get executed.
Try this:
var page;
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
page = 'Crea_Bouton';
});
$('#anotherdiv').click(function(){
if(page === 'Crea_Bouton'){
alert("yep!");
}else{
alert("Something else")
}
})
Now, when your #anotherdiv is clicked, it will only alert 'yep!' if the original Montant div has been double clicked first. Otherwise it'll do something else (or nothing at all if you omit the else).
Here's an example jsfiddle:
http://jsfiddle.net/Wb9Ba/
If you click the second button right away, it says "Something else", but if you double click the first button, and then click the second button, it says "yep!"
Use a "callback" function as jQuery does:
function onReturn(page) {
// Process your returned value
if (page == 'Crea_Bouton') {
// Action
alert(page);
}
}
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
var page = 'Crea_Bouton';
onReturn(page);
});
Or process your value inside the dblclick callback:
$('#Montant').dblclick(function(){
$("#Encadrement_Encaissement_Menu_Creation").show();
var page = 'Crea_Bouton';
// Do something with my page
if (page == 'Crea_Bouton') {
// Action
alert(page);
}
});
Since the anonymous method inside dblclick is asynchronous, it's impossible to return something.
Instead, you may create a new function:
var page;
$('#Montant').dblclick(function () {
$("#Encadrement_Encaissement_Menu_Creation").show();
display('Crea_Bouton');
});
function display(page) {
alert(page);
// ...
}
Is there any way to make my browser tell me what is the first JavaScript that is executed when I click on for instance a div.
Let me break it down:
Code example:
<div id='hello'> Hi There </div>
jQuery('hello').bind('click', function() { alert('hello') });
The code above will naturally display hello when I click on it. But is there a way to make firebug or console in Chrome to automatically break on the first very first JavaScript call without explicit set the break point.
In a complex JavaScript web pages there is a lot of binds but takes hours to find what is the actual code behind it.
you can get all events of an element with console.log($(element).data("events"));
So if I'm following the question you have this scenario:
jQuery('#hello') //function call 1
.bind('click', function(){ function call 2
alert('hello');
});
One method to do this would be to override the function you want to test. You cache the actual function, overwrite it with yours to do debugging in, then execute your cache with the original arguments.
(function(){
var _jquery = jQuery;
jQuery = function(){
console.log('debug');
_jquery(arguments);
}
})();
I'm binding the window.onload event like this
// It's a little more complex than this, I analyze if there is any other function
// attached but for the sake of the question it's ok, this behaves the same.
window.onload = myfunction;
Onload is triggered twice on my local machine a several times on the production server
If I change it by the jQuery equivalent
$jQuery(window).load(myfunction);
It behaves as expected (executed only once).
Could you help me to understand possible reasons why the first option it's not working as supposed?
Thanks!
The parentheses on your assignment — myfunction() — executes your function. You haven't shown what myfunction does, but this means that the return value from that function is being assigned to window.onload, not the function itself. So, I don't know how that is getting executed, unless you have somehow got that to work, like ending the function with return this;
You want
window.onload = myfunction;
Given the nature of window.onload, it seems unlikely that pure browser events alone are making both calls to myfunction. Therefore, a breakpoint inside your function will help you see the call stack. I've included screenshots for Chrome.
Sample code:
var alertme = function() {
alert("Hello");
}
window.onload = alertme;
function testsecondcall() {
alertme();
}
testsecondcall();
Open your page in Chrome.
After the page has loaded once, open the Developer Tools panel and put a breakpoint on the line inside your function, then refresh the page.
Check the call stack of both times that it breaks. One will be empty (the actual window.onload). The other should give you some information like the following:
On the right, under "Call Stack", you see alertme is called by testsecondcall