0

$('button').on('click', function(){
    let selection = document.getSelection().toString().trim();
  document.execCommand('createLink', true, selection);
    
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class = 'parent' contentEditable = 'true'>
Lorem ipsum dolor sit amet google.com
</div>
<br>
<button>CLICK</button>

So make a selection from google.com and click the button.

google.com becames blue as it is a link, but click on it - doesn't work.

How to get a real clickable link from google.com with target = _blank, and cursor = pointer, if possible?

  • Because of content editable it will work as an editor, you can have 2 modes preview and editor both. – Just code Dec 03 '18 at 12:21
  • Possible duplicate of [Adding a target="\_blank" with execCommand 'createlink'](https://stackoverflow.com/questions/23811132/adding-a-target-blank-with-execcommand-createlink) – nemanja Dec 03 '18 at 12:22
  • @Justcode, `you can have 2 modes...` could you explain a bit, pls, or give me a reference? –  Dec 03 '18 at 12:25

3 Answers3

0

Links wrapped in an element that has contentEditable='true' will not work, because they are basicaly inside a "text editor".

Maybe you should try changing the contentEditable attribute on click so that it is set at false when the text is not focused / clicked.

Seblor
  • 6,947
  • 1
  • 25
  • 46
0

https://jsfiddle.net/rfy5hz8q/13/

working fiddle:

(function($){
    $('button').on('click', function(){
       let selection = document.getSelection().toString().trim();
       document.execCommand('insertHTML', false, '<a contentEditable="false" 
       href="' + selection + '" target="_blank">' + selection + '</a>');    
    })

})($)
Łukasz Blaszyński
  • 1,536
  • 1
  • 8
  • 13
0

Content editable works same as the you are working in any editor, get an example of stackoverflow editor,one way is to have editor and preview both, something like this.

$('button').on('click', function(){
    let selection = document.getSelection().toString().trim();
  document.execCommand('createLink', true, selection);    
})
$("#preview").on('click', function(){
 var value = $('.parent').attr('contenteditable');

    if (value == 'false') {
        $('.parent').attr('contenteditable','true');
        $('#preview').text("Preview")
    }
    else {
        $('#preview').text("Edit")
        $('.parent').attr('contenteditable','false');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class = 'parent' contentEditable='true'>
Lorem ipsum dolor sit amet google.com
</div>


<br>
<button>CLICK</button><button id="preview">Preview</button>
Just code
  • 13,553
  • 10
  • 51
  • 93