I have a list of items in a listview. Clicking on one li sends a JSON request and opens a description page.
Since the opening of the description page takes 1 or 2 seconds there is time to click on another item in the list which then triggers more events, which I don't want. This eventually makes the scrolling (with iscrollview) messy with the bottom bar going up and down when going back to the list.
How can I stop listening to more taps on the listview while processing the opening of the description page?
Without any to look at, it's very difficult for us to help you.
However, the simplest method of avoiding this is to use a global variable as a flag.
You would set the global variable (ie: in the root-level of your JavaSCript file), as false:
tapProcessing = false;
Then, whenever you start processing you, check against this flag and - if not true, then process.
Here's a rudimentary example to show you what I mean:
$('.selector').click(function(e){
if(!tapProcessing){
//the function is not processing, therefore set the flag to true:
tapProcessing = true;
//do your load/etc, and reset the flag to false in the callback (when finished):
$.get("test.php", function(data) {
// process your data here
// set your flag back to false:
tapProcessing = false;
});
}else{
//the function is already being processed from a previous click
}
e.preventDefault(); //assuming it's a link
});
Here are the bits of code I added :
el is my list, event is the landing page
setting tapProcessing to false should only be done when "after the changePage() request has finished loading the page into the DOM and all page transition animations have completed" (JQM doc : http://jquerymobile.com/demos/1.2.0/docs/api/events.html )
$('#el').click(function(e){
if(tapProcessing) {
alert('prevent');
e.preventDefault(); //assuming it's a link
} else {
alert('oktap');
tapProcessing = true;
}
});
$(document).bind("pagechange", function(event, options) {
if(options['toPage']['selector'] == '#event') {
tapProcessing = false;
}
});
I also set tapProcessing to false if I receive a disconnect event or on timeout.
Related
I would like to create a custom event that tests if any registered handler return false, and cancel an action if any one does.
I have two types of object, (one or more) Page(s) and (one) Navigator.
Navigator registeres user attempts on leaving the page, but it has no knowledge about what is on the page or pages. The Page object knows the content of the page, but have no knowledge about when the user try to leave the page.
I want the Navigator to emmit a beforepageleave event that all Page objects could listen for, and if the beforepageleave handler in all Pages returns true Navigator should continue its business, but if any Page handler returns false, it should just cancel the navigation and stay on the page.
Page has a hasChanges attribute that should stop Navigator if it is true.
So the handler in Page could in a simplified form look something like:
navigator.on('beforepageleave', function (e) { return !this.hasChanges; });
The navigator method could simplified look something like this:
leavePageLinks.click(function (e) {
let proceed = true;
$.each(registeredEventHandlers, function (index, handler) {
if (!handler(e)) {
proceed = false;
}
}
return proceed;
});
I have seen that jQuery saves eventhandlers in (jQuery._data || jQuery.data)(elem, 'events'), but I would prefer to use non private methods and not rely on code that might change completely without my knowledge. Also, I'm not sure I should override the handling like this at all?
Using the HTML5 window.history API, I can control the navigation pretty well on my web app.
The app currently has two states: selectDate (1) and enterDetails (2).
When the app loads, I replaceState and set a popState listener:
history.replaceState({stage:"selectDate",...},...);
window.onpopstate = function(event) {
that.toStage(event.state.stage);
};
When a date is selected and the app moves to stage 2 I push state 2 onto the stack:
history.pushState({stage:"enterDetails",...},...);
This state is replaced anytime details change so they are saved in the history.
There are three ways to leave stage 2:
save (AJAX submit)
cancel
back button
The back button is handled by the popstate listener. The cancel button pushes stage 1 so that the user can go back to the details they were entering the back button. These both work well.
The save button should revert back to stage 1 and not allow the user to navigate back to the details page (since they already submitted). Basical, y it should make the history stack be length = 1.
But there doesn't seem to be a history.delete(), or history.merge(). The best I can do is a history.replaceState(stage1) which leaves the history stack as: ["selectDate","selectDate"].
How do I get rid of one layer?
Edit:
Thought of something else, but it doesn't work either.
history.back(); //moves history to the correct position
location.href = "#foo"; // successfully removes ability to go 'forward',
// but also adds another layer to the history stack
This leaves the history stack as ["selectDate","selectDate#foo"].
So, as an alternative, is there a way to remove the 'forward' history without pushing a new state?
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
popstate event can happen when user goes back ~2-3 states to the past
popstate event can happen when user goes forward
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
A simple solution:
var ismobilescreen = $(window).width() < 480;
var backhistory_pushed = false;
$('.editbtn').click( function()
{
// push to browser history, so back button will close the editor
// and not navigate away from site
if (ismobilescreen && !backhistory_pushed)
{
window.history.pushState('forward', null, window.location);
backhistory_pushed = true;
}
}
Then:
if (window.history && window.history.pushState)
{
$(window).on('popstate', function()
{
if (ismobilescreen && backhistory_pushed && $('.editor').is(':visible'))
{
// hide editor window (we initiate a click on the cancel button)
$('.editor:visible .cancelbtn').click();
backhistory_pushed = false;
}
});
}
Results in:
User opens editor DIV, the history state is saved.
User hits back button, history state is taken into account.
Users stays on page!
Instead of navigating back, the editor DIV is closed.
One issue: If you use a "Cancel" button on your DIV and this hides the editor, then the user has to click the mobile's back button two times to go back to the previous URL.
To solve this problem you can call window.history.back(); to remove the history entry by yourself which actually deletes the state as requested.
For example:
$('.btn-cancel').click( function()
{
if (ismobilescreen && backhistory_pushed)
{
window.history.back();
}
}
Alternatively you could push a URL into the history that holds an anchor, e.g. #editor and then push to history or not if the anchor exists in the recent URL or not.
I’ve made a one page site. When user clicks on the menu buttons, content is loaded with ajax.
It works fine.
In order to improve SEO and to allow user to copy / past URL of different content, i use
function show_content() {
// change URL in browser bar)
window.history.pushState("", "Content", "/content.php");
// ajax
$content.load("ajax/content.php?id="+id);
}
It works fine. URL changes and the browser doesn’t reload the page
However, when user clicks on back button in browser, the url changes and the content have to be loaded.
I've done this and it works :
window.onpopstate = function(event) {
if (document.location.pathname == '/4-content.php') {
show_content_1();
}
else if (document.location.pathname == '/1-content.php') {
show_content_2();
}
else if (document.location.pathname == '/6-content.php') {
show_content_();
}
};
Do you know if there is a way to improve this code ?
What I did was passing an object literal to pushState() on page load. This way you can always go back to your first created pushState. In my case I had to push twice before I could go back. Pushing a state on page load helped me out.
HTML5 allows you to use data-attributes so for your triggers you can use those to bind HTML data.
I use a try catch because I didn't had time to find a polyfill for older browsers. You might want to check Modernizr if this is needed in your case.
PAGELOAD
try {
window.history.pushState({
url: '',
id: this.content.data("id"), // html data-id
label: this.content.data("label") // html data-label
}, "just content or your label variable", window.location.href);
} catch (e) {
console.log(e);
}
EVENT HANDLERS
An object filled with default information
var obj = {
url: settings.assetsPath, // this came from php
lang: settings.language, // this came from php
historyData: {}
};
Bind the history.pushState() trigger. In my case a delegate since I have dynamic elements on the page.
// click a trigger -> push state
this.root.on("click", ".cssSelector", function (ev) {
var path = [],
urlChunk = document.location.pathname; // to follow your example
// some data-attributes you need? like id or label
// override obj.historyData
obj.historyData.id = $(ev.currentTarget).data("id");
// create a relative path for security reasons
path.push("..", obj.lang, label, urlChunk);
path = path.join("/");
// attempt to push a state
try {
window.history.pushState(obj.historyData, label, path);
this.back.fadeIn();
this.showContent(obj.historyData.id);
} catch (e) {
console.log(e);
}
});
Bind the history.back() event to a custom button, link or something.
I used .preventDefault() since my button is a link.
// click back arrow -> history
this.back.on("click", function (ev) {
ev.preventDefault();
window.history.back();
});
When history pops back -> check for a pushed state unless it was the first attempt
$(window).on("popstate", function (ev) {
var originalState = ev.originalEvent.state || obj.historyData;
if (!originalState) {
// no history, hide the back button or something
this.back.fadeOut();
return;
} else {
// do something
this.showContent(obj.historyData.id);
}
});
Using object literals as a parameter is handy to pass your id's. Then you can use one function showContent(id).
Wherever I've used this it's nothing more than a jQuery object/function, stored inside an IIFE.
Please note I put these scripts together from my implementation combined with some ideas from your initial request. So hopefully this gives you some new ideas ;)
Is there a way to provide a hook such as onHistoryBack? I'm currently using history.js with
History.Adapter.bind (window, 'statechange', function () {});
But I have no way to ask if user presed history.back() or if it's result of a History.pushState() call.. any idea?
The way I did this was to set a variable set to true on each click on the actual site. The statechange event would then check this variable. If it was true, they had used a link on the site. If it was false, they had clicked the browsers back button.
For example:
var clicked = false;
$(document).on('click','a',function(){
clicked = true;
// Do something
});
History.Adapter.bind (window, 'statechange', function () {
if( clicked ){
// Normal link
}else{
// Back button
}
clicked = false;
});
Hope that helps :)
All of the states are stored in History.savedStates. Each time back is pushed another state is added. So in theory you could test History.savedStates to see if History.savedStates[History.savedStates.length - 2] == currentState. That would indicate the user went from step a, to step b, back to step a. However the user could get there other ways than the back button - so you may need to use this in combination with user events.
You can also use the History.getStateByIndex method to return a saved state.
I'm using jquery and what I'm doing is binding the toggle method to a number of buttons on a webpage. It looks something like this
$('.button').toggle(function(){
// first function
}, function(){
// second function
});
However, there are animation in both of those functions. So a user can click the button while the first or second function is executing. And this messes up the order of the HTML elements and may make them move to the end of the page. Because essentially what these functions do is move one element to the end on the first click, and on the other click move it back where it originally was.
Of course, it is difficult to click the button once it is moving around the page. But it's possible.
You could use a flag. Set a flag 'isAnimating' to true when an animation begins, and false when it ends. Any subsequent animation can only proceed if this value is false.
You could also possibly check to see if the :animated selector applies to the owner of the event. And base your decisions off of that.
You could use a bool as a semiphore.. Obviously, this is in no way secure, but javascript doesn't really support locking, so you could easily have deadlocks and / or race conditions with this approach, but it will work 99,9% of the times :)
Seems like you'll be happier implementing your own toggle. Toggle really only works for cases with 0 additional logic.
$('.button').click(
function () {
if( $(self).is(":animated") {
return false;
}
if($(self).is(".rolledup")) {
self.apply(roll_window_down);
} else {
self.apply(roll_window_up);
}
});
function roll_window_up() {
$(self).addClass( 'rolledup' );
// first function
}
function roll_window_down() {
$(self).removeClass( 'rolledup' );
// first function
}
You need to place the two functions you pass to toggle in a context in which you can hold a flag to control function entrance:-
(function() {
var toggling = false;
$('.button').toggle(function(){
if (!toggling) {
toggling = true;
// first function
toggling = false;
} else {
// whatever you want to happen if re-entrance attempted
}
}, function(){
if (!toggling) {
toggling = true;
// second function
toggling = false;
} else {
// whatever you want to happen if re-entrance attempted
}
})
)();
N.B. This serialises all toggles of elements that have the .button class. IOW there is only one toggling flag for all buttons. If you want each button to have its own toggling flag:-
$('.button').each(function() {
var toggling = false;
$(this).toggle(function(){
if (!toggling) {
toggling = true;
// first function
toggling = false;
} else {
// whatever you want to happen if re-entrance attempted
}
}, function(){
if (!toggling) {
toggling = true;
// second function
toggling = false;
} else {
// whatever you want to happen if re-entrance attempted
}
});
);
You need a queue. You can build one with a semaphore variable, but jQuery already provides one, so maybe you want to use it:
$('.button').toggle(function() {
$(document).queue("foo", function() {
...
});
}, function() {
$(document).queue("foo", function() {
...
});
});
jQuery normally uses the "fx" queue to serialize animations, but you can use this "foo" queue for whatever you want.
The queue can be put on any object, so maybe you want to put it on the container that has all the .button objects in it. You cannot put it on the button (this) themselves, or you'll be back to where you're at now.
Once you've done that, all you really need to do is abort an animation. This can be done by expressly emptying the "fx" queue, or you can use $('.button').stop(); to stop all the old animations.