Remove a portion of text using javascript - javascript

Here's the code:
function bold() {
var text = document.getElementById("post-body");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
var text = '**';
$('#post-body').val(function(_, val) {
return val + text + t + text;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;"></textarea>
<div>
<button id="bold" value="**" onclick="bold()">B</button>
</div>
What I am trying to do is similar to how comments on Stack Overflow work: you highlight text in the text box, and click a button. The button then appends and prepends the proper syntax to the text. I am able to apply the proper syntax, but the highlighted text is duplicated.
I know it's because in my code, I have
return val + text + t + text;
where val is all of the text in the textarea, and t is the highlighted text, but I'm not sure how to remove the highlighted text from val and add the new version in the form of t.
Any help would be greatly appreciated.

You can record the text before and after and then return the text before, the selection and the text after.
function bold() {
var text = document.getElementById("post-body");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
var before = text.value.slice(0, text.selectionStart);
var after = text.value.slice(text.selectionEnd);
var text = '**';
$('#post-body').val(function(_, val) {
return before + text + t + text + after;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;">Select some text here.</textarea>
<div>
<button id="bold" value="**" onclick="bold()">B</button>
</div>

Related

Problems targeting the correct div id with dynamically (javascript) created divs

I'm having troubles targeting the correct div id with dynamically (javascript) created divs.
How it should function..
Each time you press the add text button a new text input is created with an incrementing id
When you type into this box the text appears in the results div
The same will repeat each time you press the add text button.
So far all of the above functions as I would expect.
The problem..
When you add a second text then try to edit the first text the id is wrong so the first text does not update.
How can I make this function as expected so no matter how many texts you add you can edit a previous one and it updates the correct id?
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext();\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext() {
document.getElementById("showtext" + (textcount)).innerText = (textcount) + ") " + document.getElementById("textarea" + (textcount)).value;
//console log id when typing to see what id is being targeted
console.log(textcount);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>
When you was getting the id to use, you was getting the number of the index. Like length. You was getting the last number. I changed a little and it worked, see below:
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext(event);\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext(e) {
var ideditaded = e.target.getAttribute("id").replace("textarea", ""); // get the id of what you are editing and remove the textarea to get only its textcount.
document.getElementById("showtext" + (ideditaded)).innerText = (ideditaded) + ") " + document.getElementById("textarea" + (ideditaded)).value;
//console log id when typing to see what id is being targeted
//console.log(ideditaded);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>

Highlight matched text

I want to implement highlight feature of Notepad++ in HTML, where notepad++ highlights selected words if found in the file. I have been able to mimic a bit only where the highlight happens only on a mouse click in the same div.
I want to change it so the highlight happens in div2 when text is selected in div1 and is found in div2, else div2 is same as div1. Also it should work except any mouse click and with multi words.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>highlight matching text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.found {
color: red;
}
</style>
<script>
function replaceText() {
$("#div1").find(".found").removeClass("found");
var searchword = $("#searchtxt").val();
var custfilter = new RegExp(searchword, "ig");
var repstr = "<span class='found'>" + searchword + "</span>";
if (searchword != "") {
$('#div1').each(function() {
$(this).html($(this).html().replace(custfilter, repstr));
})
}
}
</script>
</head>
<body>
<input type="text" id="searchtxt" placeholder="keyword" />
<input type="button" value="search" onClick="replaceText();" id="highlightButton" />
<p id="div1">I'm here but not here. Not here also. But I'm here too.</p>
<p id="div2"> </p>
</body>
</html>
Try this:
const div1 = document.getElementById("div1"),
div2 = document.getElementById("div2"),
isParent = (obj, parent) => !obj || obj === parent ? obj : isParent(obj.parentNode, parent);
/*
isParent is a short version of:
function isParent(obj, parent)
{
if (!obj || obj === parent)
{
return obj;
}
else
{
return isParent(obj.parentNode, parent);
}
}
*/
div1.addEventListener("click", e =>
{
const sel = document.getSelection();
/*
sel.anchorNode: element the selection started at
sel.focusNode: element the selection ended at
we only accept selection of div1 text
check if both of these elements are children of div1, otherwise exit
*/
if (!isParent(sel.anchorNode, div1) || !isParent(sel.focusNode, div1))
return;
const text = sel.toString() //get selected text
.trim() //trim trailing white spaces
//make it html friendly
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
//make it regex friendly
.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
if (text === "")
return;
div2.innerHTML = div2.innerHTML
//remove old highlightings
.replace(/<mark>([^<]*)?<\/mark>/g, "$1")
// convert selected text into regex,
// search and enclose found strings with <mark></mark>
.replace(new RegExp("(" + text + ")", "gi"), '<mark>$1</mark>'); //add new highlighting
});
/*
second paragraph marks
*/
p:first-child + p mark {
background-color: lightgreen;
}
#div1, #div2
{
border: 1px solid black;
padding: 1em;
}
#div2
{
background-color: #E0E0E0;
margin-top: -1px;
}
<div id="div1">
<p>I'm here but not here. Not here also. But I'm here too. <span>blah</span></p>
</div>
<div id="div2">
<p>But I'm here too. <span>blah</span> <span>blah</span></p>
<p>And also here.</p>
<p>Third paragraph, has "And also here."</p>
</div>

How to change the color of a string before inserting it at the current position of the cursor

I get this output while trying to change the color of the string I would like to add in my editor.
The css part is not taken into account. It is added as a simple html. What could be the problem ?
some text <font color="green">ADD THIS VALUE</font> some text and ...
Here are the add functions
function add_str(event) {
event.preventDefault()
var elt = document.getElementById("text_write");
insertAtCursor(elt, "ADD THIS VALUE");
}
function insertAtCursor(myField, myValue) {
myValue = myValue.fontcolor("green");
if (myField.setRangeText) {
myField.setRangeText(myValue)
} else {
document.execCommand('insertText', false, myValue);
}
}
and the html part
<button onmousedown="add_str(event)">
add srting
</button>
<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text and ...</div>
Thank you in advance
function add_str(event) {
event.preventDefault()
var coloredstring = "ADD THIS VALUE"
var colorofstring = "green"
var node = document.getElementById("text_write")
var addedstring = '<span style="color:' + colorofstring + '">' + coloredstring + '</span>'
node.innerHTML = node.innerHTML + addedstring
}
<button onmousedown="add_str(event)">
add srting
</button>
<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">some text some text and ..</div>
font tag no longer works on html5, i did a little hack using a span tag

How do you make a button that marks the same word in two div in JS?

illustration of the execution of the button:
You can add mark tag in your Html code with JS. But mark tag works only in HTML5. It will be okay in new Browsers.
Forexample this is your html code:
<div>
Word1 Word2 Word3 Word1
</div>
<div>
Word1
</div>
<input type="button" id="button" value="Click" onclick="" />
This is css code:
div { width:200px;height:200px;border:1px solid black;float:left; }
And this is our javascript code:
var commonWord = 'Word1';
var button = document.getElementById('button');
button.addEventListener('click', function () {
var divs = document.getElementsByTagName('div');
divs[0].innerHTML = divs[0].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
divs[1].innerHTML = divs[1].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
});
But this javascript code marks only first words in divs
If you want to mark all words, you can use this:
var commonWord = 'Word1';
var button = document.getElementById('button');
button.addEventListener('click', function () {
var divs = document.getElementsByTagName('div');
divs[0].innerHTML = divs[0].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
divs[1].innerHTML = divs[1].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
});
Welcome to Stack Overflow!, This will work for you -
function myFunction() {
var div = document.getElementsByTagName("span");
div[0].innerHTML += 'Hello';
div[1].innerHTML += 'Hello';
}
div {
display: inline-block;
width: 48%;
float: left;
border: 1px solid;
text-align: center;
height:50px;
}
button {
border: 1px solid;
text-align: center;
margin-top: 30px;
}
<div>
<span></span> world
</div>
<div>
<span></span>
</div>
<button class="button" onclick="myFunction()">Button </button>
Note: Do read How to Ask for tips on asking questions. This is your first time so that's why am answering this question if there is any doubt do ask me in the comments. Hope this is helpful to you.

jquery textarea add link in text with costum popup

I have a textarea where users can enter some text en sometimes they use a little html in there to make it look better. Sometimes this goes a wrong so I tried to make it easier for them by adding a few images with functions. Like wrapping text in <b> <i> <u> <del> tags. This works great. Only now I want them to add url's and this is where I got stuck.
What I want:
I want a popup with a title bar and a url bar. after pressing OK I want the text to appear in the textarea where the user had left his cursor. the text in the textarea needs to look like ' + title + '. If a user selects some text i want that to appear in the popup title field.
If the add link button is pressed the script needs to look if there is a selection in the textarea
if there is a selection the script remembers that
the popup opens
in the title-input of the popup the selection appears.
the user fills in the url
the user presses the OK button
the popup disappears and the selected text gets replaced by a link
the link looks like ' + title + '
this is some code I have:
function wrapAsLink(url) {
var textArea = $('.area'),
len = textarea.value.length,
start = textarea.selectionStart,
end = textarea.selectionEnd,
sel = textarea.value.substring(start, end),
replace = '' + sel + '';
textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
$('.area').keyup();
}
and a fiddle
You can do something like this:
The fiddle.
Change your html as:
<div class="editor">
<div class="toolbar">
<span id="btnedit-bold" title="Vergedrukte text"><img src="images/bold.png" /></span>
<span id="btnedit-italic" title="Italic text"><img src="images/italic.png" /></span>
<span id="btnedit-underline" title="Onderstreep text"><img src="images/underline.png" /></span>
<span id="divider"> </span>
<span id="btnedit-delete" title="verwijder (doorstreep) text"><img src="images/delete.png" /></span>
<span id="divider"> </span>
<span id="btnedit-link" title="Insert link"><img src="images/link.png" /></span>
</div>
<textarea name="editor-preview" class="area" placeholder="Uw bericht"></textarea>
</div>
<p> </p>
<div class="editor-preview"></div>
<div id="prompt">
<div class="prompt-background"></div>
<div class="prompt-dialog">
<div class="prompt-message">
<p><b>Insert Hyperlink</b></p>
</div>
<form class="prompt-form">
<p>titel</p>
<input id="btnedit-title" type="text" style="display: block; width: 80%; margin-right: auto; margin-left: auto;">
<p>http://example.com/</p>
<input id="btnedit-url" type="text" style="display: block; width: 80%; margin-right: auto; margin-left: auto;">
<button id="btnedit-ok" class="btn-orange" onClick="$('#prompt').show();">OK</button>
<button id="btnedit-cancel" class="btn-orange" onClick="$('#prompt').hide();">cancel</button>
</form>
</div>
</div>
And add those to your javascript as:
$('#btnedit-bold').on("click",function(e) {
wrapText('b');
});
$('#btnedit-italic').on("click",function(e) {
wrapText('i');
});
$('#btnedit-underline').on("click",function(e) {
wrapText('u');
});
$('#btnedit-delete').on("click",function(e) {
wrapText('del');
});
$('#btnedit-link').on("click",function(e) {
var textArea = $('.area'),
len = textArea.val().length,
start = textArea[0].selectionStart,
end = textArea[0].selectionEnd,
selectedText = textArea.val().substring(start, end);
$('#btnedit-title').val(selectedText);
$('#btnedit-url').val('http://');
$('#prompt').show();
});
$('#btnedit-ok').on("click",function(e) {
e.preventDefault();
$('#prompt').hide();
replacement = '<a title="'+$('#btnedit-title').val()+'" href="'+$('#btnedit-url').val()+'" rel="external">' + $('#btnedit-title').val() + '</a>';
wrapLink(replacement);
});
$('#btnedit-cancel').on("click",function(e) {
e.preventDefault();
$('#prompt').hide();
});
function wrapLink(link) {
var textArea = $('.area'),
len = textArea.val().length,
start = textArea[0].selectionStart,
end = textArea[0].selectionEnd,
selectedText = textArea.val().substring(start, end);
textArea.val(textArea.val().substring(0, start) + link + textArea.val().substring(end, len));
$('.area').keyup();
}

Categories