Skip to content

Instantly share code, notes, and snippets.

@CurtisL
Created March 25, 2016 20:58
Show Gist options
  • Save CurtisL/48785f0be175ebb2cd46 to your computer and use it in GitHub Desktop.
Save CurtisL/48785f0be175ebb2cd46 to your computer and use it in GitHub Desktop.
Script that logs and highlights elements that are out of bounds and may be causing unexpected horizontal scroll. Requires jQuery and is in no way optimized.
/**
* Sometimes you get horizontal scroll on a page,
* but can't find the element causing it.
*
* This scrapes the DOM and checks to see if any
* right edge of an element is beyond the width
* of a defined container.
*/
(function($){
// change container to the selector to look within
var container = 'body';
var content_width = $(container).outerWidth();
var skip_contents = [];
// NOT EFFICIENT! Just get the job done.
var count = 0;
var found = 0;
var ignored = 0;
var out_of_bounds = [];
$.each($('*', container), function(){
count++;
var $this = $(this);
if (!beingSkipped($this)) {
// skip elements that won't have scroll
if ($this.css('overflow') == 'hidden') {
skip_contents.push(this);
}
var $el_right_edge = $this.outerWidth() + $this.offset().left;
if ($el_right_edge > content_width) {
$this.css({
outline: '4px dotted red',
});
found++;
out_of_bounds.push($this);
};
} else {
ignored++;
}
});
function beingSkipped($element){
var skip = false;
$.each(skip_contents, function(k, v){
if( $element.closest(v).length > 0 ) {
skip = true;
}
});
return skip;
}
console.table([{
"Scanned Elements": count,
"Out-of-bounds": found,
"Skipped Contents": skip_contents.length,
"Didn't Scan": ignored
}]);
console.log("Skipped Children Of: ", skip_contents)
console.log("Elements out of bounds: ", out_of_bounds);
})(jQuery);
@CurtisL
Copy link
Author

CurtisL commented Mar 25, 2016

Since this is just a tool for debugging, I just paste in console and run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment