Inserting element just before selected text - javascript

I'd like to implement such a function on a web page: When called, it checks whether there are some text selection(often displayed as inverted colored text) on the page, if yes, insert an element <img src="my.png"/> just before the first word of the selection.
Pure JavaScript or jQuery code are both welcome, jQuery preferable. Thank you.

I can propose you this solution :
$('#butt').click(function(){
var sel = window.getSelection();
if (sel.toString().length>0) {
var key = sel.anchorNode.compareDocumentPosition(sel.focusNode) & Node.DOCUMENT_POSITION_PRECEDING
? 'focus' : 'anchor';
var $elem = $(sel[key+'Node']), txt = $elem.text(), offset = sel[key+'Offset'];
var $f = $(document.createTextNode(txt.slice(0, offset)));
$elem.replaceWith($f);
$(document.createTextNode(txt.slice(offset))).insertAfter($f);
$('<img src=http://dystroy.org/flore/icon.png>').insertAfter($f);
}
});
Demonstration

<div id="test">
<span class="spanthatcontainstext">test</span>
</div>
$(function(){
var checkfortext = $('.spanthatcontainstext').length;
if(checkfortext){
$(checkfortext).prepend('<img src="" />');
} else {
//do something if there is no text
}
});

Related

Find Text from content then hide

I am trying hide specific Text elements from content by jquery.
HTML:
<div id="name">
Trying hide specific Text elements from content.
</div>
I want this:
<div id="name">
Trying hide <p style="display: none;">specific</p> Text elements from content.
</div>
Or any others simple solution by jquery?
somthing simple like
var nameText = $('#name').text();
var newText = nameText.replace('specific','<p style="display:none">specific</p>');
$('#name').html(newText) // use html() here, not text()
add an id to your p tag and you can hide it by jquery like
$( document ).ready(function() {
$("#p-id").hide();
});
I make function for you
function hideIt(elem, exclude){
var text = elem[0].innerText;
var exculude = exclude;
var match = text.match(exclude);
if(match === null){
console.log('no match founded')
}
else{
for(var i =0 ; i<match.length; i++){
elem[0].innerText = text.replace(match[i],"")
}
}
}
hideIt($('#name'),'specific');
place 1rst param your elem with jquery selector and on 2nd parm the string want to kill
https://jsfiddle.net/xps4553m/5/ for you

Using Javascript to hide text shown on currency switch

I'd like to use Javascript (on page load) to remove the wording 'Choose a currency to display the price:'.
Leaving just the currency icons in the box (Div id = currency-switch).
How can I do this?
Page url: http://www.workbooks.com/pricing-page
Image example:
You can remove this text with for example:
window.onload = function(){
var el = document.getElementById("currency-switch");
var child = el.childNodes[0];
el.removeChild(child);
};
If you want to keep it stupid simple just add an span around the text and give it an id like "currency_text".
Then you only need this code:
var elem = document.getElementByid("currency_text");
elem.remove();
Try
$(document).ready(function() {
var currencyDiv = $('#currency-switch');
currencyDiv.innerHTML(currencyDiv.innerHTML().replace("Choose a currency to display the price:", ""));
}
This will remove the text as soon as the DOM is ready.
Please see below which will just remove the text:
This will trigger on page load
<script>
// self executing function here
(function() {
var selected_div = document.getElementById('currency-switch');
var text_to_change = selected_div.childNodes[0];
text_to_change.nodeValue = '';
})();
</script>
Since it's a text node, you could do the following in jQuery. This will be triggered on DOM ready.
$(function() {
jQuery("#currency-switch").contents()
.filter(function() {
return this.nodeType === 3;
}).remove();
});
You can use this code:
var requiredContent = document.getElementById('currency-switch').innerHTML.split(':')[1];
document.getElementById('currency-switch').innerHTML = requiredContent;
See it working here: https://jsfiddle.net/eg4hpg4z/
However, it is not very clean, but should work, if you cant directly modify the html.
A better solution would be to modify your code to move the text content within a span and show hide the text like so:
HTML:
<div id="currency-switch">
<span class="currency-label">Choose a currency to display the price: </span>
<span class="gb-background"><span class="GB"> £ </span></span><span class="es-background"><span class="ES"> € </span></span><span class="au-background"><span class="AU"> $ </span></span></div>
Javascript:
document.getElementsByClassName('currency-label')[0].style.display = 'none';

replacing html tag inside textarea with text

code :
<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var $this = $("#Test_txtarea");
var txtval = $this.val();
$this.find("img").each(function () {
var imgbytes = $(this).attr("name"); // extract bytes from selected img src
$(this).replaceWith(imgbytes);
});
$("#NewVal").html(txtval);
});
</script>
html
<textarea ID="Test_txtarea" >Hi <img src='test.png' name='test' > kifak <img src='test2.png' name='test1' > Mnih <img src='test3.png' name='test3' ></textarea>
<span id="NewVal" ></span>
what i am trying to do is basically trying to replace each img tag by it's name so the final textarea value will be like this : Hi test kifak test1 Mnih test3
this is the jsfiddle : http://jsfiddle.net/Ga7bJ/2/
the .find("img") always return 0 as length.how can i fix this code ?
Though it is not complete answer or at least not going to be "Copy paste" answer, there is few things you need to do here:
The content of Textarea is VAL of it and not InnerHTML. So, you have to pick that content as value and than create a hidden div and put it as HTML. Once you did it, you can now find the HTML tags in it using find rather easily.
Once you find tag you can find the name using attr() function
Once you have name, than you again go back to val() of textarea, and do regex replace or using HTML you can replace as well I guess, but not sure.
Look at this jsFiddle. What is does is:
It gets the value from your Test_txtarea and sets that as the html of a hidden div.
The hidden div wil render the images within the textarea.
After they have been rendered, I find these images,
- get the source,
- remove all characters after the .
- replace the entire html of the image with the src.
After all that has been done you are left with a div with the value you wanted.
All what is done next is the html from the div is copied to the value of your textarea.
function replaceImageWithSrc(value){
var div = $("#invisible");
div.html(value);
var images = div.find("img");
images.each(function(index){
var src = $(this).attr("src").split(".")[0];
this.outerHTML = src;
});
return div.html();
}
$(document).ready(function () {
var txtArea = $("#Test_txtarea");
var txtval = txtArea.val();
txtval = replaceImageWithSrc(txtval);
txtArea.val(txtval);
});
The following code works for me. Basically, I get the value of the text area and append it to an off-screen div. Now that I have valid markup nesting, I can iterate the child-nodes as normal.
function byId(e){return document.getElementById(e)}
function newEl(t){return document.createElement(t)}
function test()
{
var div = newEl('div');
div.innerHTML = byId('Test_txtarea').value;
var msg = '';
var i, n = div.childNodes.length;
for (i=0; i<n; i++)
{
if (div.childNodes[i].nodeName == "IMG")
msg += div.childNodes[i].name;
else if (div.childNodes[i].nodeName == "#text")
msg += div.childNodes[i].data;
}
byId('NewVal').innerHTML = msg;
}

