Skip to content

Instantly share code, notes, and snippets.

@Michael-1
Last active April 21, 2018 05:53
Show Gist options
  • Save Michael-1/5295ad559731c238a11a885328bedc5b to your computer and use it in GitHub Desktop.
Save Michael-1/5295ad559731c238a11a885328bedc5b to your computer and use it in GitHub Desktop.
On Stack Exchange, the accepted answer is only at the top if there is no other answer with more votes
// ==UserScript==
// Author Michael Schmid <michael.schmid@live.com>
// Forked from http://userscripts.org/scripts/show/57812
// @name Stack Exchange: sort answers by votes
// @namespace michael
// @description Accepted answer is only at the top if there is no other answer with more votes
// @include http://stackoverflow.com/questions/*
// @include http://serverfault.com/questions/*
// @include http://superuser.com/questions/*
// @include http://stackapps.com/questions/*
// @include http://*stackexchange.com/questions/*
// @include http://askubuntu.com/questions/*
// @include https://stackoverflow.com/questions/*
// @include https://serverfault.com/questions/*
// @include https://superuser.com/questions/*
// @include https://stackapps.com/questions/*
// @include https://*stackexchange.com/questions/*
// @include https://askubuntu.com/questions/*
// @include https://community.atlassian.com/*
// @version 1
// @grant none
// ==/UserScript==
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
};
function sortAnswers (a,b){
var aVotes = $(a).find('span.vote-count-post').text();
var bVotes = $(b).find('span.vote-count-post').text();
// Votes in descending order
if (parseInt(aVotes) > parseInt(bVotes)) return -1;
if (parseInt(aVotes) < parseInt(bVotes)) return 1;
// Secondarily, accepted answer goes first
if ($(a).hasClass('accepted-answer')) return -1;
// Tertiarily, sort by posting time
var aTime = $(a).find('div.user-action-time > span.relativetime').attr('title');
var bTime = $(b).find('div.user-action-time > span.relativetime').attr('title');
if (aTime > bTime) return 1;
if (aTime < bTime) return -1;
return 0;
}
$(function() {
// Do nothing if not sorting by “votes”
if ($('a.youarehere').attr('data-value') != 'votes') return;
// Let’s re-sort
var insertLocation = $('.pager-answers')[1];
if (!insertLocation)
insertLocation = $('#post-form').prev();
$('div.answer').sort(sortAnswers).each(function() {
$(this).prev().insertBefore(insertLocation);
$(this).insertBefore(insertLocation);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment