How to capture the Print Event? - javascript

Note :- Here Check = Cheque ( In USA cheque is spelled as check )
In a website, we've given the functionality to print the check to super-admin.
Super-admin can print the check by clicking on print button.
After clicking on the print button, it generates a popup to complete the action. Also, there are two events named as print and cancel(This is browser specific).
When super-admin clicks on the print event, then check comes out with all the details and all the orders belonging to the same check will get paid automatically in DB. When super-admin clicks on cancel, there is no action to be performed.
What we need to do :- We need to capture the event of print and cancel with 100% accuracy in all browsers, because here it's the matter of money (check).
So, I Need help on the way to get cancel and print events.

Why not just call the print() function from within an other function?
Like:
function myPrint() {
$("#myDiv").css({"border-color":"red"});
window.print();
}
Then you could call it from where you need it.

if you need to capture the print event you can use the beforeprint javascript event
Using addEventListener():
window.addEventListener('beforeprint', (event) => {
console.log('Before print');
});
Using the onbeforeprint event handler property:
window.onbeforeprint = (event) => {
console.log('Before print');
};
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeprint_event

Related

JavaScript event handling code get's called multiple times

I need your help. I'm currently working with a modal lib in JavaScript to display a modal for my customers:
https://github.com/vodkabears/Remodal/tree/1.1.1
Unfortunately my event handling in case the user clicks a button don't works like expected. When you take a look into the manual, you can see under the point Events the following event handler:
$(document).on('cancellation', '.remodal', function () {
console.log('Cancel button is clicked');
});
This one get's triggered for example when the cancel button get's pressed. Because I'm using one popup for multiple things, I need to attach the event handler to the call directly. So first I've wrote a function that opens the popup:
function openRemodal( remodalId ) {
let remodal = $( `[data-remodal-id=${remodalId}]` );
remodal.remodal().open();
return remodal; // <- added to handle events
}
I can call this function that way:
openRemodal( 'information-remodal' );
To get an event handling done, I've now returned the remodal in the function and re-wrote my call:
openRemodal( 'information-remodal' ).on( 'cancellation', function () {
alert( 'Test' );
} );
This seems to work but somehow when I repeat the opening of the popup and pressing the button, the alert get's shown multiple times increased by any new opening.
I'm not sure why this happens and why. Can you please help me get this working? I just want to call any function in there once - any time.
JQuery has a .one method ... try using that in place of .on. The callback should run only once. https://api.jquery.com/one/
On each time when you open model you attach function to cancelation event. so add new function and you never remove it. after first time you have one, then you have two... etc.
just attach it once, or remove it after handling event.
const modal = openRemodal( 'information-remodal' )
const handler = () => {
alert( 'Test' );
modal.off('cancellation', handler);
}
modal.on( 'cancellation', handler);

Is there any way to handle onClick Event on "Agree" or "Reject" button?

I am integrating DocuSign clickWrap on my website and It's working fine. I want to save some data when the user clicks on the Agree button. As the ClickWrap modal opens in Iframe and it is hard to get event from Iframe button, So is there any event or some Function which I can use to do this.
I have tried targetting the click event of the button inside the Iframe.
docuSignClick.Clickwrap.render({
environment: 'https://demo.docusign.net',
accountId: 'xx29fxxx-de70-xx9x-83xx-xxxxxxx43ddc',
clickwrapId: 'xxxxxx-03b2-4xxc-xxx1-cxxxxxxcbxx2c',
clientUserId: 'asdfsadfsdaf'
}, '#ds-terms-of-service');
Another way to do this is to listen to the callbacks on the render method:
docuSignClick.Clickwrap.render({
// ... env, acct, clickwrapId, etc.
onAgreed: function () {
// Triggered whenever the agreement is complete or has already been completed
},
onDeclined: function () {
}
}, '#ds-terms-of-service');
Here's how I did it. Add an event listener to the window of type 'message'. That event data contains a type field which has the information you are looking for.
window.addEventListener('message', (e) => {
if (e.data.type === 'HAS_AGREED') {
// do something after the click here.
}
})

JQuery "undo" an action by calling another function when back clicked

Is there a way to "undo" a function executed by jQuery when the back button is clicked? For example, my function that I want to execute is named doSomething:
function doSomething(button) {
...clicking the button does something...
}
And I have an undo function that undoes the above function, undoDoSomething:
function undoDoSomething(button) {
....undoes the doSomething function...
}
How do I call the function for the button and then if the back button is clicked right after I execute the function, I can call the undoDoSomething function to undo that function?
I know jQuery History goes back to a previous page saved in history but how do I use that to call a function?
the history api makes this easy: http://jsfiddle.net/Z9dRY/
html:
<button>Increase</button>click back button to decrease
<span id="counter">0</span>
js:
$("button").click(function(){
var count = +$("#counter").text() + 1;
history.pushState({count:count});
$(counter).text(count);
})
$(window).on("popstate",function(e){
if (e.originalEvent.state)
$(counter).text(e.originalEvent.state.count);
})
On each action, add to the history, and then each back button click will undo each change (of course, you have to develop the undo part. In this case, i just stored what the count should be changed to at that point and changed it.)
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Take note of the browser support, this code will work in all modern browsers and IE10+. oldIE will need a workaround either using an iframe or a hash in the url.
Here's the same example with an added decrease button to show that it doesn't really change anything: http://jsfiddle.net/Z9dRY/1/ it even inherantly supports the forward button(redo).
Update: fixed losing initial state: http://jsfiddle.net/Z9dRY/2/
You could call your undo function on the window.unload event
window.onbeforeunload = function(e) {
undoDoSomething();
};
You can usue beforeunload that is executed when leaving the page
var called = false;
function doSomething(button) {
called = true;
}
$(window).on('beforeunload',function(e){
if(called){
//call your function here
undoDoSomething()
}
});

Is there a way to capture the alert ok button click event?

Is there a way to capture the alert ok button click event? In jQuery?
The alert() function is synchronous and you can't verify what was clicked (it does not return anything), so the code below the call will be executed after it is closed (ok or close button). The alert is not used to gain user input. It is an alert, a message to the user. If you need to check what the user want, you should use confirm(). Note that the function name tells its purpose like alert.
Something like:
// if the ok button is clicked, result will be true (boolean)
var result = confirm( "Do you want to do this?" );
if ( result ) {
// the user clicked ok
} else {
// the user clicked cancel or closed the confirm dialog.
}
Alert is a blocking function, means, if you don't close it, the code below will not execute.
So you don't have to capture the alert close event, just write down the code below that alert, when alert window will be closed the code below will be executed automatically.
See example below:
alert("Close Me");
// Write down the code here, which will executed only after the alert close
console.log("This code is executed after alert")
Disclaimer: This is a very bad thing to do.
Technically you could hook into it with this code:
window.alert = function(al, $){
return function(msg) {
al(msg);
$(window).trigger("okbuttonclicked");
};
}(window.alert, window.jQuery);
$(window).on("okbuttonclicked", function() {
console.log("you clicked ok");
});
alert("something");
​
Demo: http://jsfiddle.net/W4d7J/1/
There is no event for the window.alert(). Basically the next line after it is called when they click ok. I am not sure why you would need to listen for it.
I tried this in a site I created and it worked perfectly :
<< Back
You could use JAlert and assign a click handler to the ok button.
Something like
jAlert("Alert message goes here.");
$('#popup_ok').bind('click',function(){
//Do operation after clicking ok button.
function_do_operation();
});

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories