I'm trying to run a function each time user changes 'page'in jQuery Mobile.
$(document).ready(function(){}
Doesn't work because all the pages are contained in the same .html.
The only way i can get it to work is if i listen on the nav buttons like this
$('#navNext').click(function() {
retrieveSession();
});
This causes a whole lot of head aches so i tried this
function retrieveSession(){
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
$( "#" + activePageId ).on( "pagechange", function() {
if (activePageId === "q1"){
alert("q1");
} else if (activePageId === "q2"){
alert("q2");
} else if (activePageId === "q3"){
alert("q3");
} else if (activePageId === "q4"){
alert("q4");
};
});
}
Then i run the function in $(document).ready(function(){}, the app still runs fine, but no alert when navigating through the 'pages'.
No exceptions either.
I have searched on here and can only find vague connections through other questions that don't help me with a solution.
What am i doing wrong here?
Related
So I have a website where I can select links and click a button to open them all at the same time. When I do that Firefox takes me to one of the newly opened links automatically.
I wanted to stop this behavior, so I looked and looked, and eventually found this option:
browser.tabs.loadDivertedInBackground
Now, when I set this to true, newly opened tabs never automatically take me to them. So if I click an ad on a site that normally opens in a new tab and takes me to it, now it doesn't happen. I also tried this code:
<p><a href="#" onclick="window.open('http://google.com');
window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
This code opens 2 links at the same time. I was thinking maybe opening multiple links at the same time somehow overrides Firefox. But no, the links opened and I was not automatically taken to any of the new tabs.
Also must be said that I'm having this problem in Firefox 75 and 74. But when I try it in Firefox 55.0.2, I don't have the problem. In Firefox 55.0.2 the "browser.tabs.loadDivertedInBackground" actually works even on the website where I have the problem (I can't share the site because it's behind login).
This appears to be the code responsible to open multiple links on the website I have an issue with:
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
var win = window.open(t.data('link'), '_blank');
if (win) {
win.focus();
} else {
bootbox.alert('Please allow popups for this website');
}
}
});
So I tried everything I could think of. Many changes to the about:config, restarting my browser, unticking the "When you open a link in a new tab, switch to it immediately" option in Firefox. But nothing works. When I open links from this one site using this specific button, I always get automatically taken to one of the newly opened tabs.
Here is a similar-ish problem - https://www.reddit.com/r/firefox/comments/bnu6qq/opening_new_tab_problem/
Any ideas why this happens and how to fix it? I mean, a website shouldn't be able or allowed to override Firefoxe's native setting, right?
Okay, because I don't wanna be an ass, here is the solution.
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get().reverse()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
// var win = window.open(t.data('link'), '_blank');
setTimeout(() => window.open(t.data('link'), '_blank'),1000);
// if (win) {
// win.focus();
// } else {
// bootbox.alert('Please allow popups for this website');
// }
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
Basically, adding a "setTimeout" fixed it. For some reason Firefox needed the delay to process things correctly, I guess, I think. Before the delay, the actions would happen instantly, and I'll just guess that Firefox couldn't "catch up" to it in order to apply the exemption of not navigating to new tabs. But a timeout delay fixed it.
And for anyone that may run into this with a similar issue, it also required an edit in Firefox in "about:config" to set this to True.
browser.tabs.loadDivertedInBackground
That's all folks :)
Hi I have written some javascript code to generate an iFrame and insert content inside. But I don't want to use setTimeout and I want to refactor the code. I tried to use document.ready() and window.onLoad() and they don't work.
This is my code:
onShow: function() {
//TODO: why 200 ms wait? why not wait for specific event
setTimeout(this.injectHtml.bind(this), 200);
},
injectHtml: function() {
var iframe = this.el;
if (iframe.contentWindow === null) { //Check for contentWindow for null.
$(iframe).html(this.params.html);
} else { //If contentWindow is present then open the document for writing.
iframe = iframe.contentWindow;
iframe.document.open('text/html');
iframe.document.write(this.params.html);
iframe.document.close();
$(this.el).on('load', function() {
var iframe = $(this).contents();
iframe.find("#langSelect").off("change");
iframe.find("#langSelect").on("change", function() { //If another language is selected from Dropdown.
abc.languages.setSelected($(this).val());
abc.elements.setLanguage();
Vent.trigger(Vent.Event.LANGUAGE_SELECTED, $(this).val());
});
});
}
}
I'm really confused here. Can anyone shed light?
I have tried this as well:
Case#1:
var _this=this;
$(document).ready(function(){
_this.injectHtml.bind(_this); //Does not work. Everything loads, I get empty page
});
Case#2:
window.onLoad = function(){
this.injectHtml.bind(this);
};
can anyone help?
I am using native.history.js to put a customised URL in the back button.
The script works fine. Now the issue is I want to make a page redirect when the refresh button is clicked; so i modified the script like this:
<script>
var back = 0;
$(window).bind('beforeunload', function () {
if (confirm('Want to continue?')) {
if (back == 1) {
alert('back');
//window.location.href = "<?=$$last_offer?>";
} else {
alert('refresh');
//window.location.href = "<?=$actual_link;?>";
}
} else {
// Do nothing!
}
});
window.onpageshow = function (e) {
if (e.persisted) {
location.reload();
}
};
window.onpopstate = function (event) {
if (document.location.toString().indexOf("redir=1") > 0) {
back = 1;
window.location.href = "<?=$$last_offer?>";
}
};
</script>
Issue is, the beforeunload function seems not working.
What is the problem I can't fin?.
If I am clicking the back button, the page is taking to the desired page, so it works fine.
All I want is that, somehow the page refresh must work as I anticipated.
Try use
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Instead of bind, use on, i dont know what jquery version you use, but i will suggest "on".
Works fine here:
link
on jquery version 2.x(edge)
Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?
We need to cater all browser that doesn't support HTML5
The 'popstate' event only works when you push something before. So you have to do something like this:
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './#forward');
$(window).on('popstate', function() {
alert('Back button was pressed.');
});
}
});
For browser backward compatibility I recommend: history.js
In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2) {
//Do your code here
}
there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.
Detect if user pressed "Back" button on current page:
Is there a way using Jquery to detect the back button being pressed cross browsers
detect back button click in browser
Detect if current page is visited after pressing "Back" button on previous("Forward") page:
Is there a cross-browser onload event when clicking the back button?
trigger event on browser back button click
Found this to work well cross browser and mobile back_button_override.js .
(Added a timer for safari 5.0)
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'your url';}
};
}
}
setTimeout(function(){count = 1;},200);
In case of HTML5 this will do the trick
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .
Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.
In summary - there is the variable globalCurrentHash that should be set each time you load a view.
Then when $(window).on('hashchange', ..) event listener runs, it checks the following:
If location.hash has the same value, it means Going Forward
If location.hash has different value, it means Going Back
I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated
Set Up:
Define a global var :
var globalCurrentHash = null;
When calling .load() to update the DIV, update the global var as well :
function loadMenuSelection(hrefVal) {
$('#layout_main').load(nextView);
globalCurrentHash = hrefVal;
}
On page ready, set up the listener to check the global var to see if Back Button is being pressed:
$(document).ready(function(){
$(window).on('hashchange', function(){
console.log( 'location.hash: ' + location.hash );
console.log( 'globalCurrentHash: ' + globalCurrentHash );
if (location.hash == globalCurrentHash) {
console.log( 'Going fwd' );
}
else {
console.log( 'Going Back' );
loadMenuSelection(location.hash);
}
});
});
It's available in the HTML5 History API. The event is called 'popstate'
Disable the url button by following function
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type
if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
// back or forward button functionality
}
This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd -
p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd -
p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.
suppose you have a button:
<button onclick="backBtn();">Back...</button>
Here the code of the backBtn method:
function backBtn(){
parent.history.back();
return false;
}
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.