What is the best way to implement the copy function for an icon in JavaScript?

[![enter image description here][1]][1]

bold, dynamic text**

I am trying to implement a copy functionality on an icon within a website. I have successfully achieved this with input text, but faced challenges when attempting to apply it to an icon.

            <div class="icon-container" style="display: inline-block;">
            <input class="paste" type="button" value="Copy Url" @click="urlCopy" id="copy" hidden/>
             <textarea class="paste" id="url" rows="1" cols="30" hidden></textarea>
            <img  style="display: inline-block" src="share.png" alt="">
        </div>


urlCopy() {
  console.log("sulg", this.slug.fullPath)
  let Url = document.getElementById("url");
  Url.innerHTML = window.location.href;
  console.log(Url.innerHTML)
  Url.select();
  document.execCommand("copy");

}

Answer №1

I highly suggest utilizing the vue-clipboard2 library for easier URL copying compared to traditional methods.

Demo

<div id="demo-app"></div>

<template id="copy-template">
  <div class="container">
    <input type="text" v-model="contentToCopy">
    <button type="button" @click="copyText">Copy!</button>
  </div>
</template>

<script>
new Vue({
  el: '#demo-app',
  template: '#copy-template',
  data: function () {
    return {
      contentToCopy: 'Sample Text to Copy'
    }
  },
  methods: {
    copyText: function () {
      this.$copyText(this.contentToCopy).then(function (result) {
        alert('Copied successfully!')
        console.log(result)
      }, function (error) {
        alert('Unable to copy')
        console.log(error)
      })
    }
  }
})
</script>

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

Troubleshooting: Configuring dynamic minimum time for <input type='time'> in AngularJS not functioning as expected

Can someone help me with setting the minimum time dynamically to the current time? For some reason, it's not working and I'm not getting any error messages. Where did I make a mistake? $scope.mintime = new Date(); <label class="item item-in ...

Methods for dynamically altering the background color of a parent component from a child component

Currently, I am working on a T-shirt design application using fabric.js within reactjs. I have encountered an issue when attempting to change the color of the t-shirt. My goal is to allow the color of the T-shirt to be changed from the child component but ...

Is there a way in which I could instruct 40 buttons to individually correspond to the table row on which they are placed, without the need for 40 distinct events, using JavaScript and PHP?

Imagine a scenario where there is a large table of products, each row containing the product name, its price, and a "Rebate?" checkbox. For every product in this table, there are two corresponding values: fullPrice and rebatePrice. If the "Rebate?" checkbo ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Utilizing the extend method to incorporate an object into a prototype

Every time I attempt to add the object BaseNet to IPv4Address.prototype, I encounter an error: TypeError: Cannot read property 'ipInt' of undefined This error is puzzling. It seems like the getter is being executed when copying the object to ...

keep an ear out for happenings in dynamic vue modules

What is the method to listen to an event emitted by a dynamically generated component instance? In this scenario, the first component is inserted into the DOM statically, while the second one is created dynamically using JavaScript. Vue.component("butt ...

Ways to forward a webpage once validation has been completed

I have a login form that is being validated using jQuery/Ajax to receive a JSON response. The form calls a PHP page called add-data.php. Upon successful validation, I want to redirect to another page after displaying the message Successfully logged!: if ...

Execute a function only once

Is there a way to call and utilize this function just once, and then terminate it? When calling the function: else if (msg.text == [" ...

Tips for calculating the total sum of inner object property values using JavaScript, TypeScript, or Angular 5

What is the total sum of successCount values in the given array object? var successCount;//I want count of all successCount attributes from the below object var accordianData = [ { name: "Start of Day", subItemsData: [ { title: " ...

When bootstrap labels are created dynamically, the spaces between them are stripped away

Every time I click the create button, a new bootstrap label is generated. However, the labels created appear bunched up with no spacing between them, as shown in the image below. https://i.sstatic.net/t5H1H.png How can I make sure that there is proper s ...

Creating an HTML table from JSON data using JavaScript

I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "und ...

What is the recommended placement for the implicitlyWait method in Protractor?

When implementing implicitlyWait, what is the appropriate location to include browser.manage().timeouts().implicitlyWait(5000); within the test script? ...

What is the best way to arrange objects in an array by date using Angular 4?

My array of objects is structured like this : this.filteredData = [ {'id': 1, 'date': '04-05-2018'}, {'id': 2, 'date': '29-03-2018'}, {'id': 3, 'date': '03-04 ...

Navigating to the same hash using Vue Router in a consecutive manner

Currently, I am developing a website using Vue and Vue Router for routing. The method I am using to manage scroll behavior for anchor links is as follows: const router = new VueRouter({ routes, scrollBehavior (to) { if (to.hash) { ...

The reason for setting a variable as void 0 in JavaScript

Currently, I am delving into the libraries referenced in this particular article as well as other sources. There are some truly mind-boggling concepts contained within these resources, one of which is highlighted by the following line: var cb = void 0; I ...

Which queue in Node does the callback from I/O operations returning promises get added to - the I/O queue or the microtask queue?

I'm currently delving into the intricacies of how Node's event loop operates. From my studies, I have discovered that the promise queue is given precedence over the timer queue, which in turn trumps the I/O queue. async function asyncFunc() { ...

What is the best method for resizing individual SVG elements using jQuery or JavaScript?

A unique effect on my webpage involves an SVG comprised of scattered squares that enlarge when the user scrolls past a specific point. However, there is a problem with the scaling process which results in a horizontal scroll bar appearing. This occurs beca ...

The functionality of Vue.js checkboxes is not compatible with a model that utilizes Laravel SparkForm

I've configured the checkboxes as shown below: <label v-for="service in team.services"> <input type="checkbox" v-model="form.services" :id="service.name" :value="service.id"/> </label> Although they are displayed correctly, the ...

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

Is there a way to efficiently add delimiters to an array using jquery dynamically?

Just joined this community and still figuring things out. I have a question - how can I use jQuery to dynamically add a delimiter like "|" after every 3 elements in an array? This way, I can explode the array and utilize the resulting arrays separately. He ...