Is it possible to call a function on pageload [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript that executes after page load
script type="text/javascript">
function ip(ban, win) {
var width = 15;
var height = 10;
if (newwin) {
}
</script>
</head>
<b><input type="button" value="Check" onclick="banow();"/></center></b>
Does anyone know if it is possible and how to make this function start on page load, preferably with a interval?
I am new to all this, extra help would be appreciated!

Something like this should work:
window.onload = function() {
setTimeout(banow, 2000);
};

You can just use the onload event, apply the onload event to an event listener, or put a () right after the closing curly bracket of your function.
//e.g. 1:
window.onload = function(){
setTimeout(function(){
function_to_call();
}, 1000);
};
//e.g. 3:
window.addEventListener("load", function(){
setTimeout(function(){
function_to_call();
}, 1000);
}, false);
//e.g. 2:
function function_to_call(){
}();

In jQuery:
$(function(){
// your methods here, will be called after page has been loaded
setInterval(functionName, 1000); //replace functionName with your function, 1000 is millisecond
});

You need body and onload event, please check: http://www.w3schools.com/jsref/event_body_onload.asp

<script type="text/javascript">
window.onload=function(){
alert("hello"); //call your function here
}
</script>

You can call onload in body
eg.
<body onload="ip(parameters)">
</body>

Related

How do I trigger a javascript function if body is clicked after certain seconds?

I need to trigger a window.open function on the click of body, but only if the click is after few seconds.
EXAMPLE:- if the second click is done immediately, it shouldn't open the window. but after 5 seconds, if the click is made, the window should open.
My code isn't working.
<script>
setInterval(myadFunction,5000);
function myadFunction()
{
$("body").click(function () {
window.open("https://www.google.com");
});
}
</script>
This is a wordpress website., and I entered this code before <body> tag.
Why isn't it working?
You can use a flag to simulate what you want. In this case "canClick" flag will do the job for you.Reset it back to true after your desired timeout.
var canClick = true;
$("body").click(function () {
if (canClick) {
window.open("https://www.google.com");
canClick = false;
setTimeout(() => {
canClick = true
}, 5000);
}
});
Let me know if you face any issue with this snippet.
You could try something like:
<button onclick="timeFunction()">Submit</button>
<script>
function timeFunction() {
setTimeout(function(){ window.open("https://www.google.com"); }, 5000);
}
</script>
It consists of this:
setTimeout(functionname, milliseconds, arg1, arg2, arg3...)
The following are the parameters −
functionname − The function name for the function to be executed.
milliseconds − The number of milliseconds.
arg1, arg2, arg3: These are the arguments passed to the function.
First of all. You should make sure that you are placing the code in the right place. Since it's Wordpress. That bugger really get on my nerves. Try putting it in the active theme.
var click_allowed = 0; //global var (you use const if supported)
setTimeout(function(){ click_allowed = 1; },5000);
jQuery('body').click(function(){
if(click_allowed) window.open("https://www.google.com");
});
jQuery has been used instead of $ for the selectors due to wordpress native jquery limitation.
you can use settimeout(function, millisecond)

delay a function call on button click - javascript

I am attempting to delay a function call on button click using javascript in a manner when you click the button it should delay for like 3 or 5 seconds before calling the function. This is my snippet:
jQuery(document).ready(function(){
$('#myButton').on('click', myFunction);
setTimeout(function() {
myFunction();
}, 5000);
function myFunction() {
var text = $(".total").text();
alert(text);
}
});
How can I get it right such that the function is called only when the button is clicked with a delay of 5 seconds?
You can try below code, I done some changes in your code snippet :
jQuery(document).ready(function(){
$('#myButton').on('click', function(){
setTimeout(myFunction, 5000);
});
function myFunction() {
var text = $(".total").text();
alert(text);
}
});
The issue is because you're providing the reference to myFunction() to the click handler, hence it's called immediately.
Instead you need to put the setTimeout() call in an anonymous function that you provide to the click. You also need to place the myFunction() definition in scope of the window so that it's available from the setTimeout() call. Try this:
$(function() {
$('#myButton').on('click', function() {
setTimeout(myFunction, 5000);
});
});
function myFunction() {
var text = $(".total").text();
alert(text);
}
jQuery(document).ready(function(){
$('#myButton').on('click', myFunction);
function myFunction() {
setTimeout(function(){
var text = $(".total").text();
alert(text);
}, 5000);
}
});

How do I move inner HTML script to a seperate Javascript?

So I'm trying to clean up my code and currently the following scripts are in my HTML header
<script type="text/javascript" src="js/mobile.js"></script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});
</script>
I understand that this is quite redundant but I'm a beginner and am still learning. What I'm trying to do is move this code to the mobile/js linked at the very top of the code.
What I have inside the mobile.js right now looks as follows
//initializes each function.
function init() {
hideMenu();
scaleContent();
linkAnim1();
linkAnim2();
linkAnim3();
linkAnim4();
linkAnim5();
}
function hideMenu(){
TriggerClick2 = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
document.getElementById("navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
document.getElementById("navi").animate({width:'0%'}, 1000);
};
});
};
function scaleContent(){
TriggerClick = 0;
document.getElementById("hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
document.getElementsByClassName("content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
document.getElementsByClassName("content").animate({width:'100%'}, 1000);
};
});
};
function linkAnim1(){
document.getElementsByClassName("stayThere").mouseenter(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
document.getElementsByClassName('moveThere').animate({'margin-left': '-100%'}, 1000);
});
};
//initializes the js functions above
window.onload = init;
sadly the moment I comment it out of the html document it stops doing anything altogether. To explain the functions, the first two are for mobile, bringing in the navigation while resizing the content, the other 5 are for each link Hover to animate a background image.
I'd really appreciate if someone could help me with this as I need it for January 4th, until which my teachers are unavailable.
Thanks again and happy coding
Ok I going to help you the best I can with out doing all of the work for you.
To begin you need only one document ready function for your script.
So take all of the JavaScript Code inside of the document ready functions and place it inside of a single document ready function.
Once you do that link to the JavaScript file by using the script tag right before your closing </body> tag in your html file.
Example(link to external JavaScript File):
<script src="myjavascriptfile.js"></script>
Note: The html code below assumes that your html file is in the same directory as the JavaScript.
Example(External JavaScript File Content):
$(document).ready(function(){//begin document closure
TriggerClick2 = 0;
$("#hamburger").click(function(){
if(TriggerClick2==0){
TriggerClick2=1;
$("#navi").animate({width:'35%'}, 1000);
}else{
TriggerClick2=0;
$("#navi").animate({width:'0%'}, 1000);
};
});
TriggerClick = 0;
$("#hamburger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$(".content").animate({width:'65%'}, 1000);
}else{
TriggerClick=0;
$(".content").animate({width:'100%'}, 1000);
};
});
$(".stayThere").mouseenter(function() {
$('.moveThere').animate({'margin-left': '0%'}, 1000);
}).mouseout(function() {
$('.moveThere').animate({'margin-left': '-100%'}, 1000);
});
});//end document closure
Now with that being said there is a lot of things that may be going wrong with your code. Posting your markup(HTML) will help with troubleshooting.
You are using global variables for your TriggerClick2, and TriggerClick one variables. Prefix them using the var keyword and place them at the top of the script inside of the document ready function.
You should try and get in the habit of using === instead of ==. Using === evaluates to exactly equals(matches value and type) where == matches the value. So if you want to make sure your matches the value and the variable type(number and string for example) then use === to prevent any potential headaches in the future.
Example:
var TriggerClick2 = 0;
var TriggerClick = 0;
Keep in mind that variables are scoped at the function level in JavaScript. So any variable that is declared inside of a function can not be accessed outside of the function it is declared in unless it returned by called a function that returns that variables value.

Add delay after showMessage()

I have this code
<script type="text/javascript">
var currentBlock;
function onSuccessEditUser(result) {
showMessage(result.Message);
window.location = '#Url.Action("UserIndex")';
}
</script>
and I would like to add a little delay after showMessage and before window.location.
How can I do that?
You can use setTimeout to fire off the code after a specified interval:
function onSuccessEditUser(result) {
showMessage(result.Message);
// Wait 1 second
setTimeout(function() {
window.location = '#Url.Action("UserIndex")';
},1000);
}
use java script setTimeOut method to execute something after specified time
<script type="text/javascript">
var currentBlock;
function onSuccessEditUser(result) {
showMessage(result.Message);
// Wait 5 second
setTimeout(function() {
window.location = '#Url.Action("UserIndex")';
},5000);
}
<script>
You could use a setTimeout(function(){showMessage(result.Message);}); function.
Or opt for jQuery $(..).delay(300); http://api.jquery.com/delay/
Whichever you prefer.

How to Set OnClick attribute with value containing function in ie8?

My goal is to change the onclick attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3.
For example, this works in Firefox 3, but not IE8. Why?
<p><a id="bar" href="#" onclick="temp()">click me</a></p>
<script>
doIt = function() {
alert('hello world!');
}
foo = document.getElementById("bar");
foo.setAttribute("onclick","javascript:doIt();");
</script>
You don't need to use setAttribute for that - This code works (IE8 also)
<div id="something" >Hello</div>
<script type="text/javascript" >
(function() {
document.getElementById("something").onclick = function() {
alert('hello');
};
})();
</script>
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too.
.....
You also can use:
element.addEventListener("click", function(){
// call execute function here...
}, false);

Categories

Resources