Unable to prevent user from going back to previous Log In page - javascript

Currently the users see login page when they open the application. Upon signing in, they get into the main page. I want to prevent the user from going back to the login page once they are logged in which the user can easily do by just clicking on the back button on the phone or the web browser.
The following method does that by preventing me from going back or forth to the page I want. For example if I identify the id as #home, it is going to prevent me from going back to homepage. Problem is this works for all my pages in my application less the one page I actually want to enforce this on which is my login page. When I use the login page's id, nothing happens and I am able to go back to the login page by clicking the back button. Please advise what I am doing wrong.
JS
// triggers when leaving any page
//this doesn't work cos I am using the id of my loginpage. Other page's ids works.
$(document).on('pagebeforechange', function (e, data) {
var to = data.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#loginForm') { //will work if I use #benefits for example.
alert('Can not transition the page!');
$.mobile.changePage("#home", {
transition: "flip"
});
e.preventDefault();
e.stopPropagation();
// remove active status on a button, if transition was triggered with a button
$.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-shadow').css({
'box-shadow': '0 0 0 #3388CC'
});
}
}
});
HTML for LOG IN Page
<div data-role="page" id="loginForm" data-theme="e" data-add-back-btn="false">
<header data-role="header">
<h1>Log In</h1>
</header>
<form id="form1" name="form1" method="GET" action="http://example.com">
<label for="id">Username </label>
<input type="text" name="id" id="id" />
<label for="password">Password </label>
<input type="password" name="password" id="password" />
<input type="hidden" name="rank" id="rank" value="123">
<input type="submit" name="submit" value="Login"/>
</form>
</div>
HTML for Benefits Page
<div data-role="page" id="benefits" data-theme="e">
<header data-role="header">
<h1>Benefits</h1>
</header>
<article data-role="content" >
<div data-role="collapsible-set" id="benefitsList">
<!--will fill up with info from database-->
</div>
</article>
</div>
EDITED:
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = $.mobile.pageContainer.pagecontainer("getActivePage");
$.mobile.pageContainer.pagecontainer("change", current);
}
}
});

The problem that the code above works on all pages except for first page loaded, is because - by default - jQM doesn't change hash in URL for first page. The code above checks if there retrieves hash from URL, since there is no hash for first page, it returns false and thus doesn't prevent user from going back to "login page".
The code below checks URL and compares it with .url of first page loaded. The .url is stored in $.mobile.navigate.history.stack and it has 0 index, since it is first page.
jQuery Mobile 1.4
$(document).on('pagebeforechange', function (e, data) {
var to = $.mobile.path.parseUrl(data.toPage);
if (typeof to === 'object') {
var u = to.href;
if (u === $.mobile.navigate.history.stack[0].url) {
alert('You are logged in!');
var current = "#" + $.mobile.pageContainer.pagecontainer("getActivePage")[0].id;
window.location.hash += current;
return false; /* this will stop page change process */
}
}
});
jQuery Mobile <= 1.3
Change
$.mobile.navigate.history.stack[0].url
to
$.mobile.urlHistory.stack[0].url
Change
$.mobile.pageContainer.pagecontainer("getActivePage")[0].id
to
$.mobile.activePage[0].id
Demo - Code

Related

What could cause window.onload to fire infinitely?

