To resolve the issue "Make sure the page width matches the viewport width" flagged by Hubspot SEO tools, you need to ensure that the viewport width always the same like the page width. You can do that through ensuring that all elements on your website are responsive to the screen width, but when you have hundreds of pages that have such a problem and you don't have the time and resources to resolve this problem, then you can try the following javascript hot fix.
Creating a match between page width and viewport width largely depends on the specifics of the website's design. However, a JavaScript solution can be used to dynamically adjust the viewport settings based on the window's dimensions. Below is an example of how you might use JavaScript to adjust the viewport settings:
function updateViewport() {
const viewportMeta = document.querySelector('meta[name=viewport]');
let scaleValue = 1;
const windowWidth = window.innerWidth;
if (windowWidth <= 320) {
scaleValue = 0.8;
} else if (windowWidth <= 480) {
scaleValue = 0.9;
} else if (windowWidth <= 768) {
scaleValue = 1;
} else if (windowWidth <= 1024) {
scaleValue = 1.1;
}
const contentValue = `user-scalable=yes, initial-scale=${scaleValue}, maximum-scale=2.0, width=device-width`;
viewportMeta.setAttribute('content', contentValue);
}
function handleResize() {
clearTimeout(handleResize.timeoutId);
handleResize.timeoutId = setTimeout(updateViewport, 100); // Debounce resize events
}
// Ensure there's a viewport meta tag
if (!document.querySelector('meta[name=viewport]')) {
const meta = document.createElement('meta');
meta.name = 'viewport';
document.head.appendChild(meta);
}
window.addEventListener('orientationchange', updateViewport);
window.addEventListener('resize', handleResize);
document.addEventListener('DOMContentLoaded', updateViewport);
In this code:
updateViewport
is defined to adjust the viewport
meta tag's content
attribute based on the current window width.updateViewport
, the initial-scale
value is adjusted based on breakpoints defined for various window widths.handleResize
function is used to debounce resize events, ensuring that updateViewport
is not called excessively during rapid resizing or orientation changes.orientationchange
, resize
, and DOMContentLoaded
events to ensure the viewport settings are updated whenever necessary.This script provides a dynamic approach to adjust the viewport settings, which may help in better matching the page width and viewport width. However, it's crucial to tailor the breakpoint values and scale values according to your specific design requirements and ensure that your CSS is also designed to handle varying viewport sizes appropriately.