Add text from a variable to a tweet - javascript

I am trying to tweet text I get from a function executing a getJSON command, the tweet button I created opens twitter but with no text, I want it to automatically "paste" the quote the webpage is currently displaying. My basic html code is the following:
<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
<div class="col-md-8 show boxed text-center"> Text </div>
<div class="col-md-5 text-center author"> auth
</div>
<a class="tw-button" href="https://twitter.com/intent/tweet/?text=" data-size="large" target="_blank">
<button type="twbutton" class="btn btn-primary">Tweet quote</button>
</a>
My JS:
$(document).ready(function() {
gQuote();
function gQuote() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en",
function(data) {
var Quote = data.quoteText;
var Author = data.quoteAuthor;
var quoteShow = ""
var quoteAuthor = ""
quoteShow += "<h3 class='text-center'>" + Quote + "</h3>"
quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>"
$(".show").html(quoteShow);
$(".author").html(quoteAuthor);
});
};
$("#quoteClick").on("click",function() {
gQuote();
});
$(".tw-button").click(function(){
$(this).attr("href",'https://twitter.com/intent/tweet/?text='+ Quote);
});
});
I understand that the Quote variable was created within the previous function and I am not clear as to how I can "carry" it towards the twitter button.
I am using codepen so "target:_blank" is a must.

The Quote variable is local to the callback in the $.getJSON.
One (and the simplest) of the solutions is shifting the 'var Qoute' declaration to the callback of the $(document).ready callback, so that it is accessible to the '$(".tw-button").click' callback through the scope chain during the right hand search. Though, this is not very good for larger-scaled code.
$(document).ready(function() {
gQuote();
var Quote; //Declare variable here
function gQuote() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(data) {
Quote = data.quoteText; //Set it here
var Author = data.quoteAuthor;
var quoteShow = ""
var quoteAuthor = ""
quoteShow += "<h3 class='text-center'>" + Quote + "</h3>"
quoteAuthor += "<h4 class='text-center'>" + Author + "</h4>"
$(".show").html(quoteShow);
$(".author").html(quoteAuthor);
});
};
$("#quoteClick").on("click",function() {
gQuote();
});
$(".tw-button").click(function(){
$(this).attr("href",'https://twitter.com/intent/tweet/?text='+ Quote);
});
});

If I'm not mistaken all you need to do is declare your variables Quote and Author outside gQuote() function. Inside gQuote() you can assign them whatever you wish and pass their latest values to $(".tw-button").click() event. Make sure you got JSON object and parsed data from it right.
I made something similar as freecodecamp project. Have a look here if you have difficulties.

Related

Appending HTML+RDFa with JavaScript

My JavaScript script is not allowing to be marked up semantically. As you can see in my script below, I am using Schema.org and RDFa.
The problem is that when I validate my page, only the part before the append function is validated. This means that only type, headline, publisher and datePublished comes up.
How can I fix it? I suspect the problem here is the append function.
$(document).ready(function(){
$.getJSON(webhose_request, function(results){ //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
$(".webhose").append('<div vocab="http://schema.org/" typeOf="Article"><div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div><div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div></div>');
if(results.posts[i].thread.author){
$(".webhose").append('<div class="whpublished"><b>By:</b> <span property ="author">'+results.posts[i].thread.author+'</span></div>');
}
$(".webhose").append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> '+results.posts[i].thread.published.substring(0,10)+'</p></span></em> </div>');
//we check if there is an image for this posts then display
if(results.posts[i].thread.main_image){
$(".webhose").append('<div class="whimage"><img property="image" src="'+results.posts[i].thread.main_image+'" height="125" width="200"/></div>');
}
$(".webhose").append('<div property="articleBody" class="wharttext">'+articletext.substr(0,500)+'... <div class="whlink"><a property="url" href= '+results.posts[i].thread.url+'> Read full article »</a></div></div><br>');
}
});
});
I think the issue is that most of the parts of the article aren't in the <div vocab="http://schema.org/" typeOf="Article"> element. This can be shown to be true if one indents HTML from the first append:
<div vocab="http://schema.org/" typeOf="Article">
<div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div>
<div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div>
</div>
In the following I have changed the code to create the article div and then append the contents to it and then append it to the document. The following is untested but I think it might work.
$(document).ready(function() {
$.getJSON(webhose_request, function(results) { //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
var article = $('<div vocab="http://schema.org/" typeOf="Article"></div>');
article.append('<div property="headline" class="whtitel">' + results.posts[i].thread.title_full.substring(0, 110) + '</div>')
article.append('<div class="source"><b>Source:</b><span property="publisher"> ' + results.posts[i].thread.site + '</span></div>');)
if (results.posts[i].thread.author) {
article.append('<div class="whpublished"><b>By:</b> <span property ="author">' + results.posts[i].thread.author + '</span></div>');
}
article.append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> ' + results.posts[i].thread.published.substring(0, 10) + '</p></span></em> </div>');
//we check if there is an image for this posts then display
if (results.posts[i].thread.main_image) {
article.append('<div class="whimage"><img property="image" src="' + results.posts[i].thread.main_image + '" height="125" width="200"/></div>');
}
article.append('<div property="articleBody" class="wharttext">' + articletext.substr(0, 500) + '... <div class="whlink"><a property="url" href= ' + results.posts[i].thread.url + '> Read full article »</a></div></div><br>');
$(".webhose").append(article);
}
});
});

paragraph tags in tweet field from web page

I put together a quote machine as an exercise of freecodecamp.com. You click the button, you get a quote. Then, if you want, you can tweet the quote by clicking the "Tweet It" button. I had a lot of trouble figuring out how to get the quote to populate the tweet field. I finally just looked at someone else's code on the issue, and now it is populating.
The problem: it is populating <p> and </p> tags with every quote. Example:
"<p>When typography is on point, words become images.</p>
" Shawn Lukas
It's also annoying that the second set of quotation marks always appears on the line below next to the author's name.
I'm not sure how the tags are getting in there, but I'd like help clearing them out. Here's my code:
HTML
<div id="container">
<div class="content">
<div id="quote" class="triangle-isosceles">
<p>
<span class="msg"></span>
</p>
</div>
<p id="author"><span class="nme"></span></p>
</div>
<button type="button">Get Quote</button>
<a class="twitter-share-button" id="tweet-quote" target="_blank">
<button type="button" class="btn btn-primary">Tweet it!</button>
</a>
</div>
JS
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + "<p>— " + author + "</p>")
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + quote + '" ' + author));
});
});
</script>
I'm omitting the CSS. I can't get a jsfiddle to work (never can), but here's the CodePen link: https://codepen.io/dtarvin/pen/pePowj
Update: just found a quote with an apostrophe and got back those numbers instead of the symbol. Not sure how to handle that when the quotes are random.
Thanks!
you have "<p>— " + author + "</p>" in the append code, regarding the html entity code you need to parse the quote to switch them to the normal version. Also you might need to remove tags within the a[0].content variable. if you have no control over what is returned, you may need to do a lot more filtering to catch stuff like this.
Or if you have access to the serverside script, then use this to get the quote and return the cleansed quote.
For instance, if you visit the url https://quotesondesign.com/wp-json/posts you will see the <p> tags within the quote themselves.
So you basically need to clean the content of the content variable.
for instance to remvoe the p tag within the content string try:
var quote = a[0].content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '');
If you need these tags in to display then you could add a seperate function that on pressing the tweet it button, will do this for you.
So you have them on the browser but on tweeting its all striped and good on twitter
Try this it work
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + author);
var html = quote + author;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent( text ));
});
});
</script>

Jquery command not executing, can't see what I'm doing wrong

Im trying to access random quotes through an API using Jquery. I am very new to this so I'm sure there is a simple solution that I cannot see. Basically this is my HTML code:
<div class="col-md-6">
<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
</div>
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8 show boxed text-center">
Text
</div>
<div class="col-md-2">
</div>
</div>
My JS is this:
$(document).ready(function() {
$("#quoteClick").on("click", function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
json.forEach(function(x) {
html += "<div class = 'quote'>";
html += "<h3 '" + x.quoteText + "' "+ "'>";
html += "</div>";
});
     $(".show").html(html);
});
});
});
When I use console.log(json) I can print the object I'm querying from, but when I actually try to fish out a quote and print it on my web page nothing happens. I am using codepen.
You shouldn't be iterating over the object you get from the API. If you look at a single API call, one result I got looked like this:
{
"quoteText": "To be thoughtful and kind only takes a few seconds compared to the timeless hurt caused by one rude gesture.",
"quoteAuthor": "Byron Pulsifer",
"senderName": "",
"senderLink": "",
"quoteLink": "http:\/\/forismatic.com\/en\/4255d6ba93\/"
}
You just need to drop the forEach call, and your code will work.
Also (gavgrif noted this first in their answer), your HTML is malformed - you should have the text inside the h3.
This should be better:
$(document).ready(function() {
$("#quoteClick").click(function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
html += "<div class = 'quote'>";
html += "<h3>" + json.quoteText + "</h3>";
html += "</div>";
$(".show").html(html);
});
});
});

