fire event on closing the page - javascript

I wonder if i've unset($_SESSION['enough']); and want to free it up on closing the page.
[ suppose visitor is viewing page of the website pages in new tab ]
i'm using this code
<script language="javascript">
window.onbeforeunload = function() {
console.log('event');
return false;
}
</script>
i wonder how can i apply to fire this code unset($_SESSION['login_id']); , it might look ridicules but this is the basic idea and i'm gonna give example what can be used for
For example : media website would like members not to watching more than one video in same time so the watching page drop session and free it on closing it so can watch more! js indeed is essential for website using jwplayer so no chance of talking about members with disabled js.

In order to load the killsession.php that runs the unset() command, you can run that page with ajax with async:false
Have a look at
Ajax request with JQuery on page unload
jQuery.ajax({url:"http://localhost/killsession.php", async:false})

You can use jQuery to fire on unload with the unload function (http://api.jquery.com/unload/).
$( window ).unload(function() {
// On the unload, we can fire a request back to the server
// .get(), .post(), and .ajax() may be useful.
});

Related

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

jQuery Mobile Binding Spinner To ChangePage

After a lot of google'ing and reading forums I've not found a suitable answer.
So far all I have found is something like below:
show loading message
call change page
hide loading message
This would work but I would have to do this every time I call load/change page (which is a lot).
Which would leave me either to make a middle man function like below:
function customLoader(url){
showLoader();
$.mobile.changePage(url);
hideLoader();
}
Is there anyway of binding it to the change page event?
So that it shows from the second changePage is called but hides once changePage is away...
I know the above middle man method would work but would like something more tidy and nicer to implement as there's a lot of html/js files.
Something like this:
$('#index').live('pagebeforeshow',function(e,data){
$('#test-button').live('click', function(e) {
$.mobile.showPageLoadingMsg(true);
setTimeout(function () {
$.mobile.changePage('#second');
}, 1000);
});
});
$("#second").live('pageshow', function () {
$.mobile.hidePageLoadingMsg();
});
Timeout is here only so you can see it's working successfully. This is a light example so transition is fired quickly. Remove it in your real code.
And here's an example: http://jsfiddle.net/Gajotres/arrHd/
Every change page event cycle has a order of events occuring when a page A is transiting to a page B. No matter which action is used to trigger a change page you can always disable it when page B i successfully loaded. If you want to find more about page load order take a look at this link: https://stackoverflow.com/a/14010308/1848600. There you will find a lot about jQM page dynamics.
In case you want to implement this into every page transition use this:
$('[data-role="page"]').live('pageshow', function () {
$.mobile.hidePageLoadingMsg();
});
This will hide a ajax loader (if it is open) every time a different page is successfully loaded and shown.
Maybe it's too much for many, but I found a solution different than the written in the comments of this question.
I use the jquery mobile router and in the 'show' event of a page, I do $.mobile.loading("show");, so when the page appears it does with the loading spinner showing.
I use Jquery Mobile Router for a lot more, but it solved this issue.
Though to hide the spinner, I had to use $('.ui-loader').hide();, which is weird, I know...
(Maybe just listening to the proper event and triggering the spinner would also work, as this is what JQMR does...)
I'm using JQM 1.4.2...

Callback when web page download completes

When the user click on a tab in a web page, the tab opens and its corresponding page downloads from the server.
I want to add some UI in this page through JavaScript or jQuery. I know how I can add this but problem is if I execute my JavaScript function for adding UI on click of the tab, it does not work because the corresponding page has not been downloaded yet.
Basically, what I want to know such function that is called when the page completely downloads.
Have you used JQuery success ?? success handler will be called only after your response is ready.
Try this :
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//Do the stuff here, hence downloading has been completed and response from server is ready
$(this).addUI("done");
}
});
add this in the body of your page..
<body onload="init()">
</body>
Basically your calling your init function -- which initiates all the other functions which you want only after the body of the webpage is loaded..
I have face this problem too.. Problem here is your content is not yet available before you could work on it.
any reference you give will result in returning Null
The solution can be .bind() & .live()
suppose this is your dynamic content
$('body').append('<div class="clickme">Another element</div>');
you can bind the element by,
$('.clickme').bind('click', function() {
// Bound handler called.
});
or register it for live content, by
$('.clickme').live('click', function() {
// Live handler called.
});
when no longer needed, you may unsubscribe the event on dynamic content by .die()
you may also find .delegate() & undelegate() useful as there are little issues with .live() & .die().
Check http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ for choosing the one you need for your application.
Remember not to forget you ensure that content is loaded by ajax success as programmer_1 here, mentioned.
Good luck :)
Any further clarifications pls comment.

Detect first page load with jQuery?

I need to detect the first time a page loads in jQuery so that I can perform some actions only when the page loads the first time a user navigates to that page. Similar to server side code page.ispostbasck. I have tested $(document).ready and it fires every time the page loads so this will not provide what I need. I have also tried the jQuery Load function - it also fires every page load. So by page load an example is that I have an HTML input tag on the page of type button and it does not fire a postback (like an asp.net button) but it does reload the page and fires $(document).ready
Thanks
You will have to use cookie to store first load information:
if (! $.cookie("cookieName")){
// do your stuff
// set cookie now
$.cookie("cookieName", "firstSet", {"expires" : 7})
}
Note: Above example uses jQuery Cookie plugin.
An event doesn't exist that fires only when the page is loaded for the first time.
You should use jQuery's .ready() event, and then persist the fact that you've handled a first time page load using your method of choice (i.e. cookie, session variable, local storage, etc.).
Note: This method will never be fool proof unless you can store this information at the user level in a DB. Otherwise, as soon as the user clears their cookies, or whatever method you choose, the "first time loaded" code will fire again.
I just ran into this problem and this is how I handled it. Keep track of the first time the page loads by using a variable initialLoad:
var initialLoad = true;
$(document).ready(function() {
...
...
...
initialLoad = false;
});
Then in other functions, you can do this:
if (initialLoad) {
//Do work that is done when the page was first refreshed/loaded.
} else {
//Do work when it's not the initial load.
}
This works well for me. If the user is already on the page and some jQuery functions run, I now know if that user just loaded the page or if they were already on the page.
The easy solution is to use jQuery ‘Once’ plugin
$(element).once('class-name', function() {
// your javascript code
});

Is there a way to catch the back button event in javascript?

Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the hashchange event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.
What I ended up doing was creating an object as such:
var pageload = {
ignorehashchange: false,
loadUrl: function(){
if (pageload.ignorehashchange == false){
//code to parse window.location.hash and load content
};
}
};
Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:
window.addEventListener("hashchange", pageload.loadUrl, false);
Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:
pageload.ignorehashchange = true;
and then the following line after each hash modification line:
setTimeout(function(){pageload.ignorehashchange = false;}, 100);
So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.
Check out history.js. There is a html 5 statechange event and you can listen to it.
onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.
Did you took a look at this? http://developer.yahoo.com/yui/history/

Categories

Resources