How to distinguish between left and right mouse click with jQuery

As of jQuery version 1.1.3, event.which normalizes event.keyCode and event.charCode so you don’t have to worry about browser compatibility issues. Documentation on event.which event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively so: $(‘#element’).mousedown(function(event) { switch (event.which) { case 1: alert(‘Left Mouse button pressed.’); break; case 2: alert(‘Middle Mouse … Read more

Check if an image is loaded (no errors) with jQuery

Check the complete and naturalWidth properties, in that order. https://stereochro.me/ideas/detecting-broken-images-js function IsImageOk(img) { // During the onload event, IE correctly identifies any images that // weren’t downloaded as not complete. Others should too. Gecko-based // browsers act like NS4 in that they report this incorrectly. if (!img.complete) { return false; } // However, they do … Read more

jQuery.click() vs onClick

Using $(‘#myDiv’).click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent). Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target. var myEl = document.getElementById(‘myelement’); myEl.addEventListener(‘click’, … Read more

jQuery callback on image load (even when the image is cached)

If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this: $(“img”).one(“load”, function() { // do stuff }).each(function() { if(this.complete) { $(this).load(); // For jQuery < … Read more

Direct vs. Delegated – jQuery .on()

Case 1 (direct): $(“div#target span.green”).on(“click”, function() {…}); == Hey! I want every span.green inside div#target to listen up: when you get clicked on, do X. Case 2 (delegated): $(“div#target”).on(“click”, “span.green”, function() {…}); == Hey, div#target! When any of your child elements which are “span.green” get clicked, do X with them. In other words… In case … Read more