encodeURIComponent not working with Twitter button

I'm currently trying to make an app that tweets out the quote that's currently in the text bubble. However, when I use this line of code,
<a class="twitter-share-button" href="https://twitter.com/intent/tweet?text" + encodeURIComponent(quote.quote + ' - ' + quote.author);>Tweet</a>
It doesn't take me anywhere. Is there any way I could get this working or would I need to use an external Twitter button?
Thanks!
CodePen Link: http://codepen.io/Jelani/full/rOmrOJ/
You can't embed javascript in your markup like that. One approach you could take would be to add some code to your randomQuote function like this:
var randomQuote = function() {
... // current code
var text = quote.quote + ' - ' + quote.author;
$('.twitter-share-button').attr('href', "https://twitter.com/intent/tweet?text="+encodeURIComponent(text));
}
Another approach would be to move your quote variable declaration out of the randomQuote function and set an onclick on the twitter-share-button
<a class="twitter-share-button" onclick="goTweet()">Tweet</a>
that calls a function that does something like:
function goTweet() {
var text = quote.quote + ' - ' + quote.author;
window.location.href = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(text);
}

Unexpected identifier in Javascript for loop

This seems to work 75% of the time and the modal function executes with the parameters available, but every few buttons in the table I'll get a Uncaught SyntaxError: Unexpected identifier. Does this have to do with inproper closure? My google searches landed on that as a potential issue but I was unable to implement any of the solutions into my current method here.
html += '<thead><th>Question</th><th>Answer 1</th><th>Answer 2</th><th>Answer 3</th><th>Answer 4</th></thead>';
for (var i = 0; i < questions.length; i++) {
question = questions[i].question;
questionTitle = question.q;
answer1title = question.a1;
answer2title = question.a2;
html += '<tr><td class="question"><b>'
+ question.q
+ '</b></td><td class="answer1">'
+ question.a1
+ '</td><td class="answer2">'
+ question.a2
+ '</td><td class="answer3">'
+ question.a3
+ '</td><td class="answer4">'
+ question.a4
+ '</td><td class="edit">'
+ '<button onclick="openQuestionModal(\''+questionTitle+'\', \''+answer1title+'\', \''+answer2title+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'
+ '</td></tr>';
}
$('#questionsTable').append(html);
The problem is that any of questionTitle, answer1title, or answer2title may have a single quote in their values, which breaks the string concatenation you are attempting. You need to replace all occurrences of a single quote with an escaped single quote. So something like this:
http://jsfiddle.net/ZYnfc/2/
$(document).ready(function () {
var par = "I'm the problem";
var replacer = new RegExp("'", "g");
var new_btn = $('<button onclick="clicker(\'' + par.replace(replacer, "\\'") + '\');">ASDF</button>');
$("#main").append(new_btn);
});
function clicker(param) {
alert(param);
}
You'll have to take my example and apply it to your actual code, but the main point is the use of the replace method and the replacer regex for each of your variables you're concatenating in the function call.
There are better ways to append HTML to an area, especially when it comes to a table. And I would suggest binding events with jQuery, not inline. That's a different topic and is unrelated to your problem, although it could've helped avoid it in the first place.
May be you should escape the string before adding to onclick attribute:
+ '<button onclick="openQuestionModal(\''+ escape(questionTitle)+'\', \''+ escape(answer1title)+'\', \''+escape(answer2title)+'\')" class="btn btn-small btn-primary" id="questionEdit" type="button">Edit</button>'
And Use :
unescape('str_to_revert')// to get the data back inside your function.

Categories

Resources