Reputation: 105
I want to track clicks on AdSense elements on my page. To achieve that I put the focus on the window object and if it loses focus, I check if the mouse was in the area of the AdSense iFrame. Then i put the focus back on the window again.
This works. But in Chrome it works only once. So if I click on an adSense ad (opening in a new tab) and then I click on another one, the event doesn't fire anymore.
If I execute $(window).focus() in the console, the onBlur event fires again - but the $(window).focus() executed from within my code doesn't show any effect. I tried it with a Timeout too, without success.
Any ideas?
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
$(window).focus();
}
};
};
Simplified version: https://jsfiddle.net/327skdns/2/
Upvotes: 1
Views: 2613
Reputation: 3579
This is a documented Chrome bug: jQuery focus not working in Chrome
You need to wrap your focus()
call with a setTimeout:
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
setTimeout( function(){ $(window).focus(); }, 50 );
}
};
}
Upvotes: 1