Javascript "getSelection" only if it's in a certain div

So I'm trying to collect what people are selecting on our site. Currently, it works EVERYWHERE, and I don't want that. I only want it if they are selecting in a certain DIV.
it's basically a simple modification to a script I found.
<script type="text/javascript">
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
document.oncopy = appendCopyright;
I tried modifying selection = window.getSelection(); but it just broke it :(
Basically, I want the above code, ONLY to work in a certain div, not the whole body
Probably you shouldn't use document.oncopy, instead try using div.oncopy where div is the div element you are interested in.
var selection = getSelection().toString(); is your solution - getSelection() returns a Selection object and you can get the string just by using .toString() method. More properties and methods of Selection object could be found here: https://developer.mozilla.org/en-US/docs/DOM/Selection
According to the Mozilla JS docs the selection class has a method containsNode. The following should work.
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
// HERE's THE GOODS
// set aPartlyContained to true if you want to display this
// if any of your node is selected
if(selection.containsNode(aNode, aPartlyContained)){
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
}
document.oncopy = appendCopyright;

get the text content from a contenteditable div through javascript

I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.
Why not use textContent for this:
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent;
http://jsfiddle.net/E4W8y/1/
Unfortunately, I've found that innerText is the only way to preserve newlines in contenteditable dom nodes. What I'm doing (tested only in chrome at the moment) is this:
var innerText = editableDiv.innerText // using innerText here because it preserves newlines
if(innerText[innerText.length-1] === '\n')
innerText = innerText.slice(0,-1) // get rid of weird extra newline
return innerText
lblMailContent is the id of editable field.
var details= document.getElementById("lblMailContent").innerHTML;
Put this code in clientClick. It worked well for me.
use jQuery and do
var content = $('#my-contenteditable-div').html();
also look up these links:
http://west-wind.com/Weblog/posts/778165.aspx
Extracting text from a contentEditable div
I solved it this way, because i need html-input:
message = $('<div>').html(
$('#area').html()
.replace(/<(div|p|br)[^<]*?>/g, '<br />')
.replace(/<([(i|a|b|u)^>]+)>(.*?)<\/\1>/gim,
function(v) { return '' + escape(v) + ''; })
).text();
Allows the tags A, B, I, U and replaces Divs and Ps with BRs
Using text content, working fine in most of the cases
Working Example: jsfiddle(verified in Safari)
Use this:
function textFromDiv(selector) {
const element = document.querySelector(selector);
const text = element.html().replace(/<div>/g,"\n").replace(/<\/div>/g,"").replace(/<br>/g,"\n");
return text;
}```
Here's my spin at it...
input = document.getElementsByTagName("div")[0];
input.onkeyup = function(){
text = "";
for(i=0; i<input.childNodes.length; i++){
text += input.childNodes[i].textContent + "\n";
}
text = text.trim();
console.log(text);
}
Vanilla JS solution
html:
<div
contenteditable="true"
onkeyup="myFunction(this, event)"
></div>
js:
function myFunction(self, event){
console.log(self.innerText)
console.log(event)
}

Categories