How to share a post with image using addThis plugin in jquery - javascript

How can i share a post in facebook with the image using addThis. I have written this code to share in facebook,twitter and mail.
Now i can able to post or share the content without having the image and am getting like this(Refer Image)What i get.
Please help me to post with the image and caption.
I have added my code in fiddle or even you can see it in this https://jsfiddle.net/x34nnwcs/
(function () {
addthis.init();
function navigatePage(e) {
var pageId = $(this).attr("id"),
$pageContent, sharingMarkup, content,
config = $.extend(true, {}, window.addthis_config),
share = $.extend(true, {}, window.addthis_share);
if (pageId != "pageContent") {
config["some_property"] = "some value";
share.title = $(this).html();
share.url = "http://" + pageId + ".not-a-tld";
share.photo = "http://res-5.cloudinary.com/demo/image/upload/dpr_1.0,f_auto,w_365,h_133,c_fill,g_south,o_60/group.jpg";
$pageContent = $("#pageContent");
sharingMarkup = $("#sharing_markup").html();
content = $(".pageC").html();
console.log(content);
$pageContent.html(content + sharingMarkup);
addthis.toolbox(".page_sharing_toolbox", config, share);
addthis.toolbox(".page_sharing_facebook", config, share);
}
$("#page1").click(navigatePage);
}
navigatePage.call(document.getElementById("pageContent"));
}());
<div id="pageContent">
<button id="page1">Page 1</button>
<div class='pageC'>
<img src='http://res-5.cloudinary.com/demo/image/upload/dpr_1.0,f_auto,w_365,h_133,c_fill,g_south,o_60/group.jpg'/>
<p>this is a simple paragraph that is meant to be nice and easy to type which is why there will be mommas no periods or any capital letters so i guess this means that it cannot really be considered a paragraph but just a series of run on sentences this should help you get faster at typing as im trying not to use too many difficult words in it although i think that i might start making it hard by including some more difficult letters I'm typing pretty quickly so forgive me for any mistakes i think that i will not just tell you a story about the time i went to the zoo and found a monkey and a fox playing together they were so cute and i think that they were not supposed to be in the same cage but they somehow were and i loved watching them horse</p>
<p>
</div>
</div>
<script id="sharing_markup" type="text/html">
<div class="page_sharing_facebook addthis_toolbox facebook_like">
<a class="addthis_button_facebook_like" title="Facebook Like"></a>
</div>
<div class="page_sharing_toolbox addthis_toolbox addthis_default_style" style="width:290px;">
<div class="share-icons" id="share-icons">
<a class="addthis_button_email left" title="Email"></a>
<a class="addthis_button_facebook left" title="Facebook"></a>
<a class="addthis_button_twitter left last" title="Twitter"></a>
<a class="addthis_button_google left" title="Google"></a>
</div>
</div>
</script>
<script id="page1content" type="text/html">
</script>
<!-- the async parameter has been added, query parameter style, to the hash so that things won't render until you explicitly call addthis.init() -->
<script src="//s7.addthis.com/js/300/addthis_widget.js#async=1&pubid=atblog"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>

you need only to add this meta tag to your <Head> on HTML code
<meta content="your image source" property="og:image">

Related

Change href to anchor on same page

