zclip: refer to sender element in afterCopy callback - javascript

I have multipule "copy code" buttons on one page. Each code has its own button.
here is my basic html:
<a id="1" href="#" class="small-white-btn copyme">Copy Source</a>
<div id="code-1" style="display:none;">html source code goes here</div>
<div class="msg1"></div>
<a id="2" href="#" class="small-white-btn copyme">Copy Source</a>
<div id="code-2" style="display:none;">html source code goes here</div>
<div class="msg2"></div>
My zclip jquery looks like this:
$('.copyme').zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: function () {
var id = $(this).attr('id');
var copythis = $('#code-' + id).text();
return copythis;
},
afterCopy: function () {
$("div.msg" + id).html("<p>Source Code Copied</p>");
}
});
This works, however, I cannot get the message injected into the div class="msg" tag.
How can I target the var id, add it to the div msg and display it on the page when the button is clicked.

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.
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:
<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:
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:
afterCopy: function () {
var copyMsgSelector = $(this).data('copy-msg');
$(copyMsgSelector).html("Source Code Copied");
}
Working Demo in Fiddle
So the whole thing would look like this:
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:
$('.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");
}
});

You're declaring var id within a function, so it's a private variable that gets destroyed after the function finishes running. You need to declare the variable outside of your function; then when it runs you can assign and preserve the value.
try this:
var id;
$('.copyme').zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: function () {
id = $(this).attr('id');
var copythis = $('#code-' + id).text();
return copythis;
},
afterCopy: function () {
$("div.msg" + id).html("<p>Source Code Copied</p>");
}
});

Related

Change location.href with jQuery

I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>

How to get specific div through this?

