DOMRelocator Helper for Responsive Design

This is a nice little snip I created when in a bunch with a client who needed a DOM part to be higher up in the source order at particular break points, but not higher up in the source order under other responsive break points.

So, if in a bunch, if you can’t convince another developer or owner that the stacking rules would be a better approach, or if you just have no other choice. You can use this function:

Prams are as follows DOMRelocator(1,2,3,4):

  1. Target element you wish to move around
  2. Destination Element you wish to move the element to vs. where it comes from at page load.
  3. Pending Rule is how you want to append, prepend, insertBefore or insertAfter our Destination element.
  4. Break point is the pixel size at which this function should do its magic.

Under the Hood

  • Perform the relocation at both page load and window resize.
  • Resize function has been optimized to perform the DOM relocation at the last pixel iteration of a resize event, and not over every pixel.
  • Relocated element is a clone of the original (to retain bound events), while the original is just hidden from view during the relocation.

PLEASE DON’T USE THIS UNLESS (The following) YOU ABSOLUTELY HAVE NO OTHER CHOICE!

  • CSS wont do the trick, cause faking source order with position absolute ignores content height fluctuation.
  • Source order just absolutely can’t be change to either accommodate requirements from client over all responsive break points.
  • Client just wont bend their requirements in stacking, or original location of DOM element in question…
function DOMRelocator(target_elm,dom_destination,pending_rule,break_point){
	var orignal_elm = jQuery(target_elm);
	var clone = orignal_elm.clone(true,true);
	var dest = jQuery(dom_destination);
	var screen = jQuery(this).width();
	var insertType = (pending_rule)? pending_rule : 'append';

	//For Screen Size Change
	jQuery(window).bind('resize',function(){
		if(typeof resizewait != 'undefined'){
			clearTimeout(resizewait);
		}
		resizewait = setTimeout(function(){
			var screen = jQuery(this).width();
			if(screen <= break_point){
				orignal_elm.hide();
				if(insertType == 'insertBefore' || insertType == 'insertAfter'){
					clone[insertType](dest);			
				} else {
					dest[insertType](clone);
				}
			}else{
				orignal_elm.show();
				clone.remove();	
			}
		},200);
	});

	//For page load
	if(screen <= break_point){
		orignal_elm.hide();
		if(insertType == 'insertBefore' || insertType == 'insertAfter'){
			clone[insertType](dest);			
		} else {		
			dest[insertType](clone);
		}
	}else{
		orignal_elm.show();
		clone.remove();	
	}
}

Usage example

jQuery(function(){
	DOMRelocator('.the_element_to_move','#where_to_or_around_to_move_it','append',768);
});

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus