最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript - select all text inside a ‘pre code block’ on double-click - Stack Overflow

programmeradmin1浏览0评论

I have some code block on my blog; I want that when someone double-click on a code block, all code of that code block need to be selected.

Please look at the code below (this is what I’ve got so far, though it is using jQuery). Now is it do-able with native JavaScript( without jQuery ) ?

Sorry If I've asked a dumb question, I’m new at these things. :)

<script type="text/javascript" src=".12.0.min.js"></script>
<style>
pre.highlight {
    border: 1px solid #ccc;
    padding: 10px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
    // select all code on doubleclick
    $('pre.highlight').dblclick(function() {
        $(this).select();

        var text = this,
            range, selection;

        if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    });
});
</script>
<pre class="highlight"><code>.button-css {
    cursor: pointer;
    border: none;
    background: #F2861D;
    padding: 3px 8px;
    margin: 7px 0 0;
    color: #f4f4f4;
}</code></pre>
<pre class="highlight"><code> #slider {
     border-color: #c0c0c0;
     border-radius: 5px 5px 5px 5px;
     border-style: solid;
 }</code></pre>

I have some code block on my blog; I want that when someone double-click on a code block, all code of that code block need to be selected.

Please look at the code below (this is what I’ve got so far, though it is using jQuery). Now is it do-able with native JavaScript( without jQuery ) ?

Sorry If I've asked a dumb question, I’m new at these things. :)

<script type="text/javascript" src="https://code.jquery./jquery-1.12.0.min.js"></script>
<style>
pre.highlight {
    border: 1px solid #ccc;
    padding: 10px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
    // select all code on doubleclick
    $('pre.highlight').dblclick(function() {
        $(this).select();

        var text = this,
            range, selection;

        if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    });
});
</script>
<pre class="highlight"><code>.button-css {
    cursor: pointer;
    border: none;
    background: #F2861D;
    padding: 3px 8px;
    margin: 7px 0 0;
    color: #f4f4f4;
}</code></pre>
<pre class="highlight"><code> #slider {
     border-color: #c0c0c0;
     border-radius: 5px 5px 5px 5px;
     border-style: solid;
 }</code></pre>

Share Improve this question asked Feb 9, 2016 at 17:06 Shuvojit DasShuvojit Das 1932 silver badges10 bronze badges 4
  • Can you add sample HTML as well. A jsFiddle would be useful – Thangaraja Commented Feb 9, 2016 at 17:09
  • do you want to get it with native javascript? – RomanPerekhrest Commented Feb 9, 2016 at 17:16
  • You might find some useful code in my greasemonkey script. Full details at my stackapps post. – rojo Commented Feb 9, 2016 at 17:26
  • Yes I want to achive that with native JavaScript @RomanPerekhrest – Shuvojit Das Commented Feb 9, 2016 at 17:30
Add a ment  | 

4 Answers 4

Reset to default 4

Your code works fine in Jquery.
To get the "native javascript" version go through the following steps:

  • replace jquery's $(document).ready handler with native window.onload
  • work with event target e.target instead of jquery's this
  • instead of adding an event handler for each element with class="highlight" use advanced technic which is adding the event listener to the parent element once and considering only needed pre or code elements (related to class="highlight")

    window.onload = function(){
    
        document.body.addEventListener('dblclick', function(e){
           var target = e.target || e.srcElement;        
           if (target.className.indexOf("highlight") !== -1 || target.parentNode.className.indexOf("highlight") !== -1){
                var range, selection;
    
                if (document.body.createTextRange) {
                    range = document.body.createTextRange();
                    range.moveToElementText(target);
                    range.select();
                } else if (window.getSelection) {
                    selection = window.getSelection();
                    range = document.createRange();
                    range.selectNodeContents(target);
                    selection.removeAllRanges();
                    selection.addRange(range);
                }
                e.stopPropagation();
           }              
    
        });
    };
    

https://jsfiddle/8nba46x8/

Converting jQuery to JavaScript for your code is easy, you did the hard part already.

var srcBox = document.querySelector(".sourceBox");

srcBox.addEventListener("dblclick", hiLite, false);

  • Wrap the content in another container (.sourceBox) because the most efficient way to handle multiple event listeners is to place the one event listener on the parent of all of the event.targets (the element where the event originated from, or simply the element that was actually clicked).

if (e.target !== e.currentTarget)

  • Even though the event.target would be one of the pre elements but the listener is on the parent, we can still find the correct pre element by checking if it's not the event.currentTarget (.sourceBox) in the event chain as it probigates (and stops short of event.currentTarget) and bubbles (and stops short of event.currentTarget). The normal event chain is stopped short because of the false parameter of the event listener and the e.stopPropagation(); placed at the very end of the function hiLite (event handler)

var text = e.target;

  • Singling out the correct event.target allows us to use this more or less. I believe that this in this context is still .sourceBox which in this situation is useless, which is why we're using event.target

As you can see this is one of the many reasons why many prefer jQuery over JavaScript. I'm a masochist so naturally I prefer JavaScript.

Now that my incoherent ramblings have thoroughly confused you, here's an article that explains it better than I can.

var srcBox = document.querySelector(".sourceBox");

srcBox.addEventListener("dblclick", hiLite, false);

function hiLite(e) {
  if (e.target !== e.currentTarget) {
    var text = e.target;
    var range, selection;

    if (document.body.createTextRange) {
      range = document.body.createTextRange();
      range.moveToElementText(text);
      range.select();
    } else if (window.getSelection) {
      selection = window.getSelection();
      range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }
   e.stopPropagation();
}
  pre.highlight {
    border: 1px solid #ccc;
    padding: 10px;
  }
  .sourceBox {
    border: 2px inset #222;
    padding: 1px 15px;
  }
<section class="sourceBox">
  <pre class="highlight"><code>.button-css {
    cursor: pointer;
    border: none;
    background: #F2861D;
    padding: 3px 8px;
    margin: 7px 0 0;
    color: #f4f4f4;
}</code></pre>
  <pre class="highlight"><code> #slider {
     border-color: #c0c0c0;
     border-radius: 5px 5px 5px 5px;
     border-style: solid;
 }</code></pre>
</section>

For pre or any tag one can select all text inside that tag by this simple code. It will highlight the entire tag area with yellow colour and select text inside it on single click.

document.onclick = function(event) {
    var range, selection;
event.target.style.backgroundColor = 'yellow';
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(event.target);
        selection.removeAllRanges();
        selection.addRange(range);
};

Here is the code to implement the same functionality in native javascript :

<script type="text/javascript">
    function selectText(containerid) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById(containerid));
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(document.getElementById(containerid));
            window.getSelection().addRange(range);
        }
    }
</script>

To use the above function you can write in HTML like this :

<div id="selectable" ondblclick="selectText('selectable')">This is a test div.</div>
发布评论

评论列表(0)

  1. 暂无评论