How does Financial Times add a disclaimer when pasting text? - javascript

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

Related

Adding html/any tags to either side of selection - Javascript

Adding HTML/any tags to either side of selection - Javascript
The problem:
After creating a textarea box in my PHP/html file I wished to add a little more functionality and decided to make an textarea that can use formatting, for example
<textarea>
This is text that was inserted. <b>this text was selected and applied a style
via a button<b>
</textarea>
It doesn't matter what the tags are, (could be bubbles for all that I care due to the fact the PHP script, on receiving the $_POST data will automatically apply the correct tags with the tag as the style ID. Not relevant)
The Question/s
How can I create this feature using javascript?
Are there any links that may help?
And can, if there is information, can you explain it?
EDIT: Other close example but not quite is stackoverflow's editor and note that I do not wish to use 3rd party scripts, this is a learning process for me.
The tags that are inserted in the text are saved to a database and then when the page is requested the PHP replaces the tags with the style ID. If there is a work around not involving 3rd party scripts please suggest
And for the anti-research skeptics on a google search, little was found that made sense and there was Previous Research on SOF:
- https://stackoverflow.com/questions/8752123/how-to-make-an-online-html-editor
- Adding tags to selection
Thanks in Advance
<textarea> elements cannot contain special markup, only values. You can't apply any styling in a textarea.
What you'll need to do is fake everything that a text box would normally do, including drawing a cursor. This is a lot of work, as hackattack said.
You can do a lot if you grab jQuery and start poking around. Toss a <div> tag out there with an ID for ease and start hacking away.
I've never made one personally, but there is a lot to it. HTML5's contentEditable can maybe get you a good chunk of the way there: http://html5demos.com/contenteditable/
If you want to pass this data back to the server, you'll need to grab the innerHTML of the container and slap that into a hidden input upon submission of your form.
Here's other some things you can check out if you're just messing around:
tabindex HTML attribute, to get focus in your box from tabbing
jQuery.focus() http://api.jquery.com/focus/, to determine when someone clicks in your box
cursor: text in CSS for looks http://wap.w3schools.com/cssref/pr_class_cursor.asp
jQuery.keypress() http://api.jquery.com/keypress/, or similar for grabbing keystrokes
Edit: I think I completely misunderstood
If you're not looking for a rich text editor, and just want some helper buttons for code, maybe selectionStart and selectionEnd is what you're after. I don't know what the browser support is, but it's working in Chrome:
http://jsfiddle.net/5yXsd/
you can not do anything beside basic formatting inside a texarea. If you want complex formatting, look into setting a div's contentEditable attribute to true. Or you can make a wysisyg editor, but that is a big project. I strongly suggest using 3rd party code on this one.
I suggest you using the iframe to implement the WYSIWYG effect.
There is a property in iframe called designMode
See here for more
https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla
Also there is a lightweight example maybe you would like to take a look:
http://code.google.com/p/rte-light/source/browse/trunk/jquery.rte.js

What's the best method for creating a simple Rich-Text WYSIWYG editor?

I need to create a simple rich-text editor that saves its contents to an XML file using arbitrary markup to indicate special text styles (e.g: [b]...[/b] for bold and [i]...[/i] for italic). All the backend PHP stuff seems fairly straightforward, but the front-end WYSIWYG portion of the feature seems a bit more convoluted. I've been reticent to use one of the currently-available JavaScript-based WYSIWYG editors because the rich-text options I want to allow are so limited, and these applications are so fully-featured that it almost seems like more work to stip them down to the functions I need.
So, in setting out to create a bare-bones rich-text editor, I've encountered three approaches:
The first two approaches use the contentEditable or designMode properties to create an editable element, and the execCommand() method to apply new text styles to a selected range.
The first option uses a standard div element, executes all styling commands on that elements contents.
The second option uses the editible body of a window enclosed in an iframe, then passes any styling commands initiated from buttons in the parent document into its contentWindow to alter selected ranges in the contained body. This seems like several extra steps to accomplish the same effect as option one, but I suppose the isolation of the editable content in its own document has its advantages.
The third option uses a textarea overlaying a div, and uses the oninput JS event to update the background div's innerHTML to match the input textarea's value whenever it changes. Obviously, this requires some string finagling to to convert elements like newline characters in the textarea to <br/> in the div, but this would allow me to preserve the integrity of my [/] markup, while relegating the potentially-messy DOM manipulation to front-end display only.
I can see benefits and drawbacks for each method. the contentEditable solutions seem initially the simplest, but support for this features tends to vary across browsers, and each browser that DOES support it seems to manipulate the DOM differently when implementing execCommand(). As mentioned before, the textarea/div solution seems like the best way to preserve my arbitrary styling conventions, but the custom string-manipulation procedure to display rich text in the output div could get pretty hairy.
So, I submit to you my question: Given the development goals I've outlined, which method would you choose, and why? And of course, if there's another method I'm overlooking that might better serve my purpose, please enlighten me!
Thanks in advance!
Have you looked at http://php.net/manual/en/book.bbcode.php? This is your answer. If you are having doubts, then you are doing something wrong. :-)
Then use JS to track keyup event and simple AJAX to print preview of the input. Just like in stackoverflow.
NB It would be far more efficient to generate the preview using plain-js BBcode approach. However, do not overcomplicate stuff unless you necessary need it.
The problem with BBCode, Markdown, ... is that it's not that trivial for genpop. I suggest looking at widgEditor, it is by far the simplest WYSIWYG editor I've seen to date. It was developed some time ago, so I am not sure about compatibility, but it sure is an inspiration.
I would have included this only as a comment, since it does not directly answer your question, but I am fairly new to SA and could not find out how to do that. Sorry.