I build a method that allow me to return the clicked element by the user, something like this:
$('#button2').on('mouseover', function()
{
console.log(this);
}
this return:
<tr id="res-7" class="entry border-bottom" rel="popover" data-original-title="" title="">
<td style="padding-left: 10px">
<div class="name"><strong>Test</strong></div>
<div class="description">Foo</div>
</td>
</tr>
essentially my target is get the content of div name and div description, someone could explain how to do this? Thanks.
Something like this: jsfiddle
$(document).on("mouseover","tr", function(){
var name = $(this).find(".name").text();
var description = $(this).find(".description").text();
console.log("Name: "+name+"\nDecsription: "+description);
})
Don't forget ID of each element must be unique so your code is not correct because "#button2" must be unique, so this is always #button2 in your function.
Note the difference between text() and html(). I used .text() to get just the text without "strong" code. If you need it use html().
You could use innerHTML
$(this).find('name').innerHTML; //returns "test"
$(this).find('description').innerHTML; //returns "foo"
This will find the class within the current element, and return the values you need.
Since you already have an id on your element, accessing the name and description attributes is easy:
$('#button2').on('mouseover', function() {
var $res7 = $('#res-7');
// Access the two divs
var name = $res7.find('.name').text(); // or .html()
var description = $res7.find('.description').text(); // or .html()
// Print them out
console.log(name);
console.log(description);
});
Of course, this block of code should be inside a jQuery ready event handler.
I'm sure there is a cleaner way, but this should get you what you want.
$('#button2').on('mouseover', function()
{
console.log($(this).find(".name").html());
console.log($(this).find(".description")).html());
}

how to Javascript toggle ID of div generated on runtime

I am sending a Model to a View in MVC,
and for each "Person" in my Model, I want to create a button that says "Show Details", when the user clicks it, a div with more information about that person toggles.
I am generating a a href and div id assigned to each person ID like the following:
foreach (var person in Model.Persons)
{
<div>
Show Details
</div>
<div id="#Html.Raw("detailsDiv-" + #person.id)">
<!--Content Here -->
</div>
}
I want to create the javascript that toggles on a click event
So I want to write this script but with the unique id for each person:
I want to get the id of the div that needs to be toggled.
I tried writing the script inside the foreach loop so I can be able to read the #person.id value, but it didnt work:
<script>
$(document).ready(function () {
$("#showDetails-#person.id").click(function () {
$("#details-#person.id").toggle();
});
});
</script>
Can anyone help?
put a class to your links like class="showDetails".
Now you Can create a global Event for all that links:
$('.showDetails').click(function(e) {
var id = this.id // extract id.. split with '-' or whatever..
$('#details-' + id).toggle();
});
you could put the id in a tag like "person_id" and use a class to trigger the jquery event.
<div class="middle_right">
<a class="showDetails" href="#" person_id="#Html.Raw("showDetails-" + #person.id)">Show Details</a>
</div>
and in js
$(".showDetails").click(function () {
var person_id=$(this).attr("person_id")
});

how to recode my jquery/javascript function to be more generic and not require unique identifiers?

I've created a function that works great but it causes me to have a lot more messy html code where I have to initialize it. I would like to see if I can make it more generic where when an object is clicked, the javascript/jquery grabs the href and executes the rest of the function without the need for a unique ID on each object that's clicked.
code that works currently:
<script type="text/javascript">
function linkPrepend(element){
var divelement = document.getElementById(element);
var href=$(divelement).attr('href');
$.get(href,function (hdisplayed) {
$("#content").empty()
.prepend(hdisplayed);
});
}
</script>
html:
<button id="test1" href="page1.html" onclick="linkPrepend('test1')">testButton1</button>
<button id="test2" href="page2.html" onclick="linkPrepend('test2')">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
I'd like to end up having html that looks something like this:
<button href="page1.html" onclick="linkPrepend()">testButton1</button>
<button href="page2.html" onclick="linkPrepend()">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
If there is even a simpler way of doing it please do tell. Maybe there could be a more generic way where the javascript/jquery is using an event handler and listening for a click request? Then I wouldn't even need a onclick html markup?
I would prefer if we could use pure jquery if possible.
I would suggest setting up the click event in JavaScript (during onload or onready) instead of in your markup. Put a common class on the buttons you want to apply this click event to. For example:
<button class="prepend-btn" href="page2.html">testButton1</button>
<script>
$(document).ready(function() {
//Specify click event handler for every element containing the ".prepend-btn" class
$(".prepend-btn").click(function() {
var href = $(this).attr('href'); //this references the element that was clicked
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
</script>
You can pass this instead of an ID.
<button data-href="page2.html" onclick="linkPrepend(this)">testButton1</button>
and then use
function linkPrepend(element) {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
NOTE: You might have noticed that I changed href to data-href. This is because href is an invalid attribute for button so you should be using the HTML 5 data-* attributes.
But if you are using jQuery you should leave aside inline click handlers and use the jQuery handlers
<button data-href="page2.html">testButton1</button>
$(function () {
$('#someparent button').click(function () {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
$('#someparent button') here you can use CSS selectors to find the right buttons, or you can append an extra class to them.
href is not a valid attribute for the button element. You can instead use the data attribute to store custom properties. Your markup could then look like this
<button data-href="page1.html">Test Button 1</button>
<button data-href="page2.html">Test Button 1</button>
<div id="content">
</div>
From there you can use the Has Attribute selector to get all the buttons that have the data-href attribute. jQuery has a function called .load() that will get content and load it into a target for you. So your script will look like
$('button[data-href]').on('click',function(){
$('#content').load($(this).data('href'));
});
looking over the other responses this kinda combines them.
<button data-href="page2.html" class="show">testButton1</button>
<li data-href="page1.html" class="show"></li>
class gives you ability to put this specific javascript function on whatever you choose.
$(".show").click( function(){
var href = $(this).attr("data-href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
This is easily accomplished with some jQuery:
$("button.prepend").click( function(){
var href = $(this).attr("href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
And small HTML modifications (adding prepend class):
<button href="page1.html" class="prepend">testButton1</button>
<button href="page2.html" class="prepend">testButton2</button>
<div id="content"></div>
HTML code
<button href="page1.html" class="showContent">testButton1</button>
<button href="page2.html"class="showContent">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
JS code
<script type="text/javascript">
$('.showContent').click(function(){
var $this = $(this),
$href = $this.attr('href');
$.get($href,function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
});
</script>
Hope it helps.

How to change parameters in javascript function written in html

I have some function in html code.
<span id='test' onclick="test("1", "2")">Click Me</span>
after executing i need to replace this function by other with other parameters. can you advice if it is any opportuity to write this function not by eventlistener, but as html-attribute with the aim to see this function as html code, delete this
onclick="test("1", "2")
and add new one dynamically in html code
onclick="test("3", "4")
You'd have to change the attribute (as long as it can be represented as a string) or reference a global variable.
<span id='test' onclick="test(window.globalVar1, window.globalVar2)">Click Me</span>
However this probably shouldn't be done. It would be better to have test() call a function with your parameters.
var actualFunction = function() { // your actual function }
var wrapper = function() { actionFunction.apply(null, arrayOfArgs); }
Then the html-
<span id='test' onclick="wrapper()">Click Me</span>
Beginning, you have a syntax problem (You cannot use " in attribute value), change your HTML:
<span id='test' onclick="test('1', '2')">Click Me</span>
You change attribute onclick by jQuery:
$( document ).ready(function() {
$('#test').attr('onclick',"alert('3','4')");
});
JSFiddle:
http://jsfiddle.net/LACqP/
Enjoy your code!
If your must intrude your html with javascript then here:
HTML
<span id='test' onclick="test()">Click Me</span>
Javascript
// Note: This script must go before the html unless you have a onDocReady
var testA = 1,
testB = 2;
function test () {
// use testA & testB for testing
...
// test is over increment them
testA++;
testB++;
}

Categories

Resources