I am trying this code:
function view_mail_popup_close()
{
setTimeout("function () { $('#popupbox').fadeOut('slow'); }",200);
setTimeout("function () { window.location='view_mail.php' }",800);
}
I want to execute it onclick of a link, but only fading function works!
Can someone tell me why my redirect function not working?
I'm kind of surprised that either of them works, because you're giving setTimeout a string that defines a function without calling it; if you give setTimeout a string, it essentially does an eval on the string when the timeout occurs, which in theory would create but not call the function. (Edit: And I've confirmed that: http://jsbin.com/uvuje5)
It's almost never correct or necessary to give setTimeout a string; instead, give it a function:
function view_mail_popup_close()
{
setTimeout(function () { $('#popupbox').fadeOut('slow'); },200);
setTimeout(function () { window.location='view_mail.php'; },800);
}
Live example
There, the function is created immediately and the reference to it is given to setTimeout, which will call it when the timeout occurs.
(Off-topic: I've also added a missing semicolon at the end of the window.location = statemenet. JavaScript has semicolon insertion, and so the previous version would work, but I strongly advocate never relying on it.)
Update: As Capsule points out, there's a callback on fadeOut that you probably want to use instead of a second setTimeout:
function view_mail_popup_close()
{
setTimeout(function () {
$('#popupbox').fadeOut('slow', function() {
window.location='view_mail.php';
});
}, 200);
}
Live example
You should not be putting "function(){}" in quotes - if you use quotes then put the JS code directly there. What you are doing is syntactically incorrect:
Uncaught SyntaxError: Unexpected token
(
Just kill the quotes and feed function literals. You can nest them as such:
function view_mail_popup_close()
{
setTimeout(function () {
$('#popupbox').fadeOut('slow');
setTimeout(function () { window.location.href='view_mail.php' },600);
},200);
}
If you use quotes, it's slower because it does extra evaluation, and the scope is not kept intact because its defined in global scope, in addition you have to have the DIRECT JS code in there.
If this still doesn't make the page redirect to view_mail.php, please tell us specifically, exactly what happens. If it redirects to a 404/empty page, then you may need to specify root relative, eg href="/view-mail.php" with the leading /.
Related
Trying to get the code to automatically change page using setTimeout, but I do not get it to work.
setTimeout()(page3, 500);
function page3() {
changepage3('automatic')
}
This is what my code looks like right now, but I am suspecting that this is not enough. Anyone knows what is missing?
try this one
function page3() {
changepage3('automatic')
}
setTimeout(page3, 500);
setTimout needs a specific syntax to work, check it out on the best JavaScript documentation by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax
Here is an example
saySomethingAfter(5);
function saySomethingAfter(second) {
setTimeout(saySomething, second * 1000);
}
function saySomething() {
console.log("Something");
}
Your question is "How can I automatically change a page in Javascript?" using setTimeout. Let's analyse the needs:
change a page → open a new URL (cf. Open URL in same window and in same tab)
automatically using setTimeout → with the correct syntax
function changePage(url) {
window.open(url, "_self");
}
function changePageAfter5sec(url) {
setTimeout(function() {
changePage(url)
}, 5000);
}
changePageAfter5sec("https://stackoverflow.com")
Another way using beautiful functional JavaScript:
function changePage(url) {
return () => {
window.open(url, "_self");
}
}
function changePageAfter(second) {
return (url) => {
setTimeout(changePage(url), second*1000);
}
}
const changePageAfter5sec = changePageAfter(5);
changePageAfter5sec("https://stackoverflow.com")
You have 2 major problems in the code snippet provided:
That is not correct setTimeout() syntax - thus it doesn't actually work.
Even if it did work, it would call 1 function that uses another function which doesn't exist thus breaking the code.
fix problem number 1:
window.setTimeout(changePage, 5000);
now we have a running timeout that will trigger 5000 milliseconds after initiation(usually).
so let's fix problem 2 and let changepage() call an actual proper url opening function:
function changePage(){
window.open(urlOfPage3);
}
Finally a simpler version with an anonymous callback function in the setTimeout:
window.setTimeout(function(){
window.open(urlOfPage3);
}, 5000);
I use this code:
var x = require('casper').selectXPath;
...
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
this.test.assertExists(x("//a[contains(#id,'cell_13_1')]"), 'Clickable');
this.click(x("//a[contains(#id,'cell_13_1')]"));
});
I am trying to use if-else with assertExists to click another element if the first is not there:
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
if(this.test.assertExists(x("//a[contains(#id,'cell_13_1')]")==="PASS"){
this.click(x("//a[contains(#id,'cell_11_1')]"));}
else{
this.click(x("//a[contains(#id,'cell_22_1')]"));
}
});
But that does not seem to work. How would one do it correctly?
That's exactly what casper.exists() is for. You can also explicitly pass or fail some things:
casper.waitForSelector(x("//a[contains(#id,'cell_13_1')]"), function() {
if(this.exists(x("//a[contains(#id,'cell_13_1')]")){
this.test.pass("Clickable");
this.click(x("//a[contains(#id,'cell_11_1')]"));
} else {
this.test.fail("Clickable");
//this.click(x("//a[contains(#id,'cell_22_1')]"));
}
});
This code is equivalent to your first snippet. Comment the fail() call and uncomment the last click in order to get your "intended" behavior.
Btw, it doesn't make sense to fail some assertion and still continue with the script. You have to think about what exactly you want to test and what part of your script is supposed to be navigation to the component under test.
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
Is there a way to include a javascript file only once or declare a function only once? The issue I am having is that I have an HTML module that contains a javascript include. Well this module is loaded in a loop, and therefore that file is loaded multiple times. I've worked out most of the kinks, but what bothers me is that I know the same function is getting created multiple times, and this look can be as many as 30 iterations. To me, I don't like the fact that the same function is getting created over and over. Should I care? Is there a way I can prevent this? I know I can detect when a function exists, can I put the function declaration in between an if statement?
Update
I've tried out one of the suggestions:
if(typeof btnSendInvite_click != 'function')
{
function btnSendInvite_click()
{
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
but that doesn't work. I've also tried
if(!btnSendInvite_click)
{
function btnSendInvite_click()
{
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
but it doesn't work. What happens is that I have this line:
$(document).ready(function()
{
$(".btnSendInvite").bind("click", btnSendInvite_click);
});
and when the button gets clicked, that functions is executed six times, which is the amount of times that the file was included which tells me that the function is being created multiple times... I think.
Update
So after a lot of struggling, this problem is turning into something different than what I thought. The bind is being called multiple times, so it's getting bound multiple times, and therefore calling the function multiple times. I guess my next question is, is there a way to bind a function to a control only once? I've tried the jquery "one" already and it doesn't work.
Yes, you can (run on jsfiddle).
if (!window.myFunction) {
window.myFunction = function() {
//...
}
}
Edit: In your case it would be:
if (!window.btnSendInvite_click) {
window.btnSendInvite_click = function() {
alert("#invite_guest_" + $(this).attr("event_id"));
return false;
}
}
The call to bind() also has to be somewhere in that conditional block.
Note: The following variant won't work, at least not on all browsers:
if (!window.myFunction) {
function myFunction() {
//...
}
}
Edit 2: For your update:
Declare a variable when you call bind.
if (window.iBoundThatStuff!=true) {
iBoundThatStuff=true;
//call bind() here
}
Having JS included in a loop is ridiculous. Move your JS out of the loop.
JS can tell if function was defined but fixing bad server side loop in JS is definitively a bad practice.
Yes you should worry about not including your script file several times and not to declare the function several times...
For the first part, you may want to look into changing your html structure so the js file is only included once (even though js files are cached by the browser, and the second time may not actually go to the server -- depending of several factors... there's still a penalty)
Now as for declaring your function only once, remember that functions are also object (1st class citizens) in js, so you can test if a function is already define as if you were testing an object.... if(!window.myFunc) { window.myFunc = function(){} }...
You may want to look a bit into functions and scoping in js.. here are some links
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
http://www.yuiblog.com/blog/2010/02/24/video-crockonjs-3/
http://www.slideshare.net/douglascrockford/crockford-on-javascript-act-iii-function-the-ultimate
I am trying to call showUpload(); from within two setTimeouts. Neither works. It seems to be out of scope and I'm not sure why. I tried this.showUpload() which didn't work either.
$(document).ready(function(){
var progress_key = $('#progress_key').val();
// this sets up the progress bar
$('#uploadform').submit(function() {
setTimeout("showUpload()",1500);
$("#progressbar").progressbar({ value:0}).fadeIn();
});
// uses ajax to poll the uploadprogress.php page with the id
// deserializes the json string, and computes the percentage (integer)
// update the jQuery progress bar
// sets a timer for the next poll in 750ms
function showUpload() {
$.get("/myid/videos/uploadprogress/" + progress_key, function(data) {
if (!data)
return;
var response;
eval ("response = " + data);
if (!response)
return;
var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
$("#progressbar").progressbar({ value:percentage})
});
setTimeout("showUpload()", 750);
}
});
Thank you for your time.
As #Daniel said, this should work:
setTimeout(showUpload, 750);
Please note that the quotes should be removed (this is why it isn't being executed until the timeout runs out). Right now, you are passing a string, which is evaled when the timeout runs out. This eval will happen in a different scope, which is why you are seeing the problem you are seeing.
Instead, passing a reference to the showUpload function to setTimeout will allow your function to be executed later. Keep in mind that when it runs, it will be in a different scope, so you may have other scope issues, like with progress_key. You will need to create a closure around showUpload to capture that parameter.
It looks like you need to remove the parenthesis from showUpload in both your setTimeout calls. Otherwise you will be invoking the showUpload method instead of passing it as a parameter:
setTimeout(showUpload, 750);