Copy HTML Element with AHREF And Allowing Pasting to Word - javascript

Have a modal dialog that presents user with a ticket number that is formatted as a clickable object(URL). If you were to view the underlying HTML there is an A tag to the ticket number:https:/server/form/id?ticket number. If the user highlights the ticket number, does a right mouse click and Copy (not Copy link address) and then pastes that into MS Word, the ticket number is pasted and it retains the underlying URL embedded as a hyperlink. For some users highlighting the value without getting other surrounding text can be challenging. What I want to do is include a button that will run JavaScript that will perform that same action for them. I have been able to write the script that gets the URL from the A tag and put into the users Clipboard but pasting it into MS Word pastes the entire URL - which makes sense. Is there a way to copy to the clipboard what the user does manually?

Notes
Firstly, when I answer questions, I first try to give a more generalized answer that is meant to be adapted. StackOverflow isn't a coding service and as such, the answers shouldn't answer 1 single use-case but rather, as many as possible so when other users come across a question similar to theirs, the answers can still be useful.
Relevant Answer
That being said, How do I copy to the clipboard in JavaScript seems to cover what OP is asking for. I am posting this answer to explain how/why it answers OP's question.
There are 3 methods given in the accepted answer on that post. The first method (Async Clipboard API) is going to typically be what people use. The second method is deprecated. The final method (Overriding the copy event) isn't covered in detail but applies to OP's question.
Applying the Answer
Using the first method, a button (or other actionable element) could be added to the page to copy data to the clipboard. Based on OP's question, the only other thing needed here is getting the user's selection. The MDN Web Doc for the user selection on a page covers this and a lot more, but the basic thing needed here is window.getSelection().toString(), which will get the currently selected text (text only, no element information).
Method 1
const _CopyText = () => {
navigator.clipboard.writeText(window.getSelection().toString());
console.log(window.getSelection().toString());
}
<div>
<p>This is random text just to fill space. Its <b>only purpose</b> is to create the appearance of content on a page. <span style="color: #00F;"><b><i>This is random text</i></b></span> just to fill space. Its only purpose is to create the appearance of content on a page.<p>
<p>This is random text just to fill space. Its only purpose is to create the appearance of content on a page.</p>
</div>
<input type="button" value="Copy Text" onclick="_CopyText()">
<br>
<textarea style="width: 40em; height: 5em;"></textarea>
Method 2
This method actually involves manipulating what is currently being copied by the user. For this example the focus is just to convert the copied information into text only (removing any additional information such as URLs or formatting). With this, we are using the 3rd method discussed in the linked post regarding Overriding the copy event.
document.addEventListener("copy", e => {
e.clipboardData.setData("text", window.getSelection().toString());
e.preventDefault();
});
<div>
<p>This is random text just to fill space. Its <b>only purpose</b> is to create the appearance of content on a page. <span style="color: #00F;"><b><i>This is random text</i></b></span> just to fill space. Its only purpose is to create the appearance of content on a page.<p>
<p>This is random text just to fill space. Its only purpose is to create the appearance of content on a page.</p>
</div>
<input type="button" value="Copy Text" onclick="_CopyText()">
<br>
<textarea style="width: 40em; height: 5em;"></textarea>
Additional Notes
Places like the CodePen and the StackOverflow snippets have limited or no access to certain features (such as the clipboard API). So saying 'it doesn't work' when you try the snippets is not due to failed code. Please use the code and all references to learn and then adapt the code for any specific needs and use-cases.

Related

Search function through text in my page using javascript

