HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Clearing the text when `text select` release

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thetextclearingreleasewhenselect

Problem

I required a trigger, whenever the window text selection cleared.
Finally I found this approach.

Using the same id, I have added multiple event handlers, but I am not sure my work is the best.

Is there a better way to do this?

$('#tenderContent').on('mouseup', '.tenderdocument', function (e) {
    e.stopPropagation();
    if ($.trim(window.getSelection().toString()).length) {
        $('#text').text(window.getSelection().toString());
    }

});

$('#tenderContent').on('mousemove', '.tenderdocument', function (e) {
    e.stopPropagation();
    if (!$.trim(window.getSelection().toString()).length) {
         $('#text').empty();
    }
});


LiveDemo

Solution

The jQuery $.on(); event listener can use 2+ events in its event listener parameter and then let you specify which one through e.type. This allows us to shorten a lot of code. With that in mind, we can also shorten your $.trim(window.getSelection().toString()).length to be $.trim('' + window.getSelection()) and assign it to a variable for use in our if's. We can then further simplify it by testing for e.type being 'mouseup' and if it's evaluates to false, it has to be 'mousemove'. And so we don't have nested if's, we can just use logical AND and OR operators to do something if it even has a value, and something else if it doesn't. That brings your code down to this:

$('#tenderContent').on('mouseup mousemove', '.tenderdocument', function(e) {
  e.stopPropagation();
  var selection = $.trim('' + window.getSelection());
  if ('mouseup' == e.type) {
    selection && $('#text').text(selection);
  } else {
    selection || $('#text').empty();
  }
});


That is a major cut off the amount that you had before. It also simplifies a lot of stuff to be fast and efficient.

Code Snippets

$('#tenderContent').on('mouseup mousemove', '.tenderdocument', function(e) {
  e.stopPropagation();
  var selection = $.trim('' + window.getSelection());
  if ('mouseup' == e.type) {
    selection && $('#text').text(selection);
  } else {
    selection || $('#text').empty();
  }
});

Context

StackExchange Code Review Q#78406, answer score: 2

Revisions (0)

No revisions yet.