Jquery - Firefox having slow .live() hover speeds, Chrome & IE are fast - javascript

OK, so I am working on a new website. Its a social networking type website and it has a lot of jquery interactivity.
Problem comes in when I try using the JQuery.live() for mouseover effects. It runs Very fast in Chrome & Safari, Pretty fast in IE, and slow in Firefox. Very strange as almost always FF is way faster than IE(8/9).
Page in question:
http://www.modelfy.com/user/22/info
If you hover over the 'latest pictures' in chrome and then in Firefox you will notice a huge difference in speed.
$('.hoverme').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
$(this).addClass('hoverclass');
} else {
$(this).removeClass('hoverclass');
}
});
Any help would be hugely appreciated. Also, is .live the best option for optimization?
Thanks!

i'm not totally sure why firefox is slower but you can try to add a context element. Instead of binding all events to the root element you can do something like this:
$('div.clickme', $('#recent_photos')[0]).live('mouseover mouseout', function() {
...
});
Doing this minimizes the amount of traversal and the amount of events bound to the same node.
To figure out which function call is slow you can profile your code with firebug. To get useful results you have to use the uncompressed version of jQuery.

Related

Javascript/JQuery drop event not firing in Internet Explorer IE 11

I'm dragging and dropping images from a different browser tab into the tab for my web page. My event handlers for the "drop" event are working in every other desktop browser except Internet Explorer 11.
IE just navigates away to the URL of the image I dropped, rather than firing the "drop" event and letting my JS code do what it wants with it (as happens in Chrome, Firefox, Opera and Safari, on Windows 7). Code is below. Note none of the alerts listed in the code fire.
I even followed the advice given on Microsoft's page here: https://msdn.microsoft.com/en-us/library/ms536929(v=vs.85).aspx
regarding cancelling the default action of "dragenter" and "specifying window.event.returnValue=false in both the ondragenter and ondragover event handlers" (note: other browsers didn't require me to have a dragenter event handler)
$(window).on("dragenter", function(event) {
alert('drag enter');
event.returnValue = false;
event.preventDefault();
event.stopPropagation();
});
$(window).on("dragover", function(event) {
alert('drag over');
event.returnValue = false;
event.preventDefault();
event.stopPropagation();
});
$(window).on("dragleave", function(event) {
alert('drag leave');
event.preventDefault();
event.stopPropagation();
});
$(window).on("drop", function(event) {
alert('drop');
event.preventDefault();
event.stopPropagation();
var imageSrc = $(event.originalEvent.dataTransfer.getData('text/html'))
.filter(function(i, elm){return $(elm).is('img');}).attr('src');
// Now do something with the imageSrc URL:
});
Many thanks for any suggestions!
It is working fine in IE Browser Version:11.0.40 for jQuery 2.2.4 version.
Please check your jQuery version
Note: for me event has been fired for two times when dragging image from desktop to IE 11 browser.
Please find Demo link.
Edit:
Interesting what I've got here (S.O question/answer), they had a similar problem dragging between two Internet Explorer 11 windows, on the same domain. So one more reason, if they are from different domains. He quotes:
so far I understood that this will work on Windows 10 MS browsers with
at least 1607 as version
First, this is by no means intended to be an answer to this question, it merely serves as a group of points that may help build a final answer to this puzzling problem
Two cases scenario
On the same domain
Tested when both pages are on localhost, Those events has fired normally :
you will have to change getData('text/html') to getData('text') because IE support only that, 'URL' or files
so you need to set setData() from the original page accordingly
(Generally, if the dragged markup is an image without any links, you're fine the getData('text') gives you the attribute src of the image)
On different domains
Here is the part where this is not much of an answer, the following points have been tried and are given here to be retested, tweaked or expanded in order to find a solution. As a final thought that I'm putting here first: may be this is not possible, because as you may already know, dragged markup can have inline scripts, making the target vulnerable to XSS attacks. It's not very unlikely that hackers have tried to make it happen (roughly as I'm doing right know) and each time Microsoft has counteract it.
As the original poster pointed out the use of returnValue=false is pointless. I've tried it on the original event event.originalEvent and with event as a window's event and as the handler parameter.
You may think since I've mention domain that this is a cross domain issue (very legitimate) here's what I've tried in PHP:
header("Access-Control-Allow-Origin: *");
After IE had been known for been vulnerable to XSS attacks, it may have taken drastic measures against it in IE 11, so reverting to a previous version's behaviour of it, IE9 for instance :
header('X-UA-Compatible: IE=EmulateIE9');
header('X-UA-Compatible: IE=9');
N.B The following point is not intended to be a viable solution (at least not from a developer's perspective) it is an attempt to narrow down the possibilities of the origin of the problem
You may want to try Internet Explorer's :
internet options>Custom level...-->miscellaneous--> under the label 'allow the dragging of content between separate windows' --> check enable
Or Internet Explorer security zones registry entries for advanced users or using this reference
Notice that for the purpose of testing you can make cross domain dragging between IE and Firefox/Chrome back and forth with DataTransfer behaving roughly as between two IEs on the same domain.

iPhone vs Javascript event suppression

I've got a simple click handler that does something on the screen instead of visiting that link. Here's the code (I'm cutting out the nonsense but the important stuff is accurate):
Link Text
<script type="text/javascript" src="./path/to/jquery.js"></script>
<script type="text/javascript">
$('#others').on('click', function(ev){
ev.preventDefault();
ev.stopPropagation();
// Doing stuff (some simple DOM manipulation)
return false;
});
</script>
This works fine on proper browsers. It works fine on Android (both older webkit and newer Chrome builds) and it works fine on iOS on the iPad 2... But one of my users is using an iPhone 4 and that's where all the fun starts.
When they click the link, the link loads. Despite three separate triggers not to, the event is still firing. Other javascript is working on the page and as I say, this is working everywhere else. Actually to confuse things a little more, the event is suppressed very, very occasionally. Less than 1% of the time.
So is this a known issue with iPhones? Is there a better way of doing all this?
The javascript is loaded at the end of the body (still inside it, but after all the DOM elements it mentions). jQuery version is 1.10.1
try using href="javascript:void();"
Link Text
$('#others').on('click', function(ev){
//ev.preventDefault();
//ev.stopPropagation();
// Doing stuff (some simple DOM manipulation)
return false;
});

Eliminate 300ms delay on click events in mobile Safari

I've read that mobile Safari has a 300ms delay on click events from the time the link/button is clicked to the time the event fires. The reason for the delay is to wait to see if the user intends to double-click, but from a UX perspective waiting 300ms is often undesirable.
One solution to eliminate this 300ms delay is to use jQuery Mobile "tap" handling. Unfortunately I'm not familiar with this framework and don't want to load some big framework if all I need is a line or two of code applying touchend in the right way.
Like many sites, my site has many click events like this:
$("button.submitBtn").on('click', function (e) {
$.ajaxSubmit({... //ajax form submisssion
});
$("a.ajax").on('click', function (e) {
$.ajax({... //ajax page loading
});
$("button.modal").on('click', function (e) {
//show/hide modal dialog
});
and what I'd like to do is to get rid of the 300ms delay on ALL those click events using a single code snippet like this:
$("a, button").on('tap', function (e) {
$(this).trigger('click');
e.preventDefault();
});
Is that a bad/good idea?
Now some mobile browsers eliminate 300 ms click delay if you set the viewport. You don't need to use workarounds anymore.
<meta name="viewport" content="width=device-width, user-scalable=no">
This is currently supported Chrome for Android, Firefox for Android and Safari for iOS
However on iOS Safari, double-tap is a scroll gesture on unzoomable pages. For that reason they can't remove the 300ms delay. If they can't remove the delay on unzoomable pages, they're unlikely to remove it on zoomable pages.
Windows Phones also retain the 300ms delay on unzoomable pages, but they don't have an alternative gesture like iOS so it's possible for them to remove this delay as Chrome has. You can remove the delay on Windows Phone using:
html {
-ms-touch-action: manipulation;
touch-action: manipulation;
}
Source: http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away
UPDATE 2015 December
Until now, WebKit and Safari on iOS had a 350ms delay before single taps activate links or buttons to allow people to zoom into pages with a double tap. Chrome changed this a couple of months ago already by using a smarter algorithm to detect that and WebKit will follow with a similar approach. The article gives some great insights how browsers work with touch gestures and how browsers can still get so much smarter than they are today.
UPDATE 2016 March
On Safari for iOS, the 350 ms wait time to detect a second tap has been removed to create a “fast-tap” response. This is enabled for pages that declare a viewport with either width=device-width or user-scalable=no. Authors can also opt in to fast-tap behavior on specific elements by using the CSS touch-action: manipulation as documented here (scroll down to the 'Styling Fast-Tap Behavior' heading) and here.
This plugin -FastClick developed by Financial Times does it perfectly for you!
Make sure though to add event.stopPropagation(); and/or event.preventDefault(); directly after the click function, otherwise it might run twice as it did for me, i.e.:
$("#buttonId").on('click',function(event){
event.stopPropagation(); event.preventDefault();
//do your magic
});
i know this is old but can't you just test to see if "touch" is supported in the browser? Then create a variable that's either "touchend" or "click" and use that variable as the event that gets bound to your element?
var clickOrTouch = (('ontouchend' in window)) ? 'touchend' : 'click';
$('#element').on(clickOrTouch, function() {
// do something
});
So that code sample checks to see if the "touchend" event is supported in the browser and if not then we use the "click" event.
(Edit: changed "touchend" to "ontouchend")
I've come across a hugely popular alternative called Hammer.js (Github page) which I think is the best approach.
Hammer.js is a more full-featured touch library (has many swipe commands) than Fastclick.js (most upvoted answer).
Beware though: scrolling fast on mobile devices tends to really lock up the UI when you use either Hammer.js or Fastclick.js. This is a major problem if your site has a newsfeed or an interface where users will be scrolling a lot (would seem like most web apps). For this reason, I'm using neither of these plugins at the moment.
Somehow, disabling zoom seems to disable this small delay. Makes sense, as double-tap isn't needed anymore then.
How can I "disable" zoom on a mobile web page?
But please be aware of the usability impact this will have. It may be useful for webpages designed as apps, but shouldn't be used for more general-purpose 'static' pages IMHO. I use it for a pet project that needs low latency.
Unfortunately there is no easy way to do this. So just using touchstart or touchend will leave you with other problems like someone starts scrolling when click on on a button for example. We use zepto for a while, and even with this really good framework there are some issues that came up over the time. A lot of them are closed, but it seems is not a field of simple solution.
We have this solution to globally handle clicks on links:
$(document.body).
on('tap', 'a',function (e) {
var href = this.getAttribute('href');
if (e.defaultPrevented || !href) { return; }
e.preventDefault();
location.href= href;
}).
on('click', 'a', function (e) {
e.preventDefault();
});
I searched for an easy way without jquery and without fastclick library. This works for me:
var keyboard = document.getElementById("keyboard");
var buttons = keyboard.children;
var isTouch = ("ontouchstart" in window);
for (var i=0;i<buttons.length;i++) {
if ( isTouch ) {
buttons[i].addEventListener('touchstart', clickHandler, false);
} else {
buttons[i].addEventListener('click', clickHandler, false);
}
}
In jQuery you can bind "touchend" event, witch trigger code inmediatly after tap (is like a keydown in keyboard). Tested on current Chrome and Firefox tablet versions. Don't forget "click" also, for your touch screen laptops and desktop devices.
jQuery('.yourElements').bind('click touchend',function(event){
event.stopPropagation();
event.preventDefault();
// everything else
});
Just to provide some extra information.
On iOS 10, <button>s on my page could not be triggered continuously. There was always a lag.
I tried fastclick / Hammer / tapjs / replacing click with touchstart, all failed.
UPDATE: the reason seems to be that the button is too close to the edge! move it to near the center and lag gone!
You're supposed to explicitly declare passive mode :
window.addEventListener('touchstart', (e) => {
alert('fast touch');
}, { passive : true});

DOM change event for Opera

So far I found how to do it in Chrome, the DOMSubtreeModified event:
Is there a JavaScript/jQuery DOM change listener?
Apparently it works in Firefox and IE 9 too.
Do you know solutions for detecting DOM changes in other browsers such as Opera? And maybe older versions if IE, because I'm sure the event above doesn't work in IE 6-7-8...
Or do you know other events I could use?
I'm basically looking for a way to detect if certain elements have been inserted in the document trough ajax requests...
Opera supports the DOMNodeInserted and DOMNodeRemoved mutation events. I tested and they worked on Firefox and G. Chrome too.
$(document).bind("DOMNodeInserted, DOMNodeRemoved", function() {
alert("DOM changed");
});
If you're targeting multiple browsers, maybe you could check if Mordenizr has any detection for DOM mutation events support, it could help you a lot to simplify these decisions.
onreadystatechange will work in IE8 and below. A DHTML behavior must be attached to the element via htc, but the htc file does not have to exist:
if (!!document.addEventListener)
{
$(document.documentElement).get(0).addEventListener("DOMNodeInserted", bar, false);
}
else
{
$(document.documentElement).get(0).addBehavior("foo.htc");
$(document.documentElement).get(0).attachEvent("onreadystatechange", bar);
}

Opera: Detecting back, forward, refresh and close events

I'm currently working on a jQuery plugin that tracks a visitors mouse behavior. Movements, clicks, scrolling and resizing are all recorded and sent, via Ajax, to a location where this data is parsed and stored.
Originally, the data is sent to a script when the user leaves the page. By 'leaves' I'm referring to refreshing, going back and forth though history, closing the window/tab and going to a different address.
The solution works in all browsers EXCEPT for Opera. I'm using jQuery's 'unload' event which isn't supported by Opera at all. Neither is onbeforeunload or onunload.
The question is, how do I implement this kind of functionality for Opera browsers?
One solution I had was to make special use of a 'polling' feature I created. This feature allows you to specify an interval which pushes the content to the server every 'x' seconds. Setting this to 1 second specifically for Opera browsers would probably solve this issue, but it's an awful amount of overhead and the requests aren't always completed in sequence, etc ...
Any suggestions or am I only stuck with the above option?
Thanks!
I suppose I could just link you guys to the plugin source. http://www.thedrunkenepic.com/junk/jquery.mousalytics.js
Regarding the code linked above, adding:
if(window.opera)
{
options.interval = 1;
}
On line 89 works great. My only concern is overhead, so I'm still looking for a more elegant solution.
According to http://bytes.com/topic/javascript/insights/799229-browser-quirk-onload-onunload-do-not-fire-back-forward-refresh-opera, Opera never really fires onload / onunload events, so functionality like this isn't possible without hacks.
http://dev.opera.com/articles/view/efficient-javascript/?page=4 seems to confirm this, and basically states that opera tries to maintain the state of the page across requests.
On further investgation, http://unitehowto.com/Onunload indicates that it might be possible with opera.io.webserver.addEventListener('_close', onunload, false); (where onunload is a previously defined function), however it also indicates that this functionality is not consistent across all versions of opera, and might not work at all.
I think that your best option is probably to use the polling option for Opera, or possibly use a server-side check for the current page and where it falls in the history queue.
Does adding this line of JavaScript work for you?
history.navigationMode = 'compatible';
Source: http://www.opera.com/support/kb/view/827/
I've had the same problem and this saved my day:
if( typeof(opera) != 'undefined' )
{
opera.setOverrideHistoryNavigationMode( 'compatible' );
history.navigationMode = 'compatible';
}
More info about this problem can be found at: http://www.opera.com/support/kb/view/827/

Categories