This is probably an easy question but I couldn't figure it out: I am trying to change a href to a variable using JavaScript/jQuery. I am using the Bootstrap Collapse Plugin. My code looks basically like this:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Collapsible Panel</h2>
<p>Click on the collapsible panel to open and close it.</p>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1">Collapsible panel</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">Panel Body</div>
<div class="panel-footer">Panel Footer</div>
</div>
</div>
</div>
</div>
however panels are created dynamically and at some point, I have to change the ids and hrefs. E.g.:
...
to
...
If I use Javascript
var link = newId();
//newId is part of the plugin, but is based on the previous href
element.href = "#" + link;
the html changes into
...
(which is the full address of the page, with the anchor)
and it does not work anymore. However hardcoding it like this would work:
element.href = "#361cd655-ad54-4cd5-aeb7-a3da9553c1e9";
I've tried quite a few things but I always get similar results.
I can figure out that newId() most likely involves the previous href attribute because if you were to have an anchor element:
<a href='page'></a>
Even though it is a relative URL, the code
document.getElementsByTagName("a")[0].href
would return the full URL (eg. https://serveradmin.xyz/page)
A possible solution is instead of getting the current href, when changing it, also have a variable set to the new value. For example:
var linkHref = 1;
document.getElementsByTagName("a")[0].href = linkHref;
//when you next want to change it, don't get the current href, instead, use the link variable
linkHref++;
document.getElementsByTagName("a")[0].href = linkHref;
Alternatively, you could do this:
function getRelativeHref(href) {
return href.replace(window.location.href + "#", "");
}
If the href parameter was https://stackoverflow.com/posts/51951100/edit#test then it would return #test.
I think you have some problems in your newId function. You need something like that:
btn.addEventListener("click", () =>
Array.from(
document.querySelectorAll('a'),
a => a.href = "#" + newId())
)
function newId () {
return Math.random().toString(36); // simple random string.
};
...
<button id="btn">Change!</button>

Using JQuery methods to find the class. Using a JavaScript file in a rails application

The texts 'pearl' and 'diamond' are elements in an array stored in localStorage. I couldn't find any good resources to help me pull the data from localStorage so I can display and manipulate the data in rails. Thus, I wrote a function in my application.js file to help me find the texts and the surrounding classes.
Here's the info in html.
<div class="ruby-gem">
<a target="_blank" href="https://www.website.com/pearl">pearl</a>
<img class="star-pic" src="/assets/star-gray.png" alt="star pic">
</div>
<div class="ruby-gem">
<a target="_blank" href="https://www.website.com/diamond">diamond</a>
<img class="star-pic" src="/assets/star-gray.png" alt="star pic">
</div>
Here's my function in the application.js file. Right now the variable findSrc is undefined.
function checkStorage(){
var storage = JSON.parse(localStorage.getItem("rubygems"))
var gems = $(".ruby-gem a").map(function(){
return $(this).text()
}).get()
for (var i = 0; i < gems.length; i++){
if(storage.includes(gems[i])){
var gemFavorite = gems[i]
var findDiv = $("a:contains(gemFavorite)")
var findImgClass = findDiv.next()
var findSrc = $(findImgClass).find("img").attr("src")
if(findSrc == "/assets/star-gray.png"){
$(findImgClass).attr("src", "/assets/star-blue.png")
}
}
}
}
The ultimate goal is to change the image from a gray star to a blue star if the item(s) are located in localStorage. This is probably not the best way to do it but I couldn't figure out a nicer solution.
Any advice would be greatly appreciated.
You have neglected to insert the gemFavorite variable into the selector string correctly.
var findDiv = $("a:contains(" + gemFavorite + ")")
Why do you store them in localStorage? Where do 'pearl' and 'diamond' come from?
I could imagine something like they're data from the previous page?
If i were you i would store the array in the params, when it's only two we are talking about.
For example
I'm only guessing
Previous page:
<a href="link_to_the_page_your_showing?#{{p: "pearl", d:"diamond"}.to_query}">
Go blue star!</a>
<!-- output in the url on next page: "d=diamond&p=pearl" -->
Go boring gray star!
Your page:
<!-- Using erb to manipulate the src in img -->
<div class="ruby-gem">
<a target="_blank" href="https://www.website.com/pearl">pearl</a>
<img class="star-pic" src="/assets/<%= params[:p] == "pearl" ? "star-
blue" : "star-gray" %>.png" alt="star pic">
</div>
<div class="ruby-gem">
<a target="_blank" href="https://www.website.com/diamond">diamond</a>
<img class="star-pic" src="/assets/<%= params[:d] == "diamond" ? "star-
blue" : "star-gray" %>.png" alt="star pic">
</div>

JavaScript /Jquery : A for loop function with some special usage

This application have 2 components, a HTML page which contain some element and a JavaScript to generate buttons.
I will try to give out a simplify example in the question for now, but if there's something unclear then i would upload the full code later.
I am using HandleBar.js to generate different contents in the html but don't worry if you don't have any idea about this plugin i will make another non-handlebar.js version.
Consider the Html part looks like below:
HandleBar.js version
//example:
//{{feedId}} = 0t454g465754754h456
//{{url}} = www.jegdo.co.uk
{{each}}
<div class="feedIdChecker">{{feedId}}</div>
<div class="{{feedId}}-EditRegionUrl" >{{url}}</div>
<button class="output-{{feedId}}">Output</button>
{{/each}}
Then i have a JQuery function which would output the url
var feedId = $(".feedIdChecker").html();
$('".output-'+feedId+'"').click(function(){
var postUrl = $('".'+feedId+'-EditRegionUrl"').html();
console.log(postUrl );
});
});
}
I found there's no way to identify which button is which. Since i need to declare the var feedID outside the button, it would always get the first feedID it founds and append to all buttons, how may i solve it? Please tell me if this question is confuse, i will try to explain it in a better way.
There's lots of people trying to help me but it seem i need to give out some more details in order for better understanding:
Javascript:
var initRegionEdit = function(){
var feedId = $(".feedIdChecker").html();
$(".CTHK").click(function(){
var postUrl = ($(this).prev('div').html());
})
}
HTML
<div class="EditRegionUrl" >{{url}}</div>
<div class="feedIdChecker">{{feedId}}</div>
{{#if region}}
<span class="dropdown"><i class="fa fa-map-marker" aria-hidden="true" style="color:gray;"></i>
<span class="result-date result-date-region" type="button" data-toggle="dropdown">{{region}}
<span class="caret"></span></span>
<ul class="dropdown-menu" style="min-width:100px;text-align:center;">
<li class="CTHK" data-url="{{url}}" style=" margin-top: 0px !important;margin-bottom: 0px !important;">Hong Kong</li><div class="divider"></div>
<li class="CTTW" style=" margin-top: 0px !important;margin-bottom: 0px !important;">Taiwan</li><div class="divider"></div>
</ul>
</span>
{{/if}}
I wish above information can help
So when you select $(".feedIdChecker") you actually get an array of all matching elements, but as soon as you call .html it only gets you the first. So to solve your issue we need to loop over all the $(".feedIdChecker")s like so:
$(".feedIdChecker").each(function(i, e) {
var feedID = $(e).html();
$('.output-'+feedID).click(function(){
var postUrl = $("." + feedID + "-EditRegionUrl").html();
console.log(postUrl);
});
});
This will attach the click handler to each of the buttons.
You could use the handlebars.js each/index feature to do this:
<button id="whatever-{{#index}}"
class="output-{{feedId}}">
Output
</button>
I'm assuming you need an answer on how to apply a unique id to each button, not how to bind click handlers to them (which other people have answered anyway)
May this version be quicker and with less code.
$('[class*=output-]').click(function() {
var feedId = this.className.split("-")[1];
var postUrl = $('.EditRegionUrl-' + feedId).html();
alert(postUrl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="feedIdChecker">1</div>
<div class="EditRegionUrl-1" >URL1</div>
<button class="output-1">Output1</button>
<div class="feedIdChecker">2</div>
<div class="EditRegionUrl-2" >URL2</div>
<button class="output-2">Output2</button>
Can you just put url in the button and a generic class:
<button class="output-{{feedId}} btn-class" data-url="{{url}}">Output</button>
and then
$('.btn-class').click(function(){
console.log($(this).data('url') );
});
Or even just without changing your markup at all
$("button").click(function(){
console.log($(this).prev('div').text());
});

Changing URL in string to clickable link while changing its value

For a little webapp, I'm using JS to change a url inside a string to a clickable url, while changing the url to say 'tap here'. The problem however is if I keep the URl the same, without changing it to 'tap here' it all works fine. But if I change it, the clickable link links to an error page:
Not Found
The requested URL /client/http://www.google.com'
target='_blank'>tap here was not found on this server.
Here's the code I'm using that works (without changing to 'tap here')
$('.discussion').ready(function(){
$('.discussion #messages p').each(function(){
var str = $(this).html();
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig
var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>");
$(this).html(replaced_text);
});
});
And this is the one I want to work, but gives the error:
$('.discussion').ready(function(){
$('.discussion #messages p').each(function(){
var str = $(this).html();
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig
var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>tap here</a>");
$(this).html(replaced_text);
});
});
[EDIT] and here's the HTML
<ol class="discussion" scroll-bottom="replies">
<div ng-class="getClass($index)" ng-repeat="reply in replies track by $index">
<li ng-repeat="item in reply.text.replace('?','.').replace('!','.').split('. ') track by $index" class="fix-clutter">
<div class="avatar">
<img ng-src="{{reply.avatar}}">
</div>
<div id="messages" class="animated slideInUp">
<p class="animated fadeInUp">{{item}}</p>
</div>
</li>
</div>
</ol>
I copied and pasted your code here: http://plnkr.co/edit/CK2vJdeIxtN1Bvt7Kce5?p=preview with the following HTML:
<div class="discussion">
<div id="messages">
<p>
http://stackoverflow.com/questions/32395188/changing
</p>
<p>
http://stackoverflow.com/questions/32395188/changing
</p>
</div>
</div>
Everything works pretty well on this specific scenario. Can you paste your HTML?
However the regex it's not working right. If you add "dashes" on your URI, The regex fail to get the full URI and it breaks on the dash.
Update:
I checked again... and the problem is 90% caused by the regex rule.
Another case where is breaking is when you have already on your html the link with the "href tag" as the code below:
<div class="discussion">
<div id="messages">
<p>
<a href="http://stackoverflow.com/questions/32395188/changing'>LINK</a>
</p>
</div>
</div>

making a simple quiz system with direct answer

I know there are a lot of free/paid quiz systems out there, but none are customizable enough, especially that I need it in RTL direction.
Anyway, I have made this simple script: fiddle
<!-- question 1 -->
<div id="01">hello there
<br />
<input id="01_correct_btn" type="button" onclick="getElementById('01_correct').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_wrong_a').style.display='none';getElementById('01_wrong_b').style.display='none'" />Hi
<br />
<input id="01_wrong_a" type="button" onclick="getElementById('01_wrong').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_correct_btn').style.display='none';
getElementById('01_wrong_b').style.display='none'" />bye
<br />
<input id="01_wrong_b" type="button" onclick="getElementById('01_wrong').style.display = 'block';
getElementById('01_continue').style.display = 'block'; this.style.display = 'none'; getElementById('01_correct_btn').style.display='none';
getElementById('01_wrong_a').style.display='none'" />thanks
<br />____________________
<div id="01_correct" style="display:none">yep, you're right...
<br />
</div>
<div id="01_wrong" style="display:none">You are so wrong
<br />
</div>
<input style="display:none" type="button" id="01_continue" onclick="getElementById('01').style.display = 'none';
getElementById('02').style.display = 'block'" value="continue" />
</div>
<!-- question 2 -->
<div id="02" style="display:none">question 2: Welcome to the real world</div>
1: How can I hide all wrong answers without having to add all their ids (getElementByClassName didn't work)
2: Instead of re-copying the script for each question, can this be done by JavaScript where in each new form:
a. a "correct_btn" displays a "correct_note" and hides all other buttons
b. "wrong_btn"s display a "wrong_note" and hides all other buttons
c. both "correct_btn" and "wrong_btn"s will display the continue button
d. "continue" button hides current div/form and displays next one
It would be much easier this way to create as much questions as possible.
Thank you very much.
I would suggest looking at the HTML class system. As you can assign one class to multiple items. Then just create a script instead of calling the onclick javascript event.
I know you requested javascript, but you tagged JQuery and as I feel a JQuery script would serve you better for what you are trying to do I suggested that. Doing this with Javascript could get very wordy and complicated.
HTML
<div id="Q1">Hello There<br/>
<div class = "Q1 correct choice"><input type="button"/>Hi</div>
<div class = "Q1 wrong choice"><input type="button"/>Bye</div>
<div class = "Q1 wrong choice"><input type="button"/>Thanks</div>
</div>
<div id="Q1_Correct" style="display: none;">You are correct</div>
<div id="Q1_Wrong" style="display: none;">You are wrong</div>
You can also set up a generic correct/wrong message to be displayed.
Now, using JQuery would probably be easiest... like in this fiddle : http://jsfiddle.net/p5YY4/1/ (its not perfect, but some styling should solve some click issues... but I think you can get the gist)
JQuery
$('.choice').on('click', function() {
var parent = $(this).parent().attr('id');
if($(this).hasClass('correct')){
$('.choice').hide();
var response = "#" + parent + "_Correct";
$(response).show();
}
if($(this).hasClass('wrong')){
$('.choice').hide();
var response = "#" + parent + "_Wrong";
$(response).show();
}
});
Let me know if you have any questions about this.
For making the script native to one document here is what you would need to set up to get it to work :
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//The script I have already provided should go here
});
</script>
You can also create a separate document and call it lets say quizWorker.js
and then using the same layout as I just stated (in the js file I would also put the script in the $(document).ready function)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript" src="quizWorker.js"></script>

Categories