Skip to content

Instantly share code, notes, and snippets.

@olejorgenb
Last active April 7, 2024 14:32
Show Gist options
  • Save olejorgenb/ca230bdeb87bb5bc69a8bae3e7d604b5 to your computer and use it in GitHub Desktop.
Save olejorgenb/ca230bdeb87bb5bc69a8bae3e7d604b5 to your computer and use it in GitHub Desktop.
Highlight HN author
// bookmarklet_title: Highlight HN author
// https://chat.openai.com/c/496f4ddc-0151-40aa-af92-36897587d7ea
// Because I'm lazy
// Function to change the mouse cursor to something distinctive
function setDistinctiveCursor() {
document.body.style.cursor = 'crosshair';
}
// Function to reset the mouse cursor to default
function resetCursor() {
document.body.style.cursor = 'auto';
}
// Color palette
const colors = ['yellow', 'cyan', 'magenta', 'lime', 'orange', 'pink'];
// Function to handle the click event
function handleClick(event) {
// Prevent the default behavior of the click (e.g., following a link)
event.preventDefault();
// Get the clicked element
const clickedElement = event.target;
console.debug("Clicked", clickedElement);
// Check if the clicked element is an anchor (a) element
if (clickedElement.tagName === 'A') {
let colorIndex = window.__HLHNauthorColorIndex ?? 0;
// Get the href attribute value
const href = clickedElement.getAttribute('href');
// Create a CSS selector based on the href attribute value
const selector = `a[href="${href}"]`;
// Check if the style rule is already defined in the style element
const styleElement = document.querySelector('style');
if (styleElement && !styleElement.textContent.includes(selector)) {
// Define the CSS rule for the selector
styleElement.textContent += `${selector} { background-color: ${colors[colorIndex]}; }\n`;
}
// Set the background color for the clicked element and similar elements
const elements = document.querySelectorAll(selector);
elements.forEach((element) => {
element.style.backgroundColor = colors[colorIndex];
});
console.debug("Applied color", colors[colorIndex]);
// Cycle to the next color in the palette
window.__HLHNauthorColorIndex = (colorIndex + 1) % colors.length;
// Reset the mouse cursor
resetCursor();
}
}
// Function to highlight the next clicked element
function highlightNextClickedElement() {
// Set the distinctive cursor
setDistinctiveCursor();
// Define the click event listener as a separate function
function clickEventListener(event) {
handleClick(event);
// Remove the event listener after the first click
document.body.removeEventListener('click', clickEventListener);
}
// Add the click event listener
document.body.addEventListener('click', clickEventListener);
}
// Call the function to highlight the next clicked element
highlightNextClickedElement();
@olejorgenb
Copy link
Author

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