patternjavascriptModerate
Bookmarklet for selecting code snippets on Code Review
Viewed 0 times
snippetsbookmarkletforselectingcodereview
Problem
The following code will add to each code block a 'Select Code' button that will select the code belonging to that block. Please review for maintainability.
In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/
I have tested this on FF and Chrome and it works for me.
In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/
javascript: if ($('button').length === 0) {
/* Stack Exchange does not do buttons, this does */
$(".prettyprint").each( function()
{
/* Thank you http://stackoverflow.com/a/2838358/7602 */
function selectCode(el, win)
{
win = win || window;
var 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();
}
}
var buttonText = 'Select Code',
length = buttonText.length,
codeBlock = this,
$link = $('' + buttonText + '').click(function()
{
console.log( $(codeBlock).text().substring( length ) );
selectCode(codeBlock);
});
$(codeBlock).prepend( $link );
});
}I have tested this on FF and Chrome and it works for me.
Solution
You inject the button using
jQuery.prepend(), which inserts the button as the first child of the .prettyprint code block. Therefore, when the bookmarklet is invoked, and it selects the contents of the code block, the "Select Code" button is inadvertently included in the selection. I recommend using jQuery.before() instead.Context
StackExchange Code Review Q#38336, answer score: 10
Revisions (0)
No revisions yet.