Show HN: JavaScript snippet to highlight new posts
Hi all. I wanted an easy way to highlight new posts, without basing it on the last time I visited a page. The snippet is as follows, if any of you folks would like to use it:
/**
* Usage: highlight('newpost', 3, 'hours');
*
* This will add the class 'newpost' to any post made within
* the past 3 hours. This includes, for example:
*
* 3 hours ago
* 45 minutes ago
* 22 seconds ago
*/
function highlight(className, number, type) {
var types = ['second', 'seconds',
'minute', 'minutes',
'hour', 'hours',
'day', 'days'];
// Types are inclusive, so if we filtered to 'minutes', then
// we always want posts that were made 'seconds' ago.
types = types.slice(0, types.indexOf(type) + 1);
// Any link with 'item?id' is assumed to be a timestamp.
var posts = document.querySelectorAll('a[href*="item?id"]');
// Loop through the number of posts, since we need to access
// each post using NodeList#item.
for(var i = 0; i < posts.length; i++) {
var post = posts.item(i);
try {
// The leftmost integer.
var label_number = parseInt(post.innerHTML.match(/^\d+/));
// The label (a value that maps up to the types array).
var label_type = post.innerHTML.match(/^\d+ (.+?) ago$/)[1];
}
catch(e) {
// If either of the matches fail, it's due to an
// irrelevant link.
continue;
}
// Continue if the label is out of bounds.
// For instance, 'days' when filtering by 'minutes'.
if(types.indexOf(label_type) === -1) continue;
// Continue if the label type matches, but the number
// is larger than what we're filtering for.
if(type === label_type && label_number > number) continue;
// td > div > span > a
post.parentNode.parentNode.parentNode.className += ' ' + className;
}
}
1 comment
[ 3.0 ms ] story [ 10.2 ms ] threadjavascript:void%20function(){function%20e(e,t,a){var%20n=%22.%22+e+'{%20padding-left:%2030px;background-image:%20url(%22http://www.fasttrackcalltaxi.co.in/ft_clickyourtaxi/App_Imag...),c.appendChild(d);var%20o=[%22second%22,%22seconds%22,%22minute%22,%22minutes%22,%22hour%22,%22hours%22,%22day%22,%22days%22];o=o.slice(0,o.indexOf(a)+1);for(var%20r=document.querySelectorAll('a[href*=%22item%3Fid%22]'),i=0;i%3Cr.length;i++){var%20s=r.item(i);try{var%20l=parseInt(s.innerHTML.match(/^\d+/)),u=s.innerHTML.match(/^\d+%20(.+%3F)%20ago$/)[1]}catch(m){continue}-1!==o.indexOf(u)%26%26(a===u%26%26l%3Et||(s.parentNode.className+=%22%20%22+e))}}e(%22newpost%22,3,%22hours%22)}();
Screenshot: https://s3.amazonaws.com/tz-www-misc/hn.highlighter.2015-02-...