JQuery Copy text & paste into textarea - javascript

I've created a javascript function that will take a hidden span, copy the text within that span and insert it into a single textarea tag on a website. I've written a function in JavaScript that does this (well, kinda, only after a few clicks), but I know there's a better way - any thoughts? The behavior is similar to a Retweet for twitter, but using sections of a post on a blog instead. Oh, and I'm also calling out to jquery in the header.
<script type="text/javascript">
function repost_submit(postID) {
$("#repost-" + postID).click(function(){
$("#cat_post_box").empty();
var str = $("span#repost_msg-" + postID).text();
$("#cat_post_box").text(str);
});
}
</script>

Based on the comment in your question, I am assuming you have something like this in your HTML:
copy post
And I am also assuming that because you are passing a post ID there can be more than one per page.
Part of the beauty of jQuery is that you can do really cool stuff to sets of elements without having to use inline Javascript events. These are considered a bad practice nowadays, as it is best to separate Javascript from your presentation code.
The proper way, then, would be to do something like this:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
And then you can have many more that look similar:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
<a href="#" id='copy-6' class='copy_link'>copy post</a>
<a href="#" id='copy-7' class='copy_link'>copy post</a>
Finally, you can write code with jQuery to do something like this:
$(function() { // wait for the DOM to be ready
$('a.copy_link').click(function() { // whenever a copy link is clicked...
var id = this.id.split('-').pop(); // get the id of the post
var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup
$('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas)
return false;
});
});
This is the best way to do it even if there is only one post in the page. Part of the problem with your code is that on the first click it BINDS the function, and in the subsequent clicks is when it finally gets called. You could go for a quick and dirty fix by changing that around to just be in document.ready.

$("#repost-" + postID).click(function(){
$("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element.
$("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be.
});
And wrap everything in a $(document).ready(function(){ /Insert the code here/ }) so that it will bind to $("#repost-" + postID) button or link when the DOM is loaded.

I had a problem with Paolo's example when I clicked on the link the text that appeared in #cat_post_box was "object Object". Once I added ".text()" to the end of that statement I worked.
var str = $('#repost_msg-' + id).text();
Thanks for you example Paolo!

Related

How to pass a variable in javascript to an HTML string

I am trying to pass a variable to the inline JavaScript but its not working.
var namealert = key;
$("#alerta").append("<div class='alert_item clearfix'><a href='#' id='delete_alert' onclick='localStorage.removeItem('" +namealert+ "'');'><img width='15px' style='margin-right:10px;opacity: 0.5;' src='img/error.png'></a><div class='date'>"+obj['0']+"</div><br><div class='title'>"+obj['1']+"</div><br><div class='msg'>"+obj['2']+"</div><br><a href='#' id='candidatar' onclick='candidatar()'><img width='100px' style='margin-right:10px;opacity: 0.8;' src='img/disponivel.png'></a></div>");
The output is:
<a href="#" id="delete_alert" onclick="localStorage.removeItem(" alerts_1481117090'');'>...</a>
I need it to be localStorage.removeItem('alerts_1481117090');
A lot of people have downvoted you but nobody's really given a concrete example of what we mean by "adding event handlers", since technically the onclick method you are using is an event handler (just not a good way to do what you are trying to do).
var $newElement = $("#alert")
.append("<div class='alert_item clearfix'>Click me!</div>");
// $newElement is a jQuery object returned by .append()
// set a click event handler. this is much better than doing the html
// onClick method you had in your question, because it requires no
// stringified javascript code evaluation.
$newElement.on("click", function (ev) {
alert("Hey, I was clicked! " + ev.target);
// your local storage code here instead
});
.alert_item {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="alert">
<!-- elements to append here -->
</div>
You're probably just getting into javascript by the looks of it, but don't get discouraged. It's a strange language for sure, but once you get more of a feel for how things work, there's a great book called "JavaScript, the Good Parts" on how the language can be used safely and powerfully.

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

jQuery load issue. Don't know how to approach this AJAX call

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

How do I make this link work in javascript

Ok basically I have this javascript file http://assets.revback.com/scripts/share1.js that basically adds a bunch of share buttons via javascript.
What I want to do, is change the twitter image link to use an url shortener:
so instead of:
<a href=\"http:\/\/twitter.com\/home?status=Interesting Post:(UURRLL)\" title=\"Click to share this page on Twitter\"><img src=\"http:\/\/assets.revback.com\/scripts\/images\/twitter.png\" border=\"0\"\/><\/a>
I want to use
<a href="#" onClick="window.location='http://ko.ly?action=shorten&uri=' + window.location + '&dest=twitter.com/?status=Reading ';"><img src=http://assets.revback.com/scripts/images/twitter.png"><\/a>
but I need that bottom one, to be written with javascript friendly syntax. i.e. like in the top one, instead of http://, you have http://
Lose the onclick. There is no benefit to it whatsoever, since it just acts like a normal link (except much more broken). Now you don't have to worry about escaping JavaScript inside JavaScript and the consequent \\\\\\\\ madness.
var buttonhtml= (
'<a href="http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading">'+
'<img src=http://assets.revback.com/scripts/images/twitter.png">'+
'</a>'
);
(Note that the encodeURIComponent, which is essential to correctly inserting your current URL into another URL without breaking, is also protecting you from HTML-injection, since < and & characters get %-encoded. Without that safeguard, any page that includes your script has cross-site-scripting vulnerabilities.)
Better still, lose the HTML string-slinging altogether and use DOM methods to create your content. Then you don't need to worry about & and other HTML escapes, and you don't have to hack your HTML together with crude, unreliable string replacing. You seem to be using jQuery, so:
var link= $('<a>', {href:'http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading'});
link.append('<img>', {src: 'http://assets.revback.com/scripts/images/twitter.png'});
link.appendTo(mydiv);
ETA: I'd replace the whole markuppy mess with a loop and the data broken out into a lookup. ie. something like:
(function() {
var u= encodeURIComponent(location.href);
var t= encodeURIComponent(document.title);
var services= {
Facebook: 'http://www.facebook.com/sharer.php?u='+u,
Twitter: 'http://ko.ly?action=shorten&uri='+u+'&dest=twitter.com/?status=Reading',
StumbleUpon: 'http://www.stumbleupon.com\/submit?url='+u+'&title='+t,
// several more
};
var share= $('<div class="ea_share"><h4>Share this with others!</h4></div>');
for (var s in services) {
share.append($('<a>').attr('href', services[s]).attr('title', 'Click to share this on '+s).append(
$('<img>').attr('src', 'http://assets.styleguidence.com/scripts/images/'+s.toLowerCase()+'.png')
));
}
$('#question .vt').append(share);
})();
Try this
<a href="#" onClick="window.location='http://site.com?action=shorten&uri='+
window.location + '&dest=twitter.com/?status=Reading;'">tweet this</a>
<a href="#" onClick="window.location='http://site.com?action=shorten&uri=' + window.location.href + '&dest=twitter.com/?status=Reading ';return false;">tweet this
Change the href of the link in the onclick attribute:
tweet this
The default action (going to the page designated by the href attribute) will always still be executed unless the event handler onclick receives a return value of false. So, changing the href before it happens will cause it to go to the page you want it to as long as you don't return false.

Categories