1
\$\begingroup\$

The following code will add to each code block on https://codereview.stackexchange.com/ or https://stackoverflow.com/ a 'Select Code' button that will select the code belonging to that block.

This was originally written in 2013, I adjusted it to the new CSS and exchanged var with let, otherwise I think it looks fine. However JS has changed a lot, so I am submitting it again.

The original code was reviewed here 7 years ago.

In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/

javascript: $('pre.s-code-block').not('button + *').each(function createButton() {
    /* Thank you http://stackoverflow.com/a/2838358/7602 */
    function selectCode(el, win) {
        win = win || window;
        let doc = win.document,
            sel, range;
        if (win.getSelection && doc.createRange) {
            sel = win.getSelection();
            range = doc.createRange();
            range.selectNodeContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (doc.body.createTextRange) {
            range = doc.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
    }
    let buttonText = 'Select Code',
        length = buttonText.length,
        codeBlock = this,
        $link = $('<button type=\'button\'>' + buttonText + '</button>').click(function buttonListener() {
            console.log($(codeBlock).text().substring(length));
            selectCode(codeBlock);
        });
    $(codeBlock).before($link);
});
/* Cross browser bookmarklet sorcery */
void(0);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.