Waiting for .ready and button click before function - javascript

My Google map only shows if function a is document.ready. However, then the function dothis() is called before the user clicks a button which calls function getMyID(inputId).
How do I run my script when the document is ready and a button is clicked?
Here's my code:
function dothis(inputId)
{
if (inputId == "1"){
dlat=30.745271;
dlng=0.578793;
getLocation();
}
else if (inputId == "2"){
dlat=40.836671;
dlng=0.578793;
currentloc();
}
}
$(document).ready(function a() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=ALsbSyEQvVel4MCu9xMBvD_92qAuqrFrcnos0dc&libraries=geometry,places&sensor=true&callback=dothis';;
document.body.appendChild(script);
};
$(document).ready(function() { a(); })

Well, why not call a() like
$(document).ready(function() { a(); })
Or if you don't use jquery, then
window.onload = a();
OnLoad works a bit differently though: it doesn't wait for the resources to load (e.g. images) to fire the event. jQuery document-ready event will wait for all the resources to load and then fires the event.

If you want to use jQuery, try it this way :
function dothis() {
...
}
$(document).ready(function() {
$('#MyButton').click(dothis);
}
This way, the button will be associated to the dothis function which can be called once the document is ready ;)

what you want to do is to call window.onload and initialize you button click handler there
eg
function dothis() {
// Do this
}
function getInput(input) {
// Get input
}
function init() {
document.getElementById('mybutton').onclick = getInput
}
window.onload = init

Related

How can I execute an action on element only when it's loaded?

I'm trying to write a script that simulates a click on a certain button on page. I tried using window.onload but it doesn't work. It seems to me that the problem is that when my script starts executing, the element I want to interact with doesn't exist yet. How can I do that?
Here is what I tried:
window.onload = function() {
document.getElementsByTagName('story')[0].onload = function() {
document.getElementsByTagName('story')[0].click();
};
};
Set click() in a recursive function that uses setTimeout()
window.onload = function() {
function findButton(){
setTimeout(function(){
let btn = document.getElementsByTagName('story')[0]
if(!btn){
findButton()
}else{
btn.click()
}
}, 300)
}
findButton()
}

how to get jquery to run repeatedly

I currently have a piece of jquery code that looks for a specific URL (with an anchor at the end) and runs a function if it has a match. The code only runs once, if this is the first URL loaded. Is it possible to have the following code running until it has a match?
$(document).ready(function(){
var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
$(function(){
if (location.href==url){
paintLine();
}
})
});
It only runs the first time, because changing the hash does not fire the DOM ready handler again, it does however fire the hashchange event.
$(window).on('hashchange', function() {
if ( window.location.hash === '#backup-section-3' ) {
paintLine();
}
}).trigger('hashchange'); // fire on first load as well
Note that the window is always available, and does not need a DOM ready handler
you can use setTimeout() function to run your function, for example every second:
$(document).ready(function(){
var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
function test() {
if (location.href == url) {
paintLine();
} else {
setTimeout(test, 1000);
}
}
test();
});
but what is your idea, behind your code? I sure there is more convenient ways to do your task.
using adeneo's answer:
here is what matches your code:
$(document).ready(function(){
var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
$(function(){
if (location.href==url){
paintLine();
}
});
$(window).on('hashchange', function() {
if ( location.href == url ) {
paintLine();
}
});
});

Call window.onload function in code behind not working

I have written a js function in aspx like below
window.onload = function () {
document.getElementById('grid-overlay').style.display = 'block';
}
Now I want to call this function in code behind. I tried like below:-
if (dtmkey.Rows.Count > 0)
{
HidMode.Value = "M";
HidMKey.Value = dtmkey.Rows[0]["mkey"].ToString();
var scriptSource = "function onload() { alert(""); };\n";
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true); // Not working
}
kindly suggest what is wrong
window.onload is an event handler for the load event of a window & the attached function is function that will be called on load event.
Also it is not clear what you are trying to do at this point
// I ran this variable in console, it threw unexpected syntax
var scriptSource = "function onload() { alert(""); };\n"; //
Are you trying to call a function expression here?
you can make this changes and test it
function onload(){ // This is a function expression and onload not same as window.onload
document.getElementById('grid-overlay').style.display = 'block';
}
window.onload = function () {
onload() // call onload function here once window has finished loading
}
If you are looking for onload here you can replace the below snippet
var scriptSource = "function onload() { alert(""); };\n"; with `onload();`

window.onbeforeunload executed on page refresh instead of on page close

I'm using window.onbeforeunload to pop up a confirm dialog when a close event occurs, but the confirm dialog appears on page refresh and doesn't execute on page close.
Here's the JavaScript code:
<script language="JavaScript">
window.onbeforeunload = confirmWinClose();
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
</script>
I tried it on Chrome, Firefox and Internet Explorer.
PROBLEM WITH YOUR CODE:
the function will be called when you refresh, because on refresh the page is unloaded and then reloaded.
in your solution, you should also note that you are not assigning a function to window.onbeforeunload but you are assigning the return value of the function when you write
window.onbeforeunload = confirmWinClose();
which might also execute the function (based on where you place it in the javascript) whenever the assignment is done. For e.g.
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
window.onbeforeunload = confirmWinClose();
the above code will execute the confirmWinClose function whenever this js is loaded.
(not your case as you have defined the function after call, so won't be executed on load, but you should remember this)
SOLUTION:
the below solution is working for close also
instead of your solution, i tried this
JS:
window.onbeforeunload = function() {
var confirmClose = confirm('Close?');
return confirmClose;
}
or
window.onbeforeunload = confirmWinClose; //note the absence of calling parantheses
function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}
this works as expected.
also note that you should return from the onbeforeunload explicitly.
even if you have to call a function, you should do
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
No full solution, but you can intercept the F5 key (not intercepted if the user click on the refresh browser button...)
var isRefresh = false;
// with jquery
$(function() {
$(document).on("keydown", function(e) {
if (e.which === 116)
{
isRefresh = true;
}
});
});
window.onbeforeunload = function() {
if (! isRefresh)
{
return confirm ('Close ?');
}
return false;
};
Since you anyway only want to display your text, What just using the onbeforeunload as it is expected just return the string?
<script language="JavaScript">
window.onbeforeunload = confirmWinClose;
function confirmWinClose() {return "close?";}
</script>
Try this it will work. You were assigning the method to onload that need to execute when it event occur so its need to be like object. refer link for better explanation - var functionName = function() {} vs function functionName() {}
window.onbeforeunload = confirmWinClose;
function confirmWinClose () {
var confirmClose = confirm('Close?');
return confirmClose;
};

window.onload executing before the web is loaded

Im using this code to fire a function right after the page is loaded:
function loadpapi(){
alert("Hello World!");
}
function pctaddLoadEvent(func) {
var oldonload = document.onload;
if (typeof document.onload != 'function') {
document.onload = func;
} else {
document.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
pctaddLoadEvent(loadpapi());
But is starting before the page loads, you can try it here: http://jsfiddle.net/KuTxh/
pctaddLoadEvent(loadpapi());
This code calls loadpapi (just like any other function call) and passes the result to pctaddLoadEvent.
You want to pass the function without calling it.
I changed the event from document.onload to window.onload: see a discussion here.
This document.onload vs window.onload is a complicated subject. It is likely the document.onload event isn't fired by your browser at all. (Or, as one deals with the window and the other with DOM tree, it is possible that the document.onload event has already fired when your javascript function took action - more testing can confirm that.)
Also, the function passed as parameter goes without the (), as you want to pass the function itself, not its returning value.
function loadpapi(){
alert("Hello World!");
}
function pctaddLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
pctaddLoadEvent(loadpapi);
Check demo fiddle: http://jsfiddle.net/st4kQ/

Categories