I have a copy to clipboard function working ok, though just not quite how I’d like it. As things stand, if I click the input element, the value is copied.
The problem is, I need another button to copy the text from the input, not sure how to connect the trigger(HIT ME) so when I click this it will copy the input.
Advice on the best approach?
I thought I needed to amend the focus() though not sure what to change.
Instead of defining the function inside click, define it as a variable. (var myclickfunction = function…)
then bind the click events to call that variable. ($(‘theselector’).click(myclickfunction)
As far as the focus, just change $(this) to $(‘thecorrectselector’). Nothing forces you to ‘stay within your element’ so to speak.[EDIT: Ignore this. Read the OP wrong.]
Remove the word “input” from your first selector.
Add “.find(‘input’)” to both of the $(this) statements.
Done.
EDIT: And dont mix your quote marks as i did the first time i posted that.
After much searching today, it seemed like I needed to use the input element to make the copy function work.
Ideally, I was hoping to just copy a href or text within a div to the clipboard.
Wondering if the above approach will still work like this, I might need to hide the input element and copy it while its hidden so my design is not altered.
Will run some more tests now.
Update:
I think your right!
Just ran the below and this seems to work ok.
But I need the select() else does not work.
You’re right - I did specifically tailor it to the example you gave me. Narrow answer, because it was the ‘simplest’.
If you’ve got other content in the div, we’re gonna start running into the concept of levels. So, instead of finding downwards, we find UPWARD, and THEN downward.
Let’s assume you only assign “trigger” class to things you want to trigger the copy. (As an aside, You might want a different name, as trigger is a function name in jQuery. It wont -affect- anything, but it may be confusing to type $('.trigger').trigger() at some point in the future.)
I will -assume- that all .trigger elements are somewhere INSIDE .copy-to-clipboard elements.
.closest() goes UP the DOM tree, starting at the element (this). Somewhere above that element there is a <div> with the class copy-to-clipboard. So Closest stops and says “Found it! It’s this thing.” Then find receives that, and goes diving back DOWN inside that element’s children to find the input element (note: if you have more than 1 input in the div, change this selector to be more specific.). select() you already know.
I’ll run further tests with this, at least I have a fall back if I can’t get things to work.
I even think just hiding the input could be the best option, in this instance anyhow.