I am attempting to create a search bar for looking through text on my website without using external code (such as google's custom search engine).
I have been searching this for a while and without using php it doesn't seem like there is a good solution.
I have so far found this fiddle, but don't entirely understand how it works as I am new to js http://jsfiddle.net/pdgucocw/ (code from jsfiddle copied here:
function contains(text_one, text_two) {
return text_one.toLowerCase().indexOf(text_two.toLowerCase()) != -1;
}
$("#searchText").keyup(function(){
var searchText = $(this).val();
$("ul li").each(function() {
$(this).toggle(contains($(this).text(), searchText));
});
});
right now I have this:
<p id="q">
Some text, which is a lot of text, text text.
</p>
<p id="searchthru">
Lots of text
</p>
<form>
<input name="search" >
<button type="submit" name="Submit" onclick="return false;">Submit</button>
</form>
Which is, as you can see, just HTML.
I know this question is rather broad right now, so I'll try to specify what i'm attempting to do with it.
I have a landing page on the website, and then another page with quite a bit of text on it. The text page is well kept with aptly named headers and id's and so forth. I want a search bar on the text page (or even the landing page, but unless php is the only solution I would like to stay away from it).
Then, when someone puts something in the search bar, it can either search through the text in the headers and present the match, or search through all the text and then present the header text as the "options" for which to jump to in the search.
edit: This is to say to do whichever is more feasible/better user experience. I don't want the search bar to do both simultaneously, that makes little sense in my application.
For example, they type in "Water Parks" and they will be presented with options such as "Water Parks" "Parks" "Amusement Parks" "Theme Parks" etc. Then when they click their option, they will be brought to the correct section. If they type in "water" then the search bar will only bring up "Water Parks" assuming that the word 'water' is used multiple times but only in the Water Parks section.
I would very much appreciate it if someone would explain (as if to a 5 year old who is really good at understanding syntax but doesn't know what the functions do) the javascript code as they write it.
Eventually I would like to split up the text into many pages and I think that I would have to use php for that (from what I've read so far) but I would REALLY prefer a pure js solution. If this is impossible or otherwise just a bad idea, feel free to teach me php. Thank you so much.

How to create an input field where you can type naturally, and then it translates it into HTML?

I'm trying to have a textarea input field just like when you post a new StackOverflow question. You can have line spaces, you can bold text, you can insert link etc.
However, when you push some kind of button, all of that gets translated into a long HTML string (e.g., spaces become <p> or <br>, bold becomes <strong>, link becomes <a>). Is there a way to do this with some kind of JS plug in?
What you describe is a What You See Is What You Get (WYSIWYG) editor.
Google "WYSIWYG editor library"
Examples:
https://prosemirror.net/
https://www.tinymce.com/
This question has been answered here Rendering HTML inside textarea
What you need is WYSIWYG (What you see is what you get) editor.
There are a lot of them.
You can check out these:
Ckeditor The best web editor for everyone
TinyMCE Full featured web editing
They are very easy to use.
If I have understood what you are asking, you will need to learn regular expressions. Everything is the context is based on text replacement.
Example: because textarea does not display hyperlinks, buttons, i can do somethings like in stackoverflow.
For hyperlink, i can write something link [# http://facebook.com] or [link]http://facebook.com [link];
later, I extract the http://facebook.com and wrap it between <a></a> elements.
What everybody above said is true, you want to be looking at a WISYWG editor.
If by chance you are using Bootstrap, you may want to look at Summernote.
I have no affiliation with them, but I used it for one of my projects and was very pleased.

Do you know of a javascript library that lets you embed textareas that update a webpages format in real time?

I'm introducing some at-risk kids to HTML in an upcoming class and we have a very small amount of time to show them how cool making your own web page can be.
What I'd like to do is build a page template full of text boxes which the kids can fill with text and some simple formatting tags. As they update, a split screen would update with the results of their edits.
I'm looking for a free / open source jquery or other javascript library which would help achieve the goal above.
Actually, it would quite similar to what stackoverflow does in the preview box as you are typing a question.
Rather than just blindly lifting code from other websites, I would love something with actual documentation (or at least a quick example.)
Google searches show a lot of tools and things you can download or use on other sites. The ideal here would be a library I embed in a page and position as I see fit.
Thanks for your help
Edit
As pointed out by some folks - this is a simple matter of updating divs on certain events.
<script type="text/javascript">
$(window).keyup(function(){
$('#about_me_result').html($('#about_me').val());
});
</script>
<textarea id="about_me" name="aboutMe" rows="9" cols="60">Write a little something about you...</textarea>
I went with keyup since keydown always leaves the last character off the other element.
No real need for a library. Just update the document
$(window).keydown(function(){
$('#element').html($('#sometextarea').val());
});
As btown suggests in his reply below, you could just send them to jsfiddle.net.
Or, if you want to put something like that on your own page somewhere, you could cook your own! play around here: http://jsfiddle.net/lbstr/LD9kA/
<textarea id="code"></textarea>
<div id="result"></div>
$('#code').keyup(function(e){
$('#result').html($(this).val());
});
Or, maybe you want an "Update" button instead of updating on keyup.
<textarea id="code"></textarea>
<button type="button" id="update">Update</button>
<div id="result"></div>
$('#update').click(function(){
$('#result').html($(this).val());
});
What about w3c Schools Tryit Editor it's much simpler than jsfiddle.
The only thing is you have to press a button to see the HTML update. That's probably not a bad thing though as if it changed on every key up the resulting web page might go crazy as you typed in half finished tags and attributes.

What is reliable way to clip *content* of a web page?

I wonder how it is possible to (more or less ) reliably clip the content from a random web site (using Ruby or JavaScript, doesn't really matter).
Much like Evernote and Flipboard do.
What is the best way to determine where the actual content is within a page?
The purpose: given a URL - retrieve the actual content of that page and ignore all the layout and other unrelated information.
For example:
given http://ninemsn.com/ => the HTML of the main news topic that is in the middle part of the content.
given the http://news.cnet.com/8301-1035_3-20104048-94/a-beginners-guide-to-telecom-jargon-part-7 => the HTML of the main article.
Just use Evernote's "clip full page" option to see exactly what I mean.
Thanks.
My initial thoughts would be to DOM parse the page, then traverse the DOM tree to the content of a specific div and show that (via XPath, etc). For pages without clearly-defined sections it's going to be difficult regardless of which method you use. The AutoPager plugin for Firefox and Chrome implements XPath parsing behaviour. Get the latest version and open up the .xpi to see how he does it. It's a JavaScript implementation.
Pick the div by letting someone enter, per URL/site scheme, what the id or class of the content div is. For your ninemsn example, the div containing the article's title, share buttons, the author's image, and the post content is
<div class="post">
and the actual body of the text is
<div class="postBody txtWrap" section="txt">
So someone would enter that you need to parse the first h1 from <div class="post"> and that's the article title, and then get all the text from <div class="postBody"> and make that the article content (you might need to parse the class in such a way that it can match both postBody and txtWrap).
Another example (for funsies): Stack Overflow. A question's title is contained in
<div id="question-header">
A question's text is trickier, because it's in a div with the same class as an answer's text, and no id. You need to match <div id="question"> and then traverse down to
<div class="post-text">
Similarly for answers, each <div id="answer-[UINTEGER]"> contains a <div class="post-text"> with its respective text.
In both situations, you can traverse those top-level question and answer- divs for <div class="user-details"> to fetch usernames, reputation and badge counts, etc.

How does Financial Times add a disclaimer when pasting text?

Here is an example of what happens when pasting text from Financial Times, the top paragraph is added.
Thanks in advance!
Example:
Please respect FT.com's ts&cs and copyright policy which allow you to: share links; copy content for >personal use; & redistribute limited extracts. Email ftsales.support#ft.com to buy additional rights >or use this link to reference the article - http://www.ft.com/cms/s/0/792f1aec->9600-11e0-8256-00144feab49a.html#ixzz1PFrYZiD0
Goldman Sachs gave a paid internship to a top Libyan official’s relative while the bank was carrying >out lossmaking trades on behalf of the country’s sovereign wealth fund, the Financial Times has learnt.
As already previously mentioned, modifying the clipboard data is either restricted to specific browsers or requires the user to grant access to modifying the clipboard. A work around to this you could
Add an event handler to the oncopy event
Find the selection
Prepend/append content to the content
Modify the selection range to include the appended/prepended content
Wait for the copy action to push through
Remove the appended/prepended content
I fiddled about with this method and created a plugin which does just that. Still a preliminary version and only tested on FF4/Chrome 11/IE8 so far (and IE definetly needs to have some more work done). Some of the nice things you can do with this method is that you could easily for example wrap forum post quotes in [quote=USER]content[/quote] and assign the user based on which post is copied. By default, the script always selects the DOM styling, but not the actual HTML, so if you for example copy bold content, it would be bold if pasted into a rich text editor, but just text if used in text only editors (removing the html tags).
Prepending content is significantly easier with this method, compared to appending, in which case I still am not sure whether it is fully functional. For IE, you could directly modify the clipboard, but there are some issues for example when selecting the whole page, or if you want to toggle the rich copy content. Haven't had the chance to do any further browser testing, but this appears to be at least a working solution for newer browsers.
Example: http://hertzen.com/experiments/jquery.plugin.clipboard/
Another example: http://hertzen.com/experiments/jquery.plugin.clipboard/thread.html
Source code: https://github.com/niklasvh/jquery.plugin.clipboard
You implement a handler for the oncopy event. By manipulating the clipboardData object, you can change the copied text.
Webmaster use Javascript for that.
Check file http://media.ft.com/j/FTTrack2.js
FT.Tynt={
initTynt:function(){
var Tynt=Tynt||[];
Tynt.push('cqolxGrS4r34rIadbiUt4I');
Tynt.i={
"cc":"0",
"b":true,
"ap":"Please respect FT.com's <a href='http://www.ft.com/servicestools/help/terms'>ts&cs</a> and <a href='http://www.ft.com/servicestools/help/copyright'>copyright policy</a> which allow you to: share links; copy content for personal use; & redistribute limited extracts. Email ftsales.support#ft.com to buy additional rights or use this link to reference the article -",
"t":true
}
This is something you can achieve via a jQuery plugin named jquery copy. Here's an example using the p selector.
$("p").click(function() {
$.copy($(this).text() + " Disclaimer goes here!");
});
They use JavaScript which can be found in the following file:
http://media.ft.com/j/FTTrack2.js

Categories

Resources