How to trigger (window).focus on page load? - javascript

When the page is loaded the focus/blur state isn't activated. When switching to for example another tab blur show, and upon switching back to the page focus activates – but at first load of the page none of the states are activated, why? Is this expected behavior or have I messed something up?
$(function(){
$(window).focus(function() {
document.title="focus";
});
$(window).blur(function() {
document.title="blur";
});
});
Update
Seems like Adding }).focus(); as suggested by Rory in the comments doesn't make any difference anymore due to changes in browsers – so I'm still looking for a way to detect focus on page load.
Update 2
I've added an onload to act as a "pretend focus", so far this is the best I've managed to come up with. Don't know if this a reasonable solution, so if you've got a better one I'd love to take part of it.
window.onload = function(){
document.title="focus";
};
window.onblur = function() {
document.title="blur";
};
window.onfocus = function() {
document.title="focus";
};

Related

Target page does not render after using back-button

Dear community and readers:
programming a small website I have encountered for first time a strange behavior. What I basically do is that I hide the body until page load and then fade it in. Via onClick on a link in the navigation I use redirectPage and the procedure repeats with the target link page. So this works all wonderful but when visiting the site in the browser and using the back button it seems that the pages visited before are not rendering. Latest Google Chrome versions are doing it, Firefox, Safari fail. Strangely own Safari, clicking the back button three times forces the homepage to load again. This happens most of the times but not all time.
Has anyone an idea how I could achieve in my function to force a render anytime the back button is pressed. Might be a silly question but I really never came across this issue. I tried some snippets I found and worked around them my own way. They did not work and I would rather understand the problem than choose pure cosmetics.
Thank you for your input!
// Document on load.
$(function(){
gotToNextSection();
loaderPage();
ScrollNext();
moreProjectSlider();
// Animate
contentWayPoint();
})();
$(document).ready(function() {
$("body").css("display", "none");
$("body").fadeIn(2000);
$("body").stop().animate({
opacity: 1
});
$("a.transition").click(function(event){
event.preventDefault();
linkLocation = this.href;
$("body").fadeOut(1000, redirectPage);
});
function redirectPage() {
window.location = linkLocation;
}
});

window.stop method does not seem to work when used within a function

So ive been wracking my brains with this for a while but can't figure out why this isnt working.
Im setting up some simple functionality to prevent a user from leaving a page via hyperlink and instead displaying an overlay. So ive set up a simple event listener on all links which when clicked will stop page load and fire up the overlay.
The mmClickRecieved variable is for another part of the script and is just to ensure a user only ever sees this overlay once. The timeout function will fire the same overlay if the user is inactive on page for a certain period of time.
However when i try this code, when clicking a hyperlink the overlay fires fine but the page does not stop loading. Ive tried various bits of this code in isolation and it all seems fine, cant quite figure out why this is not working. Any ideas anyone?
$("a").click(function() {
if (mmClickRecieved === false) {
if (navigator.appName == "Microsoft Internet Explorer") {
window.document.execCommand('Stop');
}
else {
window.stop();
}
clearTimeout(mmTimeout);
mmNumberOverlay();
}
else {
// no further action
}
})
update: not sure why ive got a -1 for this.. I can update the question if it doesnt make sense
Why not use preventDefault - it stops the user from following the link that was clicked and instead allows you to do something else with this click:
var mmClickRecieved = -1;
$("a").click(function(event){
// I am using this as an easy way to mimic your value
if(!(++mmClickRecieved)){
event.preventDefault();
mmNumberOverlay();
}
// You don't need an else, since the event wont be prevented
})
function mmNumberOverlay(){
alert("This happens only once!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Go to Google (this is not allowd in this snippet)!

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.

How to trigger change when using the back button with history.pushstate and popstate?

I'm pretty much a novice when it comes to js so I'm sorry if I'm missing something really simple.
Basically, I've done some research into using the history.pustate and popstate and I've made it so a query string is added to the end of the url (?v=images) or (?v=profile)...(v meaning 'view') by using this:
var url = "?v=profile"
var stateObj = { path: url };
history.pushState(stateObj, "page 2", url);
I want to make it so I can load content into a div but without reloading the page which I have done using the .load() function.
I then used this code:
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
in $(document).ready() section and later tried within just <script> tags and neither worked.
I don't know how to make it so the content changes when I use the back button or at least makes it so I can trigger my own function to do so; and I'm assuming it has something to do with the state object?! I just can't seem to find anything online that explains the process clearly.
If someone could help me out it would be amazing and thank you in advance to anyone who does!
The popstate only contains a state when there is one.
When it goes like this:
initial page loaded
new page loaded, with state added via pushState
back button pressed
then there is no state, because the initial page was loaded regularly, not with pushState. As a result, the onpopstate event is fired with a state of null. So when it is null, it means the original page should be loaded.
You could implement it such that history.pushState will be called consistently and you only need to provide a state change function like this: Click here for jsFiddle link
function change(state) {
if(state === null) { // initial page
$("div").text("Original");
} else { // page added with pushState
$("div").text(state.url);
}
}
$(window).on("popstate", function(e) {
change(e.originalEvent.state);
});
$("a").click(function(e) {
e.preventDefault();
history.pushState({ url: "/page2" }, "/page2", "page 2");
});
(function(original) { // overwrite history.pushState so that it also calls
// the change function when called
history.pushState = function(state) {
change(state);
return original.apply(this, arguments);
};
})(history.pushState);
Maybe it's not best solution, and maybe it doesn't suit your needs. But for me it was best to just reload the page. So the page is consistent an it loads everything according to current querystring.
$(document).ready(function() {
$(window).on("popstate", function (e) {
location.reload();
});
});

triggering a jQuery function n seconds after the tab/window is in view

I am using jQuery to have a promotional window opening up -say- 5 seconds after a page is loaded. But the effect is lost for people who open the page in a new window or a new tab. When they get to my tab the window will already be open.
Is there a way to get this to fire when people actually start viewing my site?
I was thinking about catching a scroll or something, but people don't get started scrolling immediately and most won't scroll at all. Other than that I am out of ideas.
I am not sure if jQuery offers a solution here... javascript?
Thanks.
the following should do the trick .. (jQuery)
<script type="text/javascript">
function initiatePopup(){
$(window).unbind('blur');
$(window).unbind('focus');
// do the popup
};
$(document).ready(
function(){
$(window).focus( initiatePopup ).blur( initiatePopup );
// your other functions should go from here on
}
);
</script>
[EDIT] on OP request..
code edited to make the example all inclusive
[EDIT 2]
The code above has been edited again because we need to handle the blur event as well.. so we take the code for the popup somewhere else in order to not duplicate it inside both events..
[EDIT 3]
if you want to pass parameters to the popup if they are created later on, then change the event binding line to
$(window).focus( function() { initiatePopup(params); } ).blur( function() { initiatePopup(params); );
and of course change the initiatePopup to accept parameters ..
Would putting a div around everything work with an onmouseover event listener? I've never tried it, so I'm not sure whether that would fire or not, but it might be worth a shot.

Categories