The reason you cannot access the id
variable you created in the copy
function from afterCopy
is because variables defined inside of a function are scoped to that function. However, this is easily overcomable.
There is no need to save the value from $(this).attr('id')
as a global variable when the copy
function is called, because you can just as easily get the id of the calling element in the afterCopy
function by using the same exact expression: i.e.
<!-- language: lang-js -->
afterCopy: function () {
var id = $(this).attr('id');
}
This answers your original question, but there is a much better way to determine which elements to select. Rather than relying on the ID
field to never change and using it to construct the id of another element, you can just store the exact id of your copy text and copy message elements in the form of custom data- attributes* on your .copyme
anchor
, like this:
<!-- language: lang-html -->
<a data-copy="#code-1" data-copy-msg="#msg1" class="copyme">Copy Source 1</a>
Then, in the copy
function, you can grab that attribute and pass it into a jQuery selector to get the text value to copy, like this:
<!-- language: lang-js -->
copy: function () {
var copySelector = $(this).data('copy');
return $(copySelector).text();
}
You can handle the afterCopy
event the same way. You can use this
instead of having to store the ID in memory. Grab the selector where you want the message to go, and apply the html to that, like this:
<!-- language: lang-js -->
afterCopy: function () {
var copyMsgSelector = $(this).data('copy-msg');
$(copyMsgSelector).html("Source Code Copied");
}
So the whole thing would look like this:
HTML:
<!-- language: lang-html -->
<a data-copy="#code-1" data-copy-msg="#msg1"
href="#" class="copyme" >Copy Source 1</a>
<div id="code-1" style="display:none;">source code 1</div>
<span id="msg1"></span>
<br/>
<a data-copy="#code-2" data-copy-msg="#msg2"
href="#" class="copyme" >Copy Source 2</a>
<div id="code-2" style="display:none;">source code 2</div>
<span id="msg2"></span>
JavaScript:
<!-- language: lang-js -->
$('.copyme').zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: function () {
var copySelector = $(this).data('copy');
return $(copySelector).text();
},
afterCopy: function () {
var copyMsgSelector = $(this).data('copy-msg');
$(copyMsgSelector).html("Source Code Copied");
}
});