Share Your Work

Mrafey
Contributor

OnClick function not working on all buttons

I have developed action cards that have a "copy text" button on them, that when clicked copy the text that is in the component.

Here is my HubL + HTML code:

Screen Shot 2023-08-31 at 4.48.19 PM.png


Following is my JS Code: 

Screen Shot 2023-08-31 at 4.49.46 PM.png


Whats odd is when I run this code, only one of the buttons "Copy text" works. So for instance if I have three action cards on my page, only the first action card's "Copy Text" button works and the other two dont. 

Anyone have any idea what it could be?

Thanks!  

0 Upvotes
2 Replies 2
skimura
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

OnClick function not working on all buttons

@Mrafey 

 

Hi.

 

The method "getElementById" returns one element

even if there are multiple elements with the same ID.

 

How about use `class` ?

 

exmaple: (not tested)

 

// Add click event all [copyBtn]
const copyBtns = Array.from(document.querySelectorAll('.copyBtn'));
copyBtns.forEach((copyBtn, index) => {
    copyBtn.addEventListener('click', () => {
        // Get the text corresponding to the copy button
        const actionDescription = document.querySelectorAll('.copy-desc-text')[index];
        const copyTxt = actionDescription.textContent;
        navigator.clipboard.writeText(copyTxt);
        ...
    });
});

 

 

Thanks.

Jaycee_Lewis
Community Manager
Community Manager

OnClick function not working on all buttons

Hi, @Mrafey 👋 Thanks for your question. Can you add your code to your post, please? You can use the code block tool to help with formatting. Troubleshooting code from screenshots is hard to impossible for our community members to help with.

 

Thanks! — Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Upvotes