$(window).focus() runs twice for each focus - javascript

I'm not sure why this happens and I would love to get an explanation.
Using jquery's focus method I bind to the window focus event.
This is a working example (copy paste into a html file and open in a browser. Doesn't work in jsfiddle or jsbin, for some reason)
<!DOCTYPE html>
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script></head>
<body>
<p1>Here:</p1>
<div id="here" >Why</div>
</body>
<script>
$(window).load(function() {
$(window).focus(function() {console.log("focus");});
$(window).blur(function() {console.log("blur");});
});
</script>
</html>
When the browser regains focus the function runs twice and 'focus` is printed into the console twice.
Any idea why this happens?
The end goal, btw, is to stop a timer from running whenever the user leaves the browser to an app or another tab.
UPDATE
Running on the latest (dev) version of chrome. I'll test it on firefox and write if it's different there.
UPDATE 2
Interesting fact - Doesn't happen on firefox. Maybe its a bug with chrome.

I had this same problem. My fix for this was using lodash's debounce() function (https://lodash.com/docs/#debounce). This was my fix:
var debouncedFocus = _.debounce(() => {
console.log('focussed');
}, 250, {leading: true, trailing: false});
$(window).on('focus', debouncedFocus);

live() has been deprecated. Use on() instead.
$(window).on("focus", function(){ alert("focus!"); });
You could try using the live() function.
$(window).live("focus", function(){ alert("focus!"); });

Maybe load() is called twice? You can register these events without .load(). Try this:
<script>
$(window).focus(function() {console.log("focus");});
$(window).blur(function() {console.log("blur");});
</script>

Which browser ? Seems to run fine for me.
As a precaution, you can use a javascript variable to make it run only once.
<script>
var isFocused = false;
$(window).load(function() {
$(window).focus(function() {
if(isFocused)
return;
console.log("focus");
isFocused = true;
});
$(window).blur(function() {
console.log("blur");
isFocused = false;
});
});
</script>

If you're simultaneously using Underscore, you can use the _.debounce() method to clamp down repeated events to a single event.

Related

OnClick works only works after reload, using jquerymobile

I know it's an often asked question, but no answer (till now) fits for me.
I wrote a mobile app with Cordova. I'm also testing apps in browser (Firefox). I'm using jQuery and jq mobile.
The problem is: my OnClick events on work only after refresh, which isn't possible on mobile and even on pc not really an solution.
Update: I read about, that the ehader isn't loaded again in jQuery mobile. So I treid it as described in thsi solution: page loaded differently with jQuery-mobile transition
didn't work.
And with alert(); you see, that the script runs once but before the site is totally build.
My html:
<div data-role="main" class="ui-content" id="container" >
<div id="container0">
<a data-role="button" id="anchor0" >Neuen Termin Hinzufügen</a>
</div>
</div>
originally the <a> had an onclick (<a onClick>="doStuff()")
Here a are my different attempts:
$(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
});
$(document).ready($(function () {
// Assign the click handler on DOM-ready
$('a').on('click', function () {
dateElementClicked(this);
});
})
);
$("#anchor0").live("click", dateElementClicked($("#anchor0")));
$("a").click( dateElementClicked(this));
$("a").bind("click", function (event, ui){
dateElementClicked(this);
});
They all work only after an refresh. or the first one runs the function instant and interupts everything because "this" is undefined.
Edit:
I even tried it with button and inpute type button and made extra js file. but my javascript only runs after an refresh... Putted an console log and alert in the script. So the whole script is stuck somehow
The dateelement clicked function (I cleared this too for testing and just put an alert() in it)
Here is the git link to the project: https://github.com/LosKartoflos/Apoll.git
function dateElementClicked(clickedAnchor) {
//anchor is clicked the first time(the id number equals numberOfAppointments)
if (clickedAnchor.id.slice(-1) == numberOfAppointments) {
dateElementClickedFirstTime(clickedAnchor);
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == true)
{
hideContent(getDateElementNumber(clickedAnchor));
}
else if (appointmentList[getDateElementNumber(clickedAnchor)]["RolledOut"] == false)
{
showContent(getDateElementNumber(clickedAnchor));
}
else
{
alert("Element not listed");
}
}
BTW: my script isin my html file.
Maybe try using the deviceready event instead of document ready.
https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
Try this
$(document).on('click', '#anchor0', function(event) {
});
or this
$(document).on('click', 'a', function(event) {
});
okay the Problem is, that Cordova is messing around with normal build/loading oder. to trigger functions, after the side is loaded.
The Cordova Documentary recommends this two solutions:
Put this in your header and bind your events in the onload or dofirst. An do everything you want to be have done, after page is ready, in the do first:
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/script.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//add all Events (click Events)
function onLoad() {
document.addEventListener("deviceready", doFirst(), false);
document.getElementById("anchor").addEventListener("click", clickedFunction, false);
}
// device APIs are available
function onDeviceReady() {
}
//things to put up first
function doFirst() {
}
</script>
or put it in the onDeviceReady function, in the auto created index.js .
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
document.getElementById("anchor0").addEventListener("click", clicked, false);
app.receivedEvent('deviceready');
},
Here the documentary: https://cordova.apache.org/docs/en/4.0.0/cordova_events_events.md.html
And i kicked out jquery and jquery mobile. Jquery was messing around with document ready and jquery mobile prevents the head from beeing loaded again.

