Tutorial Get X, Y Coordinates of Mouse Within Box

by in , 0

The below code will give you the X, Y coordinates of a mouse click within a given box. Removing all the stuff about the offset, you can easily get the X, Y coordinates of the click relative to the browser window.

$(function() {
$("#demo-box").click(function(e) {

  var offset = $(this).offset();
  var relativeX = (e.pageX - offset.left);
  var relativeY = (e.pageY - offset.top);

  alert("X: " + relativeX + "  Y: " + relativeY);

});
});

Example

Click in the box below

Tutorial Get Query Params as Object

by in , 0

Nicholas Ortenzio wrote this little plugin:

jQuery.extend({

  getQueryParameters : function(str) {
	  return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
  }

});

So if the URL is:

http://codepen.io/chriscoyier/pen/uszCr?lunch=sandwich&dinner=stirfry

You can do:

var queryParams = $.getQueryParameters();

And queryParams will be an object like:

{
   "lunch": "sandwich",
   "dinner": "stirfry"
}

Tutorial Get an Images Native Width

by in , 0

If you select and image with jQuery and then use .width(), you'll get the images current width, even if it's been scaled (e.g. max-width: 100%;). You can access the images native width (even if it doesn't have any attributes which declare it) like this:

// Get on screen image
var screenImage = $("#image");

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;

Tutorial Fixing IE z-index

by in , 0

This isn't an end-all-be-all solution to fixing all weird IE z-index issues, but it certainly can help in some circumstances. What it does is loop through each of the elements that you declare and apply ever-declining z-index values on them. IE gets this backwards, and this sets it correctly. The reason it's not end-all-be-all is because sometimes it's not DOM-order that you need z-index to be in, and sometimes scoping comes into play as well.

Nonetheless, the view the demo in IE 7 (thanks Dan Nicholls) to see the broken version on top and the fixed version below.

jQuery Version

$(function() {
       var zIndexNumber = 1000;
       // Put your target element(s) in the selector below!
       $("div").each(function() {
               $(this).css('zIndex', zIndexNumber);
               zIndexNumber -= 10;
       });
});

MooTools Version

if(Browser.Engine.trident){
       var zIndexNumber = 1000;
       // Put your target element(s) in the selector below!
       $$('div').each(function(el,i){
               el.setStyle('z-index',zIndexNumber);
               zIndexNumber -= 10;
       });
};

Reference URL

Tutorial Fixing .load() in IE for cached images

by in , 0

The .load() function fires when the element it's called upon is fully loaded. It is commonly used on images, which may not be fully loaded when the JavaScript originally runs, and thus would return incorrect information about themselves (e.g. height/width). Most browsers deal with this fine. IE can cause problems, when images on the page are cached.

Selecting the image and changing it's src attribute to append a random parameter (based on the date). This will trick IE into firing the .load() function properly.

myImge = $("<img />")
   .attr("src",anyDynamicSource+ "?" + new Date().getTime());

Now the .load() function will work, even in IE:

$(myImge).load(function() {
   alert("will alert even in IE")
});
See the first comment for a warning about using this technique with a CDN.

Tutorial Fix Select Dropdown Cutoff in IE 7

by in , 0

Run (at least the "Usage" part below) after you've loaded jQuery and either at the end of the page or in a DOM ready statement. Note that this fix does create a clone of the select, which will submit itself with the form data, but the name value has been changed to include "-clone" at the end of it, so just be aware of that especially if you are serializing all inputs.

Thanks to Craig Hoover.

// Safely use $
(function($) {

	$.fn._ie_select=function() { 
	
		return $(this).each(function() { 
		
			var a = $(this),
			    p = a.parent();
		
			p.css('position','relative');
		
			var o = a.position(),
			    h = a.outerHeight(),
			    l = o.left,
			    t = o.top;
		
			var c = a.clone(true);
		
			$.data(c,'element',a);
		
			c.css({
				zIndex   : 100,
				height   : h,
				top      : t,
				left     : l,
				position : 'absolute',
				width    : 'auto',
				opacity  : 0
			}).attr({
				id    : this.id + '-clone',
				name  : this.name + '-clone'
			}).change(function() {
				$.data(c,'element')
					.val($(this).val())
					.trigger('change')
			});
				
			a.before(c).click(function() { 
				c.trigger('click');
			});
		
		}); // END RETURN
	
	}; // END PLUGIN
        
        // Usage
	if ($.browser.msie) {
		$('select')._ie_select();
	}

})(jQuery); // END SAFETY

Reference URL