JavaScript – Readout selected sentence and search on Wiki

この記事は約4分で読めます。

JS coding memo from book reading and studying.

Tiny JavaScript that completes following:

  • Readout selected sentence from a document
  • That selected sentence can be searched by Wikipedia.
<!DOCTYPE html>
  <head>
    <script>
      function getSelectedText(){ 
        if (window.getSelection){ 
           return window.getSelection().toString();
        } else if (document.getSelection) {
           return document.getSelection();
        }else if (document.selection) { 
           return document.selection.createRange().text;
        }
      }
   </script>
  </head>
<body>
  <h1>
    <a href="javascript: var q; 
            if (window.getSelection) q = window.getSelection().toString(); 
            else if (document.getSelection) q= document.getSelection();
            else if (document.selection) q = document.selection.createRange().text; 
            void window.open('http://en.wikipedia.org/wiki/' + q);
     ">
    Look up selected text in wiki</a>
  </h1>
  <div><img src="images/first-item1_pic.jpeg" alt="" style="width:10%;" /></div>        
  <div>At Hong Kong</div>       
  <div>Beautiful European buildings near the shuttle station.</div> 
  <div><img src="images/first-item3_pic.jpeg" alt="" style="width:10%;" /></div>        
  <div>Tagaytay city near Metro Manila</div>        
  <div>It was my 4th visit to Tagaytay which is very familier as closest mountains near Manila.</div> 
  <div><img src="images/first-item4_pic.jpeg" alt="" style="width:10%;" /></div>        
  <div>Very cute Pinoy kids at Halloween</div>        
  <div>Three little Philipino boys who wear Halloween costumes.</div>  
 </body>
</html>
タイトルとURLをコピーしました