document.ready() function not executed, works in dev console

I'm trying to simulate a click in a tabbed div when the page loads.
To do this I use:
$(document).ready(function() {
$("#tab_inbox").click();
});
However, this doesn't seem to work, but when I enter this in the dev console on Google chrome, it does work..
$("#tab_inbox").click();
To show the tabs, I use this code:
$("#tab_inbox").click(function() {
$("#othertab").hide();
$("#tab_inbox").show();
});
Anybody knows what's wrong?
Try this:
$(document).ready(function() {
setTimeout(function () {
$("#tab_inbox").trigger('click'); //do work here
}, 2500);
});
I read in your comment that you're using show/hide techniques and I assume you need the click for an initial display option? If so, hide (or show) your element(s) specifically in the code rather than saying click to hide/show. So
$(document).ready(function() {
$("#tab_inbox").hide();
}
Or try core JavaScript and use
window.onload = function() {
// code here
}
window.onload waits until everything is loaded on your page, while jQuery's .ready() may fire before images and other media are loaded.
you can try making your own function with pure JS:
document.getElementById('triggerElement').addEventListener('click', funtction(e) {
document.getElementById('hideElement').style.display = 'none';
document.getElementById('showElement').style.display = 'block';
}, false);

window.unload() won't work in jQuery

I'm trying to alert something out after closing page.
A simple window.unload example as below :
HTML
<html>
<body>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="test.js" type="text/javascript">
</html>
test.js
$(window).unload( function () {
alert("Bye now!");
});
P.S :
I have tried javascript too, but doesn't alert anything out !
test.js
window.onunload = function() {
alert("Bye now!");
};
Most browsers prevent alert in unload. The best you can do is to use an onbeforeunload handler that returns a string - the browser will show that string to the user:
window.onbeforeunload = function() {
return "Bye now!";
};
Demo here.
What browser are you testing this code in ?
If you check the following link from W3School, Opera and Chrome do not support it. LINK
And a working example for onbeforeunload is to use jquery as following :
$(window).on('beforeunload', function() {
// Do stuff
});
(I was going to comment this last bit on the above post but I cannot yet comment :'( )
Use body or document instead of window.

window.onload function doesn't work on Mozilla Firefox

I'm using a loading screen for a webpage and I use window.onload function.
Everything works great except in Mozilla Firefox browsers. When we first visit or refresh the page with ctrl+F5 combination, the loading screen never disappears. if we refresh the page only with F5, then it works.
I use the code below
$(window).load(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
I have also tried the code below but nothing changed.
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}
Why this is happening?
Please help.
Thanks in advance.
The problem is caused by another jquery background plugin which is placed inside $(document).ready()
I moved it inside $(window).load() function, now it works perfect.
I have also moved another function to resize images on the page load. When it was inside $(document).ready() block, sometimes it was malfunctioning if loading time took too long but now it also works great.
function resizeImages(){
//Some Code
}
$(window).load(function(){
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
$.vegas({
src: backURL , fade:0
});
resizeImages();
});
$(document).ready(function(){
//Some Other code
});
I got the same problem when mistyped the type attribute in the script tag:
<script type="text/javascript">
Try This:
$(document).ready(function(e) {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
});
Read for load and ready functions difference What is the difference between $(window).load and $(document).ready?
You must call function on initialization like :
window.onload = init();
in other word modify your code to:
window.onload = function () {
$("#body-mask").fadeOut(1000,function(){
$(this).remove();
});
}();// Added
Copy following code in file then open it with firefox
<script>
window.onload = function () {
alert('saeed')
}();
</script>

$(window).load() in IE?

Recently I ran into a mysterious problem that IE (6-8) is keeping throwing me an error. I don't know if this is the problem, but I think it is.
Open up the F12 developer tools in a jQuery included website, enter
$(window).load(function(){
alert("Wont able to see me");
});
And an error will popup:
"Unable to get value of the property 'slice': object is null or undefined"
Did I do anything wrong, or anything else???
I recently found a work-around for IE not recognizing $(window).load()...
window.onload = function() {
alert("See me, hear me, touch me!");
};
This is a little different than $(function(){}) as it executes after all elements are loaded as opposed to when the DOM is ready.
I recently implemented this in another project and it worked wonderfully.
For anyone still running into this, IE11 (only one I tested) does not fire the the load event if the listener is inside of the jquery ready function. So pull the load function outside of the ready function and it will fire in IE11.
//this is bad
$(() => { //jquery ready
window.onload = () => { //wont fire in IE
cosole.log('window loaded');
}
});
//this is good
$(() => { //jquery ready
cosole.log('dom ready');
});
window.onload = () => { //will fire in IE
cosole.log('window loaded');
}
The latest jQuery (1.7.1) with IE10 and IE9 does not produce such an error for me.
As a side note; If you wish to execute something when the dom is ready;
Try this way;
$(function(){
alert("Wont able to see me");
});
I believe this is the standard convention for attaching a function to domready event.
Reference: jQuery Documentation

Categories

Resources