I want to be able to identify if selected text contains a URL - the idea is that once a user selects text within a content editable div if it contains a URL - the URL is displayed in another content editable div to allow them to make corrections to the URL. Then if they make changes to the URL it then updates the <a href>.
I have currently created the code to allow the users to select any text and create a link its just the amendments thats causing the problem.
The code below is a section of my code where when the user selects an element of text it assigns # as the URL then they can write a http:// link into a content editable div called #link once the user has entered a http:// link it then updates # with the link.
document.getElementById("insertHTML").onclick = function(e) {
var sText =document.getSelection();
document.execCommand('insertHTML', false, '' + sText + '');
};
var contents = $('#link').html();
$('#link').blur(function() {
if (contents!=$(this).html()){
contents = $(this).html();
document.getElementById('data_link').setAttribute('href', contents);
document.getElementById('data_link').setAttribute('id', contents);
}
$('#link').empty();
});
any ideas would be great had no luck with anything online so far
Thanks Everyone :)
Jsfiddle
Select some text, you'll see it appears in the alert. You can uncomment the line with the url, make it your own url and place the text wherever you want it, I simply placed it where I did as an example of how you would implement this. When the text is selected, it will bring you to that url.
If you want to create an input type="button" id="myInputButtonId" etc to link to another page, then use
$("#myInputButtonId").on('click', function(){
instead of
$("#writtenstuff").on('mouseup', function () {
HTML
<div id="writtenstuff">
<p>The quick brown fox jumps over the lazy dog</p>
</div>
JS
$("#writtenstuff").on('mouseup', function () {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
if (text != "" && text != " ") {
alert(text);
//window.location.href = "http://www.someurl.com/"+text;
}
});
Related
I'm working on a chrome extension and I want to do something with the text that is selected (highlighted by the user) on the page. For that, I need a way to remove the selected text, for example text inside an input field.
I found a way to "clear" the selected text, meaning it will be unselected:
Clear Text Selection with JavaScript But it doesn't seem to be what I'm looking for.
This just removes the highlighting from the text:
window.getSelection().empty();
I want to remove the text that is selected, if it's editable text. Is this possible with JavaScript?
You can use the deleteFromDocument method:
window.getSelection().deleteFromDocument()
This will immediately remove the selected content from the document, and as such also clear the selection.
As described formally in the MDN web docs:
The deleteFromDocument() method of the Selection interface deletes the selected text from the document's DOM.
If you'd like to be able to delete text from input elements instead, you need to use different APIs:
var activeEl = document.activeElement;
var text = activeEl.value;
activeEl.value = text.slice(0, activeEl.selectionStart) + text.slice(activeEl.selectionEnd);
Edit from me, Synn Ko: to cover input fields, textareas and contenteditables, use this:
var selection = window.getSelection();
var actElem = document.activeElement;
var actTagName = actElem.tagName;
if(actTagName == "DIV") {
var isContentEditable = actElem.getAttribute("contenteditable"); // true or false
if(isContentEditable) {
selection.deleteFromDocument();
}
}
if (actTagName == "INPUT" || actTagName == "TEXTAREA") {
var actText = actElem.value;
actElem.value = actText.slice(0, actElem.selectionStart) + actText.slice(actElem.selectionEnd);
}
I am really struggling with this.
I have two div on a page. The first one has got contents (mainly text). On the second div, I want to display the content of first div based on the position. for example if i select line 30, then the content of that line will be displayed in second div. Is there any idea to do that?
Thank you
This answer assumes you only want to copy the selected text to the new div and provices a basic idea how you can do so
In order to achieve that kind of behaviour you need to listen to the mouseup event in your container where you want text to be selected. That way we assume, that the user was selecting something and ended the selection.
I have prepared this JS fiddle for you: https://jsfiddle.net/djzkcw0m/
Code for the prove of concept:
HTML
Highlight some text with mouse in this container:
<div id="test">
This is some text and you can highlight it with your mouse
</div>
Result div:
<div id="result"></div>
JS
const testDiv = document.getElementById('test');
const resultDiv = document.getElementById('result');
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
testDiv.addEventListener('mouseup', function(e) {
const selectedText = getSelectionText();
resultDiv.textContent = selectedText;
})
note
Method "getSelectionText()" is found from a related question Get the Highlighted/Selected text
I am trying to make a content editable div that can be used to generate message templates for an app. Users can append placeholders for fields like names to a template by hitting a button. The placeholders can be removed by hitting an 'x' on them as well. Here's the working snippet.
var removePlaceholder = function(e){
e.parentNode.parentNode.removeChild(e.parentNode);
}
var appendPlaceHolder = function(field){
var e = document.getElementById("t");
e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span>')
}
.tag {
background-color : blue;
color : white;
}
.remove {
color : red
}
<div id="t" contenteditable="true">Hello</div>
<button onclick=appendPlaceHolder("first_name")>Add first name</button>
The contenteditable part works just fine. But after I've added a placeholder using my appendPlaceHolder function, everything I type seem to get appended to the last inserted HTML element.
How can I prevent this. I have closed the tag properly. Is there any way to change this behaviour.
To recreate issue, run the snippet and hit the "Add First Name" Button, then continue typing in the area.
Update
Have added image to explain the situation
What you can do is add a space after the placeholder has been appended:
JavaScript
var removePlaceholder = function(e){
e.parentNode.parentNode.removeChild(e.parentNode);
}
var appendPlaceHolder = function(field){
var e = document.getElementById("t");
e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span> ')
}
Note: The which has been added at the end of the span just creates a space.
Live Example
JSFiddle
I have got a button 'edit description' when I click on it text disappear and appear
if (id == 'commedit') jQuery(this).html('<textarea>'+jQuery(this).text()+'</textarea>');
else if (id == 'commsave') {
jQuery(this).text(jQuery(this).find('textarea').val());
}
In MySql I have this text - "tetee<br>afafaf<br>afafaf<br>afsafsasfasf" in view it dispays with line breaks but when I click 'edit' in text area which come with Jquery text appear without lines and when I click save it also appear in my description field in one long line without line breaks. So I need your help
<br> are html breaks. You want \n in a textarea.
jQuery(this).html().replace(/<br>/gi,"\n")
When you save, you want to change it back to breaks and use html() instead of text();
var elem = jQuery(this);
if (id === 'commedit') {
var text = jQuery(this).html().replace(/<br>/gi,"\n");
elem.html('<textarea>'+ text +'</textarea>');
} else if (id === 'commsave') {
var html = elem.find('textarea').val().replace(/\n/g,"<br>");
elem.html(html);
}
JSFiddle Example
I want to implement readmore/less feature. i.e I will be having html content and I am going to show first few characters from that content and there will be a read more link in front of it. I am currently using this code :
var txtToHide= input.substring(length);
var textToShow= input.substring(0, length);
var html = textToShow+ '<span class="readmore"> … </span>'
+ ('<span class="readmore">' + txtToHide+ '</span>');
html = html + '<a id="read-more" title="More" href="#">More</a>';
Above input is the input string and length is the length of string to be displayed initially.
There is an issue with this code, suppose if I want to strip 20 characters from this string:
"Hello <a href='#'>test</a> output", the html tags are coming between and it will mess up the page if strip it partially. What I want here is that if html tags are falling between the range it should cover the full tag i.e I need the output here to be "Hello <a href='#'>test</a>" . How can I do this
Why not just hide the hidden part of the content instead of adding it later? I usually just use a display: none for hidden content and have it set to display: block when the read more is clicked..
Edit:
I'm sorry I didn't read the question good enough.
This should work though:
<div id="test">
This links to google
<strong>and</strong> some random text to make it a little bit longer!
</div>
<script type="text/javascript">
$(document).ready(function() {
var max_length = 21;
var text_to_display = "";
var index = 0;
var full_contents = $("#test").contents();
// loop through contents, stop after maxlength is reached
$("#test").contents().each(function(i) {
if ($(this).text().length + text_to_display.length < max_length) {
text_to_display += $(this).text();
index++;
} else {
return false;
}
});
// second loop removes unwanted content
$("#test").contents().each(function(i) {
if (i > index) {
$(this).remove();
}
return true;
});
// add link to show the full text
$('read more...').click(
function(){
$("#test").html($(full_contents));
$(this).hide();
}).insertAfter($("#test"));
});
</script>
This can be accomplished quite easilly using jQuery
<div id="test">This is a link to google</div>
<script type="text/javascript">
$(document).ready(function() {
alert($("#test").text());
});
</script>
Good luck!
You stated that the html tags would become an issue, so why not remove in the string conversion and replace with plain text, then on the Show More click, Toggle plain + Html
$(document).ready(function(){
var Contents = $('#post p'); //Object
var Plain = Contents.text(); //truncate this
//Hide the texts to Contents
Contents.hide();
var PlainContainer = $("<div>").addClass("Plain_Container").val(Plain)
//Add PlainContainer div after
Contents.append(PlainContainer);
var $('.show_hide').click(function(){
$(Plain_Container).remove(); //Delete it
Contents.Show(); //Show the orginal
$(this).remove(); //Remove the link
return false; //e.PreventDefault() :)
});
});
This way using the text() function will convert html tags to there values and remove the tag itself, all you have to do is toggle them :)
Note: The code above is not guaranteed to work and is provided as example only.