Reputation: 158
I am designing a web page in Joomla! and I run into a problem where I have an element I can't see that causes the page to scroll horizontally.
I'm completely useless with js and jQuery so can anyone help me with a script that will output to console all elements that have width larger than a specific value or larger than the browser window ? Or that can find in some other way which element causes the browser scroll horizontally ?
I would prefer a one line console script but a .js file will do also.
Upvotes: 8
Views: 6326
Reputation: 21421
What helped for me was running
$("body *").each(function() {
$(this).css('background-color', 'red');
});
on the console. This helped me identifying elements that caused the document width to grow beyond the window width. In my case we had elements moving in from the outside of the document (hello fancy websites). This said, there wasn't a single element that was wider than the window width. They where simply positioned outside the ordinary bounds.
Since I was already using <meta name="viewport" content="width=device-width, initial-scale=1.0">
, I ended up adding this CSS:
body {
overflow-x: hidden;
}
Upvotes: 2
Reputation: 509
JS Code to find elements larger than window width, use in browser console:
var maxWidth = document.documentElement.offsetWidth;
[].forEach.call(
document.querySelectorAll('*'),
function(el) {
if (el.offsetWidth > maxWidth) {
console.log(el);
}
}
);
if still this give you haddache, use a bit of extreme css:
body {
overflow-x: hidden;
}
Upvotes: 5
Reputation: 5068
I used
var outOfScreen = $('*').filter(function(){if($(this).width()>$(window).width())return true})
so then I could inspect the whole collection by accessing the outOfScreen
var.
Upvotes: 1
Reputation: 194
You not need a script. Open the page with Chrome, press F12 and in elements tab select each element, and you can see a each element in page with other color and width.
Upvotes: -1
Reputation: 1140
To get window width simply use:
$(window).width()
So to use ComFreek's example, to loop through elements wider than your window width you would write is like this:
$("*").each(function() {
if ($(this).width() > $(window).width()) {
console.log(this.tagName + "#" + this.id);
}
});
Upvotes: 5
Reputation: 29434
I suggest you to have a look in your browser's developer console. For example, Firefox can display you a nice 3D view!
If you really want to enumerate all elements whose width are greater than x in JavaScript, use this:
$("*").each(function() {
if ($(this).width() > 100) {
console.log(this.tagName + "#" + this.id);
}
});
Use document.body.clientWidth
for x if you want to compare against the body's visible width.
Upvotes: 18