Created
May 15, 2025 05:26
-
-
Save boydaihungst/67c46467059cd086ec82e57f7d912266 to your computer and use it in GitHub Desktop.
YouTube Rich Grid: 4 Items Per Row
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name YouTube Rich Grid: 4 Items Per Row | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Forces the YouTube rich grid (like the homepage) to display 4 items per row by setting the --ytd-rich-grid-items-per-row CSS variable. | |
// @author Your Name | |
// @match *://www.youtube.com/* | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
// Function to apply the CSS variable | |
function applyGridStyle() { | |
// Find the rich grid element | |
const richGrid = document.querySelector('ytd-rich-grid-renderer'); | |
// If the element is found, set the CSS variable | |
if (richGrid) { | |
// console.log('Found ytd-rich-grid-renderer, setting --ytd-rich-grid-items-per-row to 4'); // Optional: for debugging | |
richGrid.style.setProperty('--ytd-rich-grid-items-per-row', '4'); | |
} | |
} | |
// --- Initial Application --- | |
// Apply the style when the script first runs in case the element is already present | |
applyGridStyle(); | |
// --- Observe for Dynamic Loading --- | |
// Use a MutationObserver to watch for changes in the DOM | |
// This is necessary because YouTube loads content dynamically (SPA) | |
const observer = new MutationObserver(function(mutations) { | |
mutations.forEach(function(mutation) { | |
// Check if any nodes were added | |
if (mutation.addedNodes.length > 0) { | |
// Re-apply the style. This function is safe to call multiple times; | |
// it will only do something if the element is found. | |
// We don't need to check mutation.addedNodes specifically for the grid, | |
// as applying the style globally if the grid exists is sufficient. | |
applyGridStyle(); | |
} | |
}); | |
}); | |
// Start observing the body for additions of new nodes or changes within its subtree | |
observer.observe(document.body, { | |
childList: true, // Observe immediate children additions/removals | |
subtree: true // Observe changes in the entire DOM subtree | |
}); | |
// Optional: You might want to disconnect the observer if navigating away, | |
// but for a single-page application like YouTube, keeping it active | |
// is usually fine and simpler. | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment