Changing visibility does not immediately hide iFrame - javascript

I have a page that on a certain action makes an iframe visible and fills the iframe with some HTML (say for example a multi-select box and an ok button).
The OK button on the iframe has the onClick method defined kinda like this:
onClick="parent.hideIFrame();parent.processMultiSelectBox();"
When User clicks OK on the iframe (presumably after playing with the multi-select box), I'd like the iFrame to disappear immediately and then the selected values in the multi-select box can be processed. But this is not what's happening. The iFrame remains visible during the time the other function runs and disappears only after the second function finishes.
The hideIFrame function is pretty straightforward:
function hideIFrame() {
frmObj = document.all.iFrameID;
if(frmObj) {
frmObj.style.visibility = "hidden";
}
}
I've paraphrased the above function for clarity (removed some indicator variable assignments etc.)
The second function actually loops on all the options in the multi-select object and does stuff with it. This takes about a half a second and only after that is done, does my iFrame disappear. It is a little bothersome to see it linger for half a second when I click ok.
My question is whether there is some way I can make the darn thing disappear faster. Speaking in "classical C" lingo, is there a "flush" for the change in visibility to happen immediately?
I did notice that if I put an "alert" as the first line in my second function, the iframe disappears immediately but now it is the OK on the alert box that lingers for the time it takes the second function to finish.
Thanks.
EDIT: Based on DDaviesBrackett's answer, this is what I ended up doing:
The onclick in the iframe changed to:
onClick="parent.hideAndProcessMultiSelectBox(parm1, parm2);"
The hideAndProcessMultiSelectBox function was defined as:
function hideAndProcessMultiSelectBox( parm1, parm2 ) {
hideIFrame();
setTimeout( function() { processMultiSelectBox( parm1, parm2 ); }, 0 );
}
Voila.. no delay..

You've gotten to the root of your problem already; document reflow doesn't happen until the current JS thread is done (so as not to repaint lots of times during JS execution). You need to return control to the browser before doing your expensive processing.
The simplest way to achieve that, though it doesn't make for obvious code in the slightest, is to call processMultiSelectBox in a setTimeout with a delay of 0:
onClick="parent.hideIFrame();parent.setTimeout(parent.processMultiSelectBox,0);"
If you need to pass parameters to the thing you're setting a timeout on, you have two options: set a timeout on a string that evals to Javascript (bad, bad, very bad, horrible) or define an anonymous function that calls the one you're interested in:
onClick="parent.hideIFrame();parent.setTimeout(function(){parent.processMultiSelectBox(foo, bar, 'baz');},0);"
RSolberg's response may also help, though there's a difference between visibility:hidden and display:none.

Related

Execute 2 JavaScript functions in order

I have a function with two lines and I want them to be executed in order. The function is :
showNotification(message){
$("#notificationMessageBody").html(message); // line1
$("#notificationModal").modal('show'); //line2
}
So, whenever I call showNotification("Hello World!") how do I ensure line1 is executed before line2 (meaning content loading is done before the modal triggers)
Basically, I am trying to fill in my message in modal body and then show it, not before filling.
--EDIT--
The functions are indeed executing one after the other, but my modal pops before jQuery loads my message into my #notificationMessageBody
As a result, for example : If I call showNotification("Hello") I get a modal with "Hello" (the arrangement of modals and stuff is done), but then after that if I call showNotification("World") modal appears with "Hello" first then after that it changes to "World".
Note : "Hello" and "World" are big junk of text, so loading that into my DIV must be taking some time, I believe. Even though they are executed one after other, it appears (to common-er) that firstly modal is popping and then replacement is done. I hope the picture is a little clear now.
No AJAX involved anywhere here around the function. Basically, this is my custom alert() function one can say. A modal with proper ID is there in my page. I change the modal-body content(with jQuery's .html() function) and trigger the modal to show, as seen from the code.
You can use the .promise() method (added in jQuery 1.6) to ensure the second one is executed after first is completed:
$("#notificationMessageBody").html(message).promise().done(function() {
$("#notificationModal").modal('show');
});

Programmatically change first page jQuery Mobile shows

My goal is to show a different first page depending on whether the user is logged in or not. The login check happens using a synchronous Ajax call, the outcome of which decides whether to show a login dialog or the first user page.
The normal way to do this would be to set $.mobile.autoInitialize = false and then later on initialize programmatically, as described in the answer to this question. For some reason this won't work, instead another page gets loaded every single time.
I decided to give up on this way and try out a different parcour. I now use a placeholder, empty startup page that should be shown for as long as the login check takes. After the login check it should automatically change. This is done by calling a function that performs the ajax call needed for authentication on the pagechange event that introduces this startup page. The function takes care of changing to the outcome page as well.
The trick is that it doesn't quite do that.. Instead it shows the correct page for just a short time, then changes back to the placeholder. Calling preventDefault in pagechange didn't prevent this, as described in the tutorial on dynamic pages. Adding a timer fixed this, leading me to think that the placeholder wasn't quite finished when pageshow got fired (as per this page on page events), or some side-effect of the initial page load still lingered.
I'm really clueless as to how to fix this seemingly trivial, yet burdensome problem. What causes this extra change back to the initial page? Also, if my approach to intercepting the initial page load is wrong, what would be the correct approach instead?
I use jQuery Mobile 1.4.0 and jQuery 1.10.2 (1.8.3 before).
EDIT: Below is the code to my last try before I posted the question here. It does not work: preventDefault does not prevent the transition to the placeholder page.
$(document).on("pagebeforechange", function(e, data) {
if (typeof(data.options.fromPage) === "undefined" && data.toPage[0].id === "startup") {
e.preventDefault();
initLogin();
}
});
function initLogin() {
// ... Login logic
if (!loggedIn) // Pseudo
$('body').pagecontainer("change", "#login", {});
}
If you're using a Multi-page model, you can prevent showing any page on pagebeforechange event. This event fires twice for each page, once for the page which is about to be hidden and once for the page which is about to be shown; however, no changes is commenced in this stage.
It collects data from both pages and pass them to change page function. The collected data is represented as a second argument object, that can be retrieved once the event is triggered.
What you need from this object is two properties, .toPage and .options.fromPage. Based on these properties values, you decide whether to show first page or immediately move to another one.
var logged = false; /* for demo */
$(document).on("pagebeforechange", function (e, data) {
if (!logged && data.toPage[0].id == "homePage" && typeof data.options.fromPage == "undefined") {
/* immediately show login dialig */
$.mobile.pageContainer.pagecontainer("change", "#loginDialog", {
transition: "flip"
});
e.preventDefault(); /* this will stop showing first page */
}
});
data.toPage[0].id value is first page in DOM id.
data.options.fromPage should be undefined as it shouldn't be redirected from another page within the same webapp.
Demo
I'm undergoing the same problem as the one described by #RubenVereecken, that is, a coming back to the initial page once the cange to my second page has completed. In fact, he posed the question "What causes this extra change back to the initial page?" and it hasn't been replied yet.
Unfortunately, I don't know the reason since I haven't found how the page-event order works in JQM-1.4.2 yet, but fortunately, the workaround suggested by #Omar is working for me.
It's not exactly the same code but the general idea works at the time of preventing a coming back to the initial page. My code is as follows:
$(document).on("pagebeforechange", function(event, data) {
if ( typeof (data.toPage) == "string") {
if (data.toPage.indexOf("#") == -1 && typeof (data.options.fromPage[0].id) == string") {
event.preventDefault();
}
}});
The condition data.toPage.indexOf("#") == -1 is because I checked that all the undesired coming-backs to the initial page were happening when the property '.toPage' was set to something like [http://localhost/.../index.html].

How to delay the onclick response of an element in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to tell browser to stay on current window
Can I delay the onclick action of an element. I have an element which calls a function in the onclick event. How do I delay the call to that function? I want to tell the browser to stop two seconds before performing the onclick action.
The element looks like this.
<div id="id01" class="channel" onclick="load_window('http://www.ewtn.com')"><a>EWTN.com</a></div><br/>EWTN television network</div>
If I put a setTimeout inside the load_window function, the browser treats the window.open as a popup and stops it. So I want to put the question a different way. Is there a way to tell the browser to wait before doing the onclick? In the .click of that element I have code that performs other functions.
$('.channel').click(function() {
$(this).addClass("selected");
show_layer();
setInterval("refresh_caption()",300000);
});
I am looking to delay the call to load_window() while still having that action be treated by the browser as a user action.
The quick and dirty way is to make a new function that wraps a timeout for the load_window call, and set that new function as the onclick value.
function channel_click(){
// anon wrapper function, 2 second delay
setTimeout( function () {
load_window('http://www.ewtn.com');
} , 2000 );
}
then
<div id="id01" class="channel" onclick="channel_click()"><a>EWTN.com</a></div><br/>EWTN television network</div>
no idea what your load_window function is actually doing, so I can't say what happens after the 2 seconds are up.
Again, this is specific to the example you provided. If you need a more generic approach, you'll have to provide more information.
No, there is no viable way to delay execution of the currently running javascript thread without hanging the browser for that period of time.
You could loop in a tight loop until 2 seconds elapsed and then do your popup thing, but that would be a horrible user experience and some browsers may even abort your script because of its non-responsiveness. I would NOT recommend this at all. It is a bad design.
Executing some code at a later time is normally done via setTimeout(), but you've already said you don't want to use that for popup reasons.
If you care to explain what problem you're really trying to solve, perhaps we can offer some other way to approach the problem.

Website: Detect when I arrive somewhere because of History Navigation

I have a page where I show a throbber when I navigate away from the page. Like <a onclick="throbber.show()"> on every link. When I now navigate back in Firefox, the throbber is still shown.
Is there any javascript event that is fired to the arriving webpage when I click back? Or one that is fired just when the webpage is changed to the new one? Or can I make my throbber more intelligent?
Thanks for any input!
put this in your html:
<form name="_browser"><input id="checker" value="1" type="hidden"></form>
and also this javascript:
function cacheCheck()
{
var checker = document.getElementById("checker");
if (checker.value == 2) return true;
checker.value = 2;
checker.defaultValue = 2;
return false;
}
function cacheReload()
{
if (cacheCheck()) location.reload(true);
}
and then call cacheReload when your page loads:
<body onload="cacheReload()">
Dldnh's answer inpired me to do some tests. I suspected that the body.onload() event would be called when going back and forth. So I created a simple testpage and found out that this is true in Firefox 10, IE7, IE 8, IE 9 and Chrome 17. Also jQuery(document).ready() will be called.
The very simple solution for hidind the throbber would therefore be either using
<body onload="hideThrobber()">
or using jQuery ready
jQuery(document).ready(function () {
hideThrobber();
};
to hide the throbber then. I implemented this and it seems to work fine on my page. Would be great if somebody with a similar problem could confirm this.
I also found this interesting Stackoverflow question. While it is a little outdated, the point that calling javascript on navigation back and forth slowing down the page is still true. But I would guess that todays JS-Engines are fast enough so this is not a real issue anymore.
If you can't turn off the throbber from the page you navigate to, there are a few things you can do. The trick is that the page will be left active, so you can start up some things before you leave, in the onclick. They aren't perfect though.
Start a timer. The timer will be running when you return to the page, so the timeout routine will be called, and you can switch the throbber off there.
Problem: if you set the timer interval too small, the timeout routine will be called before the user has actually left the page, and the throbber will stop. Or if you set the interval too large, it will take a while before the timeout routine kicks in after they have returned.
Add an event listener to the body that responds to the mousemove event, so that as soon as the user moves the mouse, the routine that turnes off the throbber will be called.
Problem: if the user clicks the browser's Back button, the mouse will be outside the window when the page is redisplayed, so the throbber will remain visible until the user moves the mouse into the window.
So, take your pick. Or do both. Just remember to clean up afterwards - stop the timer, remove the event listener.

Why are parameters not sent to a function in setInterval() all the time?

I have a page that automatically refreshes content via Ajax. I want this to be subtle so I do not want to display my loading gif during automatic page refreshed. So I did something like this with my getPosts function (unnecessary code cut out for succinctness)
function getPosts(image)
{
//loading icon while getPosts
if (image)
{
$("#postcontainer").bind("ajaxStart", function(){
$(this).html("<center><img src='ajax-loader.gif' /></center>");
});
} //... ajax call, etc. don't worry about syntax errors, they aren't in real code
I know the center tag is deprecated, just a shameless shortcut.
And then I will set the interval like setInterval(function() { getPosts(false); }, 10000);
Therefore my automated calls will not trigger the image to display
All my manual refreshes will then call it like this getPosts(true);
You can (probably) see the bug in action at my personal site
The problem is, the setInterval function seems to use the image bool from the latest function call. So it does not display the image at first during automated calls, but after I click a manual refresh, it starts showing the image during each call.
How can I combat this?
Thanks for anyone who views/posts this topic! I hope this question becomes a good reference to others.
The problem is that once you've bound your "ajaxStart" handler to the container it will execute on every ajax call for that container. That is, the first time you call it with getPosts(true) it will create the binding. The next time you call it with getPosts(false) it doesn't go down that if path but the binding still exists so when you do your ajax call the handler still executes - and the handler doesn't doesn't have any conditional logic. (Actually, I believe you'll end up with multiple bindings on the "ajaxStart" event, one created every time you call getPosts(true), but they're probably not noticable since they all just do the same thing overwriting the same html.)
Why not do something like this:
function getPosts(image) {
if (image) {
$("#postcontainer").html("<center><img src='ajax-loader.gif' /></center>");
}
// Actual ajax call here
}
setInterval(function() { getPosts(false); }, 10000);
Because after the first manual refresh you have attached a event handler "ajaxstart" which is to show the image when a ajax call starts. Now this event handler is there even in case you call the function with image = false. It will get triggered on all ajax calls.
What you need to do is something like:
$("#postcontainer").bind("ajaxStart", function(){
$(this).html("<center><img src='ajax-loader.gif' /></center>")
//Remove event handler
$(this).unbind("ajaxStart");
});

Categories