I have a web page with a bunch of automatically generated contents (I can't touch the HTML). Usually, what happens is:
User selects something on the web page (ex. enter donation amount)
User clicks a button to enter personal information (as far as I know, the inputs are loaded after the button is clicked and takes around 1-2 seconds to load)
I'm trying to add some code to allow the user to enter some information before clicking the button, and the logic basically works like this:
the web page is loaded
place mydiv between some automatically generated contents
when user selects an option, put that information in local storage
when user clicks the button to generate personal informations, use setinterval to try to put the value in local storage in the corresponding field every 100ms, and call clearInterval when it succeeds (basically, it should work with 100ms of the personal information fields being loaded)
<style>
/* some styles */
</style>
<div id="mydiv">
<span style="font-weight:bold; margin-left: 12px;">
Please select an option
</span>
<div id="mydiv-options" style="margin-left: 14px;">
<input id="getinfo-mydiv" type="radio" name="mydiv-question" onclick="setstorage(0)">
</input>
<label for="getinfo-mydiv">
option1
</label>
<br>
<input id="future-mydiv" type="radio" name="mydiv-question" onclick="setstorage(1)">
</input>
<label for="future-mydiv">
option2
</label>
<br>
<input id="already-mydiv" type="radio" name="mydiv-question" onclick="setstorage(2)">
</input>
<label for="already-mydiv">
option3
</label>
<br>
<div id="clear-selection" onClick="clearSelection()">
Clear selection
</div>
</div>
</div>
<script>
// some functions
let repeatTryCheck = null
function setstorage(x) {
console.log("setstorage")
window.localStorage.setItem('selected', x)
}
function tryClickInput() {
console.log('tryClickInput')
let elementLoadedAfterUserClicksButton = document.getElementById("some-input")
if (elementLoadedAfterUserClicksButton == null) {
return
} else {
clearInterval(repeatTryCheck)
}
// do stuff with the value from storage
}
function tryClickUntilLoaded() {
console.log("tryClickUntilLoaded")
repeatTryCheck = setInterval(tryClickInput, 100) // 10x per second
}
function placeBeforeGeneratedDiv() {
console.log("placeBeforeGeneratedDiv")
let comments = document.getElementById("generateddiv")
comments.insertAdjacentElement('beforebegin', document.getElementById("mydiv"))
document.getElementById("mydiv").style.display = "block"
}
var i = 0;
function init() {
console.log("init")
placeBeforeGeneratedDiv() // place mydiv before generateddiv
document.getElementById('button-to-load-personal-info').addEventListener('click', tryClickUntilLoaded)
setstorage(null)
console.log(i)
i = i + 1
}
window.onload = init
</script>
The problem I keep getting is that the init function keeps getting called and I can't figure out what's causing it (I used this code on another page and it worked well)
Thanks

Get new content from ajax function and replace it on click

I have a single page with a div that gets new content when a user click on a radio button, when the page is loaded it display the main content, when user click on X radio button, that content gets "re-new" or "different" information, there is a DIV id that doesn't change... so...
When user loads the page, I check fro some values, is X value is lower than then replace the div content, on the first load it works fine, but if the user changes options then the first script wont do nothing... so here is the basic html
<div id="options">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="1" name="shipping" id="s1">
<input type="radio" onclick="javascript:checkOut(this.name,'shipr');" value="2" name="shipping" id="s2">
<input type="text" id="qty" class="hidden" value="1.2" style="display: none;">
</div>
<div id="information">
<div id="prices>$120.00</div>
<div id="products">Multiple[...] and tabs long list</div>
<div id="checkoutbtn">Buy Now</div>
</div>
Basically when user click on any of the radio buttons the content of the div "information" gets replace by ajax information, I'd like to know how do I get the new content and "replace" some values...
Now, the input with the ID qty that is hidden has the value I need is that value is less or grater than I replace the button inside the div with the id checkoutbtn from "buy now" to "Only inside US and UK, please Request a quote"... so, my JS is:
(function($) {
var pkg = $("#qty").val();
var cot = '<a rel="{handler: \'iframe\', size: {x: 570, y: 550}}" ' +
'class="modal" href="qut.php">' +
'<input type="button" value="Quotation" class="btn btn-small">' +
'</a>';
window.onload = function() {
if (pkg < 4 ) {
// do something
// alert('Checked');
$('#checkoutbtn').html(cot);
}
};
$('input:radio[name="shipping"]').change(
function(){
if ($(this).is(':checked') && $(this).attr("id") == 's1') {
// alert(pkg);
$('#checkoutbtn').html(cot);
} else if ($(this).is(':checked') && $(this).attr("id") == 's2') {
$('#checkoutbtn').html(cot);
}
});
})(jQuery);
When the page is load for the first time it works fine, and if it wasn't for the ajax that change the content of the div with the id information it would be flawless, but is not...
As you can see I have this piece of code: $('input:radio[name="shipping"]').change() ... so now I need something that would give some time to load the new content or to check when the new content is ready and then execute this other code $('#checkoutbtn').html(cot); ... the question is, how do I do that... if I put a timeout of 2 seconds it might work, but sometimes it takes 3 or 5 seconds for the new information to be ready and available to the user and that would be a problem...
So, I need to check when the new content is ready after the user has click on the radio button, how do I do that?
Thank you.

Passing data to forms via URL

I'm trying to create a very basic bookmarklet.
My form exists on page, for example mysite.com/posts/, within a bootstrap modal box.
<div class="post-window">
<div class="window-left">
<textarea name="title_image" class="form-control" rows="3" placeholder="Post title"></textarea>
<input name="postimage" class="form-control" placeholder="Post image URL" />
</div>
</div>
<div class="modal-bottom">
<div class="upload">
<input type="hidden" name="letsbingo" value="1" />
<button class="btn-block">Post Selfie</button>
</div>
</div>
1- Following is bookmarklet code and it works fine.
javascript: var selfiesite = 'SelfieNow',
selfiesiteurl = 'http://my.com/post/';
(function () {
if (window.selfiesiteit !== undefined) {
selfiesiteit();
} else {
document.body.appendChild(document.createElement('script')).src = 'http://my.com/assets/js/postit.js';
}
})();
2- The result of above javascript is exactly what I want as shown below
http://my.com/post/?postimage=%3A%2F%2Fexample.com%2Fwp-content%2Fuploads%2F2013%2F12%2FGripster-Wrap-Mini-For-The-Ipad-Mini-3-690x460.jpg&title_image=Example%20-%20Men%27s%20Gear%2C%20Lifestyle%20and%20Trends
3- Now my my.com/post/ contians a piece of javascripts which triggers modal box on window load.
jQuery(window).load(function ($) {
jQuery('#postModal').modal('show');
});
The bookmarklet is working, modal box is opening on window load. But data in not passing to form. The form opens in modal box, url changed but the form appears empty. I don't know what is wrong. Either the modal box is opening (on window load) the wrong way or the bookmarklet created url isn't fit for this kind of form. Please guide me a little bit.
Try to bind your JS function when the modal is show. Like this:
$('#postModal').on('show', function () {
var selfiesite = 'SelfieNow',
selfiesiteurl = 'http://my.com/post/';
if (window.selfiesiteit !== undefined) {
selfiesiteit();
} else {
document.body.appendChild(document.createElement('script')).src = 'http://my.com/assets/js/postit.js';
}
});

Why when i scroll top my page and click link which append a form it scroll me down

i have a page that show activity feeds with a comment link for each feed, i add a comment form dynamically like this :
$("#feedList").on("click", ".comment-link", function(e){
$(this).parent().append('<form method="post" action="#" class="commentForm"><p><textarea class="comment"></textarea></p><p><input type="submit" value="add" class="send-Comment-Btn" /></p></form>');
$("textarea.comment").select();
return false;
});
when i scroll down my page and i click in some comment link it shows me the form as expected, but if i scroll to the top of the page again and i try to click a comment link it shows the form too but it scroll me to the bottom page to the last link i have clicked before, someone can tell me why this behavior and solution for this ?
$("textarea.comment").select();
will always move you to first created textarea element with class "comment". Maybe you must add some ID that increments every click like:
var someID = 0;
$("#feedList").on("click", ".comment-link", function(e){
someID += 1;
$(this).parent().append('<form method="post" action="#" class="commentForm"><p><textarea class="comment" id="selectorForComment' + someID + '"></textarea></p><p><input type="submit" value="add" class="send-Comment-Btn" /></p></form>');
$("#selectorForComment" + someID).select();
return false;
});

How to focus next field if user clicked on the link?

I have a number of fields with labels-links like below:
<div class="control-group">
<label class="control-label" for="some-id-1">Text1</label>
<div class="controls">
<input type="text" id="some-id-1" name="some-id-1"><br>
</div>
</div>
<div class="control-group">
<label class="control-label" for="some-id-2">Text2</label>
<div class="controls">
<input type="text" id="some-id-2" name="some-id-2"><br>
</div>
</div>
If user clicks on the link, how can I focus according field (without preventing default action)? I.e. if user clicks on Text1, then I should open http://example.com/some-id-1 in new window and set focus at input with id some-id-1.
jsfiddle
$(".control-label a").click(function(){
$(this).parent().next().find('input').focus();
});
$('.control-label a').on('click', function(e) {
e.preventDefault();
$(this).parent().next().find('input').focus();
// or
$('.control-group').has(this).find('input').focus();
});
Text1
If understanding correctly you want to open a new page and in the new page set focus based on link that was clicked
If you are opening a new page you will need to pass a hash in url or use a cookie and have other page parse the hash or cookie
In current page:
$(function(){
$('.control-label a').click(function(){
var hash='#'+ $(this).next().find('input').attr('id');
window.open( this.href + hash);
return false;
});
})
In other page:
$(function(){
var hash= location.hash;
$(hash).focus();
})
JavaScript in one page can't control how another page responds to a URL, if the 'other' page is under your control then you could set it up to parse the id:
var parts = document.location.href.split('/'),
id = parts.pop();
document.getElementById(id).focus;
On the other hand, if you want to focus that element reliably, just pass an id, as a hash, to the URL:
Go to an element of 'some id'
This may not focus the form element, but it should draw that element to the attention of the user and, in pages outside of your control, is much more reliable.

Categories

Resources