How does one properly test a javascript widget?

So, I've written a little javascript widget. All a user has to do is paste a script tag into the page, and right below it I insert a div with all of the content the user has requested.
Many sites do similar things, such as Twitter, Delicious and even StackOverflow.
What I'm curious about is how to test this widget to make sure that it will work properly on everyone's webpage. I'm not using an iframe, so I really want to make sure that this code will work when inserted most places. I know it looks the same in all browsers.
Suggestions? Or should I just build one hundred web pages and insert my script tag and see if it works? I would hope there is an easier way than that.
Once you have confirmed that your javascript works cross-browser in a controlled environment, here are some things that might cause problems when used on an actual website:
CSS
You're using a CSS class that is already being used (for a different purpose) by the target website
You're using positioning that might interfere with the site's CSS
The elements you are using are being styled by the website's CSS (you might want to use some sort of "reset" CSS that applies only to your widget)
HTML
You're creating elements with the same id attribute as an element that already exists on the website
You're specifying a name attribute that is already being used (while name can be used for multiple elements, you may not be expecting that)
Javascript
What is the expected behaviour without Javascript enabled? If your script creates everything, is it acceptable for nothing to be present without JS?
At very basic you should make sure your widget works for following test-cases. I am sure then it will work on all web-pages -
http/https: There should not be any warning for HTTPS pages for unencrypted content.
<script> / <no-script>: What if JavaScript is disabled? Is your widget still visible?
What happens when third-party cookies are disabled? Does your widget still work?
Layout-box restrictions: When parent div element's size is less than your widget. Does your widget overflow the given size and destroys owners page?
By keeping all your Javascripts under a namespace (global object) with a very unique name, you should be pretty much OK. Also, you can simply use an anonymous function if you just want to print out something.
Similar question: How to avoid name clashes in JavaScript widgets

Why is it bad practice to use links with the javascript: "protocol"?

In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:
Press me!
And then suddenly I stopped to see it. They were all replaced by things like:
Press me!
For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?
The execution context is different, to see this, try these links instead:
Press me! <!-- result: undefined -->
Press me! <!-- result: A -->
javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });
Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup
http://www.alistapart.com/articles/behavioralseparation
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.
Couple of reasons:
Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.
SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.
Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.
You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.
I open lots of links in new tabs - only to see javascript:void(0). So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents. Why? Well,
Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically. Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.
Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel. These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery). They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people. So it makes sense to keep them in
separate documents as well.
Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element <a> is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the <a> element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.
Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.
The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"
href = "#dostuff"
For the page:
onLoad = if(hash="dostuff") doStuff();
Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '</a>' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an <h1>, an <img>, or a <p> would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.
I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work". And then I setup my anchor tags like this...
<a href="EnableJavascript.htm" onclick="funcName(); return false;">
This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible. This will degrade gracefully. Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.
I think it has to do with what the user sees in the status bar. Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).

Create your own HTML Textfield with Javascript

I came across the following http://ckeditor.com/demo , and was wondering if anyone had a basic tutorial how to implement this (or perhaps what key search terms I should use)?
Is this just a heavily modified TextField, or have they somehow managed to create a completely new TextField from scratch?
I tried googling this many times, and I always get pages relating to customizing the built-in TextField with CSS etc.
A good place to start if you want to learn how richtext web editors work is to look into the contenteditable attribute and the document.execCommand method (the best editors use a lot more than this, but these are at the foundation). Over-simplified, an editor consists of a contenteditable block and ways to invoke document.execCommand on the text selection.
But, speaking as a person who has actually developed an editor of this kind, you might be better off using an existing one (CKEditor being a great one, in my opinion).
Edit: Note that contenteditable is a proprietary (Microsoft) property, but most (all?) browsers have implemented it now, and it will be in HTML5.
Edit 2: I want to try to clear up a few misconceptions.
A div or iframe isn't in itself editable, it requires the contenteditable attribute. The use of an iframe is typically a workaround for the fact that older Gecko browsers only supported an alternative editable property (designMode) that could only be applied to a whole document.
While some operations of advanced editors probably do employ innerHtml, this isn't the key to making an editor on the web.
It is not a textbox. It is a DIV that has lots of HTML injected to it with javascript.
The basic idea is that JavaScript uses the innerHtml property of the div and writes HTML to it.
This is a javascript implementation that replaces a input. It basically hides the input and uses it for storing and passing the data via POST.
The advanced textfields I have seen have all been iframe or div. The code behind them is quiet messy and not very accessible.
Proceed with caution!
You may want to consider WYSIWYM instead of WYSIWYG.

Categories

Resources