views:

39

answers:

2

Can I create something like an Internet Explorer accelerator using JavaScript on the client-side?

I want a clickable icon to show up when the user selects some text on the page.

What is the event I should wait on?

+1  A: 

Probably the best way is to set a mouseup listener on the page which calls a function that tests for a selection, like

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;
}

You could change this to return the selection and manipulate it in other ways. But the Boolean returned here could determine whether or not your button shows up.

Use attachEvent for IE and addEventListener for Firefox, et. al, and listen for the mouseup event.

Robusto
+1  A: 

In essence the idea is to handle document.onmouseup event appropriately, show your hidden "accelerator" div and retrieve the text selected.

I guess 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>
Li0liQ