Make jQuery prevent going back on android - javascript

I have a simple pop-up contact form script written:
$(document).ready(function(){
var popupButton = $("#contact-popup-button");
var popupBox = $("#pop-up-contact");
var popupBg = $("#pop-up-close-background");
popupButton.on("click", function(){
popupBox.addClass("slide-out");
popupBg.fadeIn(200);
});
popupBg.on("click", function(){
popupBox.removeClass("slide-out");
popupBg.fadeOut(100);
});
Basically when a button is clicked, a div appears and the space behind it gets foggy. If you press the space around the appeared div, it will dissapear.
Now for mobile devices, I'd like there also to be an option to make the div dissapear on clicking the back button. Unfortunately, I can not get it to work in practice at all.
I have tried these answers:
handling back button in android from jquery
Take control of hardware back button jquery mobile
But both seem to fail in this task, and the others use plugins, which I'd like to avoid.
Tested on LG G2 Mini and Sony Xperia Z1

One approach would be to use the HTML5 History API.
When opening the popup you can push a state to the history stack before opening the popup:
history.pushState({popupOpen: false}, "My title", "index.html");
This method automatically updates the page title (which is currently ignored in most browser implementations) and the last part of the url, that will be displayed in the browser bar. In most cases, you can enter your filename here. The first argument is an object containing the data you can access later when popping a state.
As soon as you have pushed a state to the history stack, when pressing the back key, the browser does not return to the last page as usual, but pops the last state on the stack. This applies for all browsers though, if you want the functionality for mobile browsers only, you have to do a browser check before calling history.pushState.
To correctly handle the back event, you need to subscribe to the popstate-Event. This can be done with the following code:
window.addEventListener("popstate", function(event) {
var data = event.state;
if(data.popupOpen === false) {
popupBg.trigger('click');
}
});
You register an event listener that fires as soon as the user navigates back. In the event.state variable the data you passed in when pushing the state can be accessed again.
Good luck!

Related

Tab order on prompt page

Using Cognos Analtyics 11.1.7IF9.
I have a user who, oddly enough, wants Cognos to make his workflow more efficient. (The nerve!) He thinks that if he can use the TAB button to navigate a prompt page, he'll be faster because he never needs to reach for the mouse.
To test this I created a simple report with a very simple prompt page using only textbox prompts. As I tab I notice it tabs to everything in the browser: browser tabs, the address bar, other objects in Cognos, ...even the labels (text items) I created for the prompts. Oh... and yes, at some point focus lands on a prompt control.
Within Cognos, I see that the tab order generally appears to be from the top down. (I haven't tried multiple columns of prompts in a table yet.) I must tab through the visual elements between the prompts. Also, while value prompts get focus, there is no visible indication of this.
Is there a way to set the tab order for the prompts on a prompt page?
Can I force it to skip the non-prompt elements?
Can the prompts be made to indicate that they have focus?
I tagged this question with javascript because I figure the answer will likely involve a Custom Control or a Page Module.
Of course, then I'll need to figure out how all this will work with cascading prompts and conditional blocks.
I found a similar post complaining about this being a problem in Cognos 8. The answer contains no detail. It just says to go to a non-existent web page.
I had the same frustration as your user and I made a solution a while back that could work for you. It's not the most elegant javascript and I get a weird error in the console but functionally it works so I haven't needed to fix it.
I created a custom control script that does 2 things on a prompt page.
First, it removes the ability to "select" text item elements on the page. If you only have text items and prompts on the page it sets it's "Tabindex" to "-1". This allows you to tab from one prompt field to the next without it selecting invisible elements or text elements between prompts.
Secondly, if you press "Enter" on the keyboard it automatically submits the form. I am pasting the code below which you can save as a .js and call it in a custom control on a prompt page. Set the UI Type to "None"
define( function() {
"use strict";
function AdvancedControl()
{
};
AdvancedControl.prototype.initialize = function( oControlHost, fnDoneInitializing )
{
function enterSubmit (e)
{
if(e.keyCode === 13)
{
try {oControlHost.finish();} catch {}
}
};
function setTab () {
let nL = [...document.querySelectorAll("[specname=textItem]")]
//console.log(nL)
nL.forEach((node) =>{
node.setAttribute('tabindex','-1')
})
};
setTab();
let exec_submit = document.addEventListener("keydown", enterSubmit, false);
try {exec_submit;} catch {}
fnDoneInitializing();
};
return AdvancedControl;
});

How to disable browser feature

I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload.
Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost.
I have used this:
window.onbeforeunload = function()
{
return "Try This";
};
But this get called even when I click a button that redirects the page.
If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. E.g.:
var warnWhenLeaving = true;
window.onbeforeunload = function() {
if (warnWhenLeaving) {
return "your message here";
}
};
then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:
warnWhenLeaving = false;
In a comment you asked:
can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)
The answer is: Sort of, but not really; you're almost certainly better off not trying to.
But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert: All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout, you won't get the callback if they leave and you will if they stay:
window.onbeforeunload = function() {
if (warnWhenLeaving) {
setTimeout(function() {
display("You stayed, yay!");
}, 0);
return "No, don't go!";
}
};
Live Example
So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)
I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.

Lightswitch 2013: Save then Refresh in JS

I have the 2 sets of code:
Saves the data
myapp.activeDataWorkspace.ProjectHandlerData.saveChanges();
2.Refreshes the page
window.location.reload();
is there a way to make both of these work together on one button, as currently when i click save, the browser recognizes the changes and the (are you sure you want to leave the page) message or something along those lines pops up..
cheers
This is for the HTML client, right?
Assuming that is the case:
saveChanges() is an asynchronous operation, so you'd want to do:
myapp.activeDataWorkspace.ProjectHandlerData.saveChanges().then(function () {
window.location.reload();
});
That way it will wait until it is finished saving the changes before it reloads the screen.
However, there is a smoother way to do it, at least from the user perspective it's smoother.
On the edit screen, leave the Save method out, let LightSwitch handle that. When the user clicks save, it will close the edit screen, and go back to where they were before. Using the options parameter of the showScreen method, we can change that behavior.
Change the method that calls the edit screen like this:
myapp.showEditProject(screen.Project, {
afterClosed: function (editScreen) {
myapp.showViewProject(editScreen.Project);
}
});
This way, after the edit screen is closed, and it has handled the save changes operation for you, the application will automatically navigate to the details view screen of the recently edited item.
If you are instead wanting to refresh the browse screen after adding a new entity:
myapp.showAddEditProject(null, {
beforeShown: function (addEditScreen) {
addEditScreen.Project = new myapp.Project();
},
afterClosed: function () {
screen.Projects.load();
}
});
Those two options, beforeShown and afterClosed, give you a lot of really cool abilities to influence the navigation in your application.
I have learnt that you can save from a add/edit window, and reload the main page you are going back to by doing the following:
For Example: (adding an order to an order screen)
click on your button to add the order
enter the details required.
hit your custom save button with your validation included.
before your commitChanges(); write in the following line: screen.OrderLine.OrderTable.details.refresh(); "This needs applying to your scenario"
when you return to your screen your details should have been updated (for example the total value now displays the correct value in my case)
hope this helps...

RadScheduler update interval

I'm using RadScheduler for my project. In the scheduler, I need a periodical update, so in my javascript, I set interval for a method that call rebind() on the RadScheduler for every 60 seconds. The problem is that, when my user open the advanced form, the rebind() method makes the form disappear. How can I detect AdvancedForm opening and closing event so that I can stop /restart the timer ?
Thank you in advance.
While there is an event for when the RadScheduler opens its Edit form, called OnClientFormCreated, there is not one for when the edit form closes. There are ways to do this though, but you have do add some additional code.
When you think about it there are several different items that can lead to the form closing - the user can click on the close icon at the top right (or left, depending on your orientation) of the window, they can click cancel, or they can hit save.
Keeping that in mind, we can take a look at this demo, which shows the Advanced Edit Form in action, and also has some JavaScript pre-written for us.
Within the schedulerFormCreated() function we can do the following:
function schedulerFormCreated(scheduler, eventArgs) {
// Create a client-side object only for the advanced templates
var mode = eventArgs.get_mode();
if (mode == Telerik.Web.UI.SchedulerFormMode.AdvancedInsert ||
mode == Telerik.Web.UI.SchedulerFormMode.AdvancedEdit) {
// Initialize the client-side object for the advanced form
var formElement = eventArgs.get_formElement();
var cancelButton = $("[id$='_CancelButton']");
cancelButton.on("click", formClosed);
var templateKey = scheduler.get_id() + "_" + mode;
....
And then we have the formClosed event:
function formClosed(eventArgs) {
}
in formClosed you can just create your logic for resuming the timer, while in schedulerFormCreated you can directly call the function that stops the timer right after that if-statement.
In case you're wondering what we're doing here we're simply grabbing an instance of the jQuery object representing the element with an id that ends with _CancelButton (we're not interested in the beginning part) and then just binding to the click event using the .on() jQuery function.
To get an instance of the save button you just have to use _UpdateButton, and for the close icon it is _AdvancedEditCloseButton. Keep in mind that any element that ends with these substrings will be selected, so if you want to be more specific I recommend inspecting the elements of your advanced form using FireBug or the Chrome Dev tools to get their ID and plug that into the selector above.
This should allow you to get the functionality you're looking for.

Alerts when navigating away from a web page

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).
Are you sure you want to navigate away
from this page?
You have unsaved changes in this
document. Click Cancel now, then
'Save' to save them. Click OK now to
discard them.
Press OK to continue, or Cancel to
stay on the current page.
My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?
By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.
window.onbeforeunload = function(){ return 'Testing...' }
// OR
var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);
Will yield a dialog that says
Are you sure you want to navigate away from this page?
Testing...
Press OK to continue, or Cancel to stay on the current page.
You can nullify this by setting the handler to null
window.onbeforeunload = null;
// OR
window.removeEventListener('beforeunload', unloadListener);
The alerts are part of the web application. View the source code and look at the javascript.

Categories