User:Zack/Collapsable posts userscript.js

From BlogNomic Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// ==UserScript==
// @name           BlogNomic Collapsable Posts
// @author         TheOnlyZac
// @namespace      blognomic
// @version        1.0
// @description    Makes posts collapsable on the BlogNomic main page.
// @include        https://*blognomic.com/
// @grant          GM_getValue
// @grant          GM_setValue
// @grant          GM_log
// @require        http://code.jquery.com/jquery-1.11.2.min.js
// ==/UserScript==
var $ = window.jQuery;

(function() {
    'use strict';

    $('.post').each(function(i) {
        var $this = $(this);
        if ($this.hasClass('stickypost')) return; // ignore stickied posts

        var $title = $this.find('.post-title');
        var $body = $this.find('.post-body');
        var $footer = $this.find('.post-footer');

        var $btn = $(document.createElement('div')); // create expand/collapse button
        $btn.addClass('collapse-btn');
        $btn.text("◂");
        $btn.css({
            "float": "right",
            "width": "20px",
            "height": "20px",

            "text-align": "center",
            "color": "black",
            "background-color": "#f0f0f0",

            "border": "1px solid black",
            "border-radius": "2px",

            "user-select": "none",
            "cursor": "pointer"
        });

        $btn.content = $body;
        console.log($btn.content);

        var $newFooter = $footer.detach();
        $this.append($newFooter); // move footer out of post body
        $body.hide(); // hide post body by default

        $this.prepend($btn) // add expand/collapse button
    });
})();

$(document).on('click', '.collapse-btn', function() {
    var $this = $(this);
    var $postBody = $this.parent().find('.post-body');
    $postBody.toggle('fast');

    if ($this.text() == '◂') $this.text('▾');
    else $this.text('◂');
});