Forum Moderators: open
Basically, Opera treats a JavaScript call as an asynchronous call, while other browsers don't. I'd like to know if there is a way to either force the call to be synchronous, or a better way to work around it than the rather kludgy fashion demonstrated here.
---
A friend of mine asked me to post this question on this forum, and see what suggestions come about. This sort of dovetails into an earlier discussion I remember about JavaScript knowing when a page is being rendered for printing (We figured out that there was no way to do this).
He figured a way to work around it, but it seems quite a hack.
Here goes:
The CSS:
<style type="text/css">
div#div1 {
border: 2px solid red;
}
div#div2 {
border: 2px solid green;
}
</style>
The JavaScript:
<script type="text/javascript">
function print_test() {
document.getElementById('div1').style.display = 'none';
window.print();
document.getElementById('div1').style.display = '';
return false;
}
</script>
The XHTML:
<div id="div1">This <div> shouldn't print.</div>
<br />
<br />
<div id="div2">This <div> should print.</div>
<br />
<br />
<a href="#" onclick="return print_test()">Print via Javascript</a>
The problem is that, in Opera, the line immediately after the window.print(); line is executed immediately, so the hidden <div></div> is shown in the printout.
Basically, Opera treats window.print(); as an asynchronous operation, while other browsers don't.
His kludgy fix is thus:
<script type="text/javascript">
function print_test() {
document.getElementById('div1').style.display = 'none';
window.print();
if (window.opera){
setTimeout("document.getElementById('div1').style.display = ''", 1);
}
else {
document.getElementById('div1').style.display = '';
}
return false;
}
</script>
Any ideas?
I'm no javascript guru, but I have done some research about this issue. Does this page from dev.opera.com offer any help? In particular, this quote caught my eye:
Nested EventsThere is a special case where events are not sequenced, but nested. If an event is fired explicitly through script using the dispatchEvent()-method (fireEvent() in Internet Explorer), the event is dispatched immediately. The initial script will only continue when the dispatched event has finished (and the default action has executed).
[dev.opera.com...]