-1

I need a copy-to-text button using a font awesome icon in a div in wordpress.

I do not want any alerts. Just a simple click.

<div class="btcTXT">text</div>

<div id="cpy" class="cpy"><i class="far fa-copy"></i></div>

I am a novice so please tell me the steps I need to do.

Thank you in advance.

Ruvee
  • 8,611
  • 4
  • 18
  • 44
Erik
  • 5,701
  • 27
  • 70
  • 119

2 Answers2

0

Give your div an id first, like so:

<div class="btcTXT" id="your-div-id">text</div>

Then write this javascript to do the trick for you!

document.getElementById("cpy").addEventListener("click", () => {
    navigator.clipboard.writeText(document.getElementById("your-div-id").textContent).then(() => {
        console.log('Copied to clipboard!!!');
    });
});

Make sure you "enqueue/inject" your javascript to the page you're testing.

Let me know if you were able to get it to work!

Ruvee
  • 8,611
  • 4
  • 18
  • 44
  • How do I place javascript inside a wordpress page? Its doesn't seem to work if I add it to the page. – Erik Apr 06 '21 at 16:36
  • I don't know what you mean with "enqueue/inject" – Erik Apr 06 '21 at 16:41
  • I can't seen to figure out how to place the javascript. – Erik Apr 06 '21 at 16:42
  • In wordpress you need to load your javascript onto the page. Do you know how to do it? – Ruvee Apr 06 '21 at 16:55
  • I just tested it on my wordpress website and it works seamlessly fine. – Ruvee Apr 06 '21 at 17:25
  • Yes, please. How do you load javascript on the page? – Erik Apr 06 '21 at 18:09
  • Don't I need to make reference to
    ??
    – Erik Apr 06 '21 at 18:14
  • I've already done that in the javascript! In your wordpress root directory, create a javascript file and call it, let's say, "test.js", copy the javascript code that i gave you above and paste it into the "test.js". Then in the root folder of your active theme find a file called "functions.php", open it up and copy the following code into it, save it and load your wordpress. ```add_action('wp_enqueue_scripts', function () {wp_enqueue_script('test_js', get_theme_file_uri('test.js'), "", microtime(), false);});``` – Ruvee Apr 06 '21 at 18:21
  • Where do I put the test.js? – Erik Apr 06 '21 at 18:32
  • In the root directory of your active theme. – Ruvee Apr 06 '21 at 18:36
  • If i were you, i would find a developer and ask him/her to do it for me. The script that I've provided, is tested and works. I'll leave it here for future reference. – Ruvee Apr 06 '21 at 18:52
  • I'm trying to do this in a pop up window plugin – Erik Apr 06 '21 at 19:04
0

What @Ruvee said is correct. You typically need to enqueue scripts on your site to make sure everything works as expected. If that isn't your cup of tea I would suggest using a plugin like Simple CSS and JS Plugin.

You can add that piece of code as a new JS file using that plugin and should work just fine.

InvictusMKS
  • 401
  • 3
  • 8