Accelerator User Interface in JavaScript

Is it possible to create something like an Internet Explorer accelerator using JavaScript on the client side?

I want the displayed icon to appear when the user selects any text on the page.

What event should I expect?

+3
source share
2 answers

Essentially, the idea is to handle the event document.onmouseupappropriately, show the hidden “accelerator”, divand extract the selected text.

I think the following sample will be a good starting point for you:

<html>
<head>
    <script>
        function getSelectedText() {
            var selection = '';
            if (window.getSelection) selection = window.getSelection().toString();      
            else if (document.getSelection) selection = document.getSelection();                
            else if (document.selection) selection = document.selection.createRange().text;
            return selection;
        }

        function showAccelerator(x, y){
            var text = getSelectedText();
            if (text !== ''){
                accelerator.style.display = '';
                accelerator.style.left = x;
                accelerator.style.top = y;
                timeout_id = setTimeout(hideAccelerator, 1000);
            } else {
                hideAccelerator()
            }
        }

        function hideAccelerator(){
            clearTimeout(timeout_id);
            accelerator.style.display='none';
        }

        function isAcceleratorHidden(){
            return accelerator.style.display === 'none';
        }

        function onMouseUp(evt){
            if (isAcceleratorHidden()){
                var event2 = (document.all) ? window.event : evt;
                showAccelerator(event2.clientX, event2.clientY);
            }
        }

        function alertSelection(){
            alert(getSelectedText());
        }

        document.onmouseup = onMouseUp;
    </script>
</head>
<body>
    <div id="accelerator" style="position: absolute; width: 100px; left: 0px; top: -50px; display: none; border: solid; background-color : #ccc;">
        accelerator div<input type="button" value="alert" onclick="alertSelection();" />
    </div>
    <p>
        sometext<br/><br/><br/>
        even more text
    </p>
</body>
</html>
+2
source

, - mouseup , , ,

function hasSelection() {
  var selText = "";
  if (document.selection) { // IE
    selText = document.selection.createRange().text;
  } else () { // Standards-based browsers
    selText = document.getSelection();
  }
  // This simple example does not include legacy browsers like Netscape 4, etc.
  if (selText !== "") {
    return true
  }
  return false;
}

, . Boolean , .

attachEvent IE addEventListener Firefox, et. al mouseup.

+1

Source: https://habr.com/ru/post/1736882/


All Articles