Make sure to include additional details, such as copyright information and a link to read more, when copying text. It is also important to maintain the

When attempting to include a read more link in my copied text, I am encountering an issue where the line breaks and formatting are being neglected:

 <script type='text/javascript'>
function addLink() {
    var body_element = document.getElementsByTagName(&#39;body&#39;)[0];
    var selection;
    selection = window.getSelection();
  var pagelink = &quot;<br/><br/> More Jokes at: http://jokesforhimandher.blogspot.com/ <br/>&quot;; // modify this as needed
    var copytext = selection + pagelink;
    var newdiv = document.createElement(&#39;div&#39;);
    newdiv.style.position=&#39;absolute&#39;;
    newdiv.style.left=&#39;-99999px&#39;;
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function() {
        body_element.removeChild(newdiv);
    },0);
}
document.oncopy = addLink;
</script>

Is there a way to maintain the line breaks and formatting?

Answer №1

Preserve line breaks and formatting by copying the selection as plain text and then obtaining the selected text as HTML.

Check out the JSFiddle demo here

Here is the JavaScript code:

function addLink() {
    var selection = window.getSelection();

    var htmlDiv = document.createElement("div");
    for (var i = 0; i < selection.rangeCount; ++i) {
        htmlDiv.appendChild(selection.getRangeAt(i).cloneContents());
    }
    var selectionHTML = htmlDiv.innerHTML;

    var pagelink = "<br/><br/>Read more: http://www.stackoverflow.com/ <br/>";
    var copytext = selectionHTML + pagelink;

    var newdiv = document.createElement('div');
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    document.body.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function () { document.body.removeChild(newdiv); }, 0);
}
document.oncopy = addLink;

Answer №2

You may have overlooked a few quotes and thought it originated from this source or this one.

Seems to be functioning as expected, following the necessary corrections (View Working Demo):

function addLink() {
        var body_element = document.getElementsByTagName("body")[0];
        var selection = window.getSelection();
        var pagelink = '< br/> < br/> More Jokes at: http://jokescollection.com/ <br/>'; 
        var copytext = selection + pagelink;
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        body_element.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {
            body_element.removeChild(newdiv);
        }, 0);
    }

document.oncopy = addLink;

UPDATE:

Consider using pre instead of div & the newline character ('\n') to maintain line breaks. (See Updated Demo)

function addLink() {
        var body_element = document.getElementsByTagName("body")[0];
        var selection = window.getSelection();
        var pagelink = '\n\nMore Jokes at: http://jokescollection.com/\n'; 
        var copytext = selection + pagelink;
        var newdiv = document.createElement('pre');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        body_element.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {
            body_element.removeChild(newdiv);
        }, 0);
    }

document.oncopy = addLink;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...

Sharing a Redux action with nested child components

The current structure I am working with looks like this: UserPage -> Container |-----UserList -> Dumb Component |--- User ->Dumb Component My action and dispatch are connected to the container, which is UserPage. function mapStateToProps(state) ...

What is the best way to call an API within a loop using Node.js?

How can I efficiently make API calls based on page numbers in a loop? I am using the request() function for API calling, but when debugging my code, the response block is not reached and I do not get a response. Can someone please provide guidance on how ...

In Chrome, the `Jquery $('input[name=""]').change(function will not be triggered unless there is an unhandled error following it

Here is a script that I've created to make certain inputs dependent on the selection of a radio button. The 'parent' input in this case is determined by the radio button choice. Upon document load, the script initially hides parent divs of ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

The console experienced a forced reflow when a tooltip appeared on the slider handle while executing JavaScript

I am currently facing an issue with my web page that includes various elements along with the Ant.design slider. The values of the slider are being controlled through React states. However, I have noticed that when the slider tooltip is enabled, the respon ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

Navigating through various locators with Protractor to fill an array

Currently utilizing protractor, my aim is to iterate through a collection of locators (each with unique identifiers) in order to retrieve the displayed text and then compare it against an array of expected values. I have encountered examples similar to th ...

using eloquent in vuejs to fetch database columns

I am currently attempting to retrieve data from a database using an AXIOS get request. I have two models, Content and Word, which have many-to-many relationships. In my controller, I am trying the following: public function fetchCourses(){ $dayOne = C ...

Using a function to identify and check dynamically added checkboxes

I am using a PHP page that loads a group of categories from another PHP script as checkboxes. Here is the format for the checkboxes: <input type='checkbox' class='cat-selector' id='Business' data-toggle='checkbox&apo ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/ This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu are ...

Displaying the information from a nested array of objects in an HTML table through iteration

In the code snippet below, there is an input with a nested array of objects. The main array of objects is called summary and within it, there's a nested array called run_type. let input = { "summary": [ { " ...

What can be done to enhance this particular element?

I've created a Component that uses a 3rd party joke API to fetch jokes with a specific category upon page load. The component also includes a refresh button for fetching new jokes. export default function Jokes() { const { cat } = useParams(); const [ ...

What is the best way to revert my useState back to its original state once the filtered list has been displayed?

I am struggling to reset my projectList to its initial state so that the filterProjects function can search through the entire projectList instead of the already filtered ones. I have a resetProjects function, but I'm unsure where to call it in order ...

What is the method for applying background color to text within a textbox?

I am struggling to phrase this question properly and unable to find the solutions I need on Google. When searching, it only provides information on how to add an entire background color to a textbox, which is not what I am looking for. What I aim to achiev ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

Strategies for deploying on production as you develop a fresh Nuxt application

What are some recommended strategies for deploying a Vue/Nuxt project on production, especially for larger applications with lengthy build times? Typically, running the command npm run build Causes the app to be inaccessible to users until the build proc ...