Implement opt-in Facebook like button - javascript

I've implemented a facebook like button into my (html) website. Now german data protection laws want webpages to be opt-in. Other websites do this by not immediately showing the facebook like but instead showing a button saying "activate facebook button" and when this button is clicked they replace it with the real facebook button.
So it requires two clicks, but this is ok for me. An example is this webpage.
I know html and php but got no clues about javascript (yet). I'd like to know how to implement this: how can I replace the fake button with the facebook one upon clicking?

Looking in their source, they site is using a function they called button2iframe - here it is:
function button2iframe(id,link){
//alert(id);
var substr = link.split("?");
var url = substr[0];
substr.reverse();
substr.pop();
substr.reverse();
var params = substr.join("?");
params = params.split("&");
var k;
var param = "";
var paramname = "";
for( var k=0; k<params.length; k++ ) {
param = params[k].split("=");
if(param.length>1){
if(param.length>2){
paramname = param[0];
param.reverse();
param.pop();
param.reverse();
param[1] = param.join("=");
param[0] = paramname;
}
param[1] = encodeURIComponent(param[1]);
}
params[k] = param.join("=");
}
params = params.join("&");
link = url+"?"+params;
jQuery(function ($) {
$("#"+id).html($('<iframe allowtransparency="true" frameborder="0" scrolling="no" src="'+link+'" id="iframe_'+id+'"/>'));
});
}
And this is what the associated markup for the facebook button looks like:
<li class="wpsoptin_facebook" id="wpsoptin_facebook_39429">
<div class="wpsoptin_medium">
<a class="wpsoptin_sharerlink" href="javascript:button2iframe('wpsoptin_facebook_39429','FACEBOOK LIKE BUTTON IFRAM URL GOES HERE')">Facebook aktivieren</a>
<div class="wpsoptin_sharerend"></div>
</div>
</li>
This code requires you include jQuery in your site as well.

try this if you dont want to use jquery, just remove the couple of line provided Nathan Anderson good answer
//jQuery(function ($) {
// $("#"+id).html($());
document.getElementById(id).innerHTML = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="'+link+'" id="iframe_'+id+'"/>'
///});

Related

display clickable Amazon image links from JAVA to HTML

have a simple calculation that if the selected 2 radio is true it will display the correct link to the div where you can find it. the link is now clickable and opens the right website/URL thanks to User: imvain2 who helped with some of the code. Now when I put an Amazon link in it, it only displays the URL and not the Amazon affiliate clickable Image link.
<div id="DisplayResults"></div>
function create_link(url, target_obj){
var a = document.createElement('a');
var linkText = document.createTextNode(url);
a.appendChild(linkText);
a.title = url;
a.href = url;
target_obj.appendChild(a);
}
function Selectport() {
var aOpticalin = document.getElementById("aOpticalin");
var aOpticalout = document.getElementById("aOpticalout");
var astereoout = document.getElementById("astereoout");
var astereoin = document.getElementById("astereoin");
var DisplayResults = document.getElementById("DisplayResults");
if(astereoout.checked && aOpticalin.checked){
create_link(<iframe style="width:120px;height:240px;" marginwidth="0"
marginheight="0" scrolling="no" frameborder="0" src="//ws-
na.amazon-adsystem.com/widgets/q?
ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=
US&source=ac&ref=
tf_til& ad_type=product_link&tracking_id=whatsmycable-
20&marketplace=amazon&region=US&placement=B01HGHNCMW&asins=
B01HGHNCMW&linkId=
f3759832fc138a941ade9bde6128b083&show_border=
true&link_opens_in_new_window=
false&price_color=333333&title_color=000000&bg_color=d1d1d1">
</iframe>,DisplayResults);
}
}
That function was originally created based on simply creating a link from a URL. If you would like to append actual precreated HTML, you can use innerHTML.
Make sure to wrap your code in single quotes (apostrophes) if your code has double quotes in it.
DisplayResults.innerHTML += 'Your iframe code goes here';

Get url query string and use as src on iframe

I'm completely new at javascript and I'm wondering about something really elementary here. I've got an iFrame that I want a dynamic src on. This src(source) should just be a variable. And then a script sets that variable before the frame is loaded.
It's actually a webpart in Sharepoint 2010, so I set up the webpart and edit it's HTML source to something like this:
<script language="JavaScript">
var qs = getQueryStrings();
var myParam = qs["myParam"];
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
} </script>
<iframe height="500" src="(myParam);" width="800"></iframe>
I'm not even sure the syntax is correct. Basically, I want to insert the variable into the src of the iframe.
you have to give some class or ID to your Iframe.
And then you can call a function which will give src to i frame dyanmically.
from client side use this:
$('#ID_of_Iframe').attr('src','NEW SRC hERE');
Example: $('#ID_of_Iframe').attr('src','www.google.com');
Make your links like this:
File1.PDF
or:
<iframe name='myPdfFrameName'></iframe>
File1.PDF
function loadFrame(href) {
window.frames['myPdfFrameName'].location = href;
return false;
}
EDIT: Easiest is probably using target attribute of a link:
<a href='file1.pdf' target='myPdfFrameName'>File1.pdf</a>

why call flash function from javascript work but FileReference don't work in flash?

I need call flash function from javascript. I use flash.external and addCallback to do this. all things work well but when I use FileReference in my flash, function did not open my browser ...
please see below describtion:
I call my function in javascript with this code:
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
you can see all my HTML as below:
<html>
<head>
<title>Upload test</title>
</head>
<script>
function hello (size) {
alert ("size hast: " + size);
}
function sendToFlash(val){
var flash = getFlashObject();
flash.new_browser(val);
}
var flash_ID = "Movie2";
var flash_Obj = null;
function getFlashObject(){
if (flash_Obj == null){
var flashObj;
if (navigator.appName.indexOf( "Microsoft" ) != -1){
flashObj = window[flash_ID];
}
else{
flashObj = window.document[flash_ID];
}
flash_Obj = flashObj;
}
return flash_Obj;
}
</script>
<body>
<center>
<embed width="560" height="410" type="application/x-shockwave-flash"
flashvars="sampleVars=loading vars from HTML"
salign="" allowscriptaccess="sameDomain" allowfullscreen="false" menu="true" name="Movie2"
bgcolor="#ffffff" devicefont="false" wmode="window" scale="showall" loop="true" play="true"
pluginspage="http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"
quality="high" src="Movie2.swf">
</center>
<input type="button" value="Browse" onclick="sendToFlash('Hello World! from HTML');" />
</body>
</html>
when I click Browse in html page, javascript call sendToFlash function and SendToFlash function send my string (Hello World! from HTML) to flash.
in flash I get this string with below code:
resultsTxtField.text = "";
uploadButton.onPress = function () {
return browse_file("Hello World! from Flash");
}
import flash.external.*;
ExternalInterface.addCallback("new_browser", this, browse_file);
function browse_file (my_test_val) {
_root.resultsTxtField.text = "val: " + my_test_val;
import flash.net.FileReference;
var fileTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
fileTypes.push(imageTypes);
var fileListener:Object = new Object();
var btnListener:Object = new Object();
var fileRef:FileReference = new FileReference();
fileRef.addListener(fileListener);
fileRef.browse(fileTypes);
fileListener.onCancel = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Upload Cancelled\n";
}
fileListener.onSelect = function(file:FileReference):Void
{
_root.resultsTxtField.text += "File Selected: " + file.name + " file size: "+ file.size + " file type: " + file.type;
getURL("javascript:hello("+file.size+");");
}
}
I have only one Scene and this code is on root of this Scene. and I have one movie clip named uploadButton and has only a rectangle that work as button in this sample.
when you click on rectangle browse_file("Hello World! from Flash"); called and a browser open that you can select a photo to upload.
when you click on browse in html same process must do but as you see variable send to function but browser to select a photo did not open any more.
I try several ways. for example I set new function to open only picture browser or set new Scene or use gotoAndPlay and more but there is another problem.
you can download my source from below link:
http://www.4shared.com/zip/YTB8uJKE/flash_uploader.html
note that javascript onclick="sendToFlash('Hello World! from HTML');" don't work in direct opening. you must open it in localhost.
I'll be so so happy for any clue.
thanks so much
Reza Amya
You can't programmatically call browse(), it has to be from a mouse click inside Flash: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#browse()
In Flash Player 10 and Flash Player 9 Update 5, you can only call
this method successfully in response to a user event (for example, in
an event handler for a mouse click or keypress event). Otherwise,
calling this method results in Flash Player throwing an Error
exception.
after a day reading I know that it is impossible for security reasons.
then you can't open file reference with addCallback javascript code any way. for more information read fileReference browse from js, simulate keypress in flash workaround
Thanks again
Reza Amya

How can i rerender Pinterest's Pin It button?

I'm trying to create and manipulate the Pin It button after page load. When i change the button properties with js, it should be rerendered to get the functionality of pinning dynamically loaded images. So, does Pinterest have any method like Facebook's B.XFBML.parse() function?
Thanks...
Just add data-pin-build attribute to the SCRIPT tag:
<script defer
src="//assets.pinterest.com/js/pinit.js"
data-pin-build="parsePinBtns"></script>
That causes pinit.js to expose its internal build function to the global window object as parsePinBtns function.
Then, you can use it to parse links in the implicit element or all of the links on the page:
// parse the whole page
window.parsePinBtns();
// parse links in #pin-it-buttons element only
window.parsePinBtns(document.getElementById('pin-it-buttons'));
Hint: to show zero count just add data-pin-zero="1" to SCRIPT tag.
The best way to do this:
Remove the iframe of the Pin It button you want to manipulate
Append the html for the new button manipulating it as you wish
Realod their script - i.e. using jQuery:
$.ajax({ url: 'http://assets.pinterest.com/js/pinit.js', dataType: 'script', cache:true});
To render a pin-it button after a page has loaded you can use:
<a href="..pin it link.." id="mybutton" class="pin-it-button" count-layout="none">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" width="43" height="21" title="Pin It" />
</a>
<script>
var element = document.getElementById('mybutton');
(function(x){ for (var n in x) if (n.indexOf('PIN_')==0) return x[n]; return null; })(window).f.render.buttonPin(element);
</script>
Assuming of course the assets.pinterest.com/js/pinit.js is already loaded on the page. The render object has some other useful methods like buttonBookmark, buttonFollow, ebmedBoard, embedPin, embedUser.
I built on Derrek's solution (and fixed undeclared variable issue) to make it possible to dynamically load the pinterest button, so it can't possibly slow down load times. Only tangentially related to the original question but I thought I'd share anyway.
at end of document:
<script type="text/javascript">
addPinterestButton = function (url, media, description) {
var js, href, html, pinJs;
pinJs = '//assets.pinterest.com/js/pinit.js';
//url = escape(url);
url = encodeURIComponent(url);
media = encodeURIComponent(media);
description = encodeURIComponent(description);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
$('#pinterestOption').html(html);
//add pinterest js
js = document.createElement('script');
js.src = pinJs;
js.type = 'text/javascript';
document.body.appendChild(js);
}
</script>
in document ready function:
addPinterestButton('pageURL', 'img', 'description');//replace with actual data
in your document where you want the pinterest button to appear, just add an element with the id pinterestOption, i.e.
<div id="pinterestOption"></div>
hope that helps someone!
Here's what I did.
First I looked at pinit.js, and determined that it replaces specially-marked anchor tags with IFRAMEs. I figured that I could write javascript logic to get the hostname used by the src attribute on the generated iframes.
So, I inserted markup according to the normal recommendations by pinterest, but I put the anchor tag into an invisible div.
<div id='dummy' style='display:none;'>
<a href="http://pinterest.com/pin/create/button/?
url=http%3A%2F%2Fpage%2Furl
&media=http%3A%2F%2Fimage%2Furl"
class="pin-it-button" count-layout="horizontal"></a>
</div>
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js">
</script>
Then, immediately after that, I inserted a script to slurp up the hostname for the pinterest CDN, from the injected iframe.
//
// pint-reverse.js
//
// logic to reverse-engineer pinterest buttons.
//
// The standard javascript module from pinterest replaces links to
// http://pinterest.com/create/button with links to some odd-looking
// url based at cloudfront.net. It also normalizes the URLs.
//
// Not sure why they went through all the trouble. It does not work for
// a dynamic page where new links get inserted. The pint.js code
// assumes a static page, and is designed to run "once" at page creation
// time.
//
// This module spelunks the changes made by that script and
// attempts to replicate it for dynamically-generated buttons.
//
pinterestOptions = {};
(function(obj){
function spelunkPinterestIframe() {
var iframes = document.getElementsByTagName('iframe'),
k = [], iframe, i, L1 = iframes.length, src, split, L2;
for (i=0; i<L1; i++) {
k.push(iframes[i]);
}
do {
iframe = k.pop();
src = iframe.attributes.getNamedItem('src');
if (src !== null) {
split = src.value.split('/');
L2 = split.length;
obj.host = split[L2 - 2];
obj.script = split[L2 - 1].split('?')[0];
//iframe.parentNode.removeChild(iframe);
}
} while (k.length>0);
}
spelunkPinterestIframe();
}(pinterestOptions));
Then,
function getPinMarkup(photoName, description) {
var loc = document.location,
pathParts = loc.pathname.split('/'),
pageUri = loc.protocol + '//' + loc.hostname + loc.pathname,
href = '/' + pathToImages + photoName,
basePath = (pathParts.length == 3)?'/'+pathParts[1]:'',
mediaUri = loc.protocol+'//'+loc.hostname+basePath+href,
pinMarkup;
description = description || null;
pinMarkup = '<iframe class="pin-it-button" ' + 'scrolling="no" ' +
'src="//' + pinterestOptions.host + '/' + pinterestOptions.script +
'?url=' + encodeURIComponent(pageUri) +
'&media=' + encodeURIComponent(mediaUri);
if (description === null) {
description = 'Insert standard description here';
}
else {
description = 'My site - ' + description;
}
pinMarkup += '&description=' + encodeURIComponent(description);
pinMarkup += '&title=' + encodeURIComponent("Pin this " + tagType);
pinMarkup += '&layout=horizontal&count=1">';
pinMarkup += '</iframe>';
return pinMarkup;
}
And then use it from jQuery like this:
var pinMarkup = getPinMarkup("snap1.jpg", "Something clever here");
$('#pagePin').empty(); // a div...
$('#pagePin').append(pinMarkup);
I rewrote the Pinterest button code to support the parsing of Pinterest tags after loading AJAX content, similar to FB.XFBML.parse() or gapi.plusone.go(). As a bonus, an alternate JavaScript file in the project supports an HTML5-valid syntax.
Check out the PinterestPlus project at GitHub.
The official way to do this is by setting the "data-pin-build" attribute when loading the script:
<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>
Then you can render your buttons dynamically like so:
// render buttons inside a scoped DOM element
window.parsePins(buttonDomElement);
// render the whole page
window.parsePins();
There is also another method on this site which lets you render them in JavaScript without the script tag.
Here is what i did.. A slight modification on #Derrick Grigg to make it work on multiple pinterest buttons on the page after an AJAX reload.
refreshPinterestButton = function () {
var url, media, description, pinJs, href, html, newJS, js;
var pin_url;
var pin_buttons = $('div.pin-it a');
pin_buttons.each(function( index ) {
pin_url = index.attr('href');
url = escape(getUrlVars(pin_URL)["url"]);
media = escape(getUrlVars(pin_URL)["media"]);
description = escape(getUrlVars(pin_URL)["description"]);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
index.parent().html(html);
});
//remove and add pinterest js
pinJs = '//assets.pinterest.com/js/pinit.js';
js = $('script[src*="assets.pinterest.com/js/pinit.js"]');
js.remove();
js = document.createElement('script');
js.src = pinJs;
js.type = 'text/javascript';
document.body.appendChild(js);
}
});
function getUrlVars(pin_URL)
{
var vars = [], hash;
var hashes = pin_URL.slice(pin_URL.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Try reading this post http://dgrigg.com/blog/2012/04/04/dynamic-pinterest-button/ it uses a little javascript to replace the pinterest iframe with a new button and then reloads the pinit.js file. Below is the javascript to do the trick
refreshPinterestButton = function (url, media, description) {
var js, href, html, pinJs;
url = escape(url);
media = escape(media);
description = escape(description);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
$('div.pin-it').html(html);
//remove and add pinterest js
pinJs = $('script[src*="assets.pinterest.com/js/pinit.js"]');
pinJs.remove();
js = document.createElement('script');
js.src = pinJs.attr('src');
js.type = 'text/javascript';
document.body.appendChild(js);
}
Their pinit.js file, referenced in their "Pin it" button docs, doesn't expose any globals. It runs once and doesn't leave a trace other than the iframe it creates.
You could inject that file again to "parse" new buttons. Their JS looks at all anchor tags when it is run and replaces ones with class="pin-it-button" with their iframe'd button.
this works fine for me: http://www.mediadevelopment.no/projects/pinit/ It picks up all data on click event
I tried to adapt their code to work the same way (drop in, and forget about it), with the addition that you can make a call to Pinterest.init() to have any "new" buttons on the page (eg. ajax'd in, created dynamically, etc.) turned into the proper button.
Project: https://github.com/onassar/JS-Pinterest
Raw: https://raw.github.com/onassar/JS-Pinterest/master/Pinterest.js
As of June 2020, Pinterest updated the pin js code to v2. That's why data-pin-build might not work on
<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>
Now it works on pinit_v2.js
<script async defer src="//assets.pinterest.com/js/pinit_v2.js" data-pin-build="parsePins"></script>

Passing javascript variable from iframe to URL

Lets say I have a function like this:
<script type="text/javascript">
function ReturnURL()
{
var url = document.URL;
var url2 = url.split("=");
var urlID = url2[url2.length-1];
//window.open('http://localhost/POSkill/skillshow.aspx?user_id =' + urlID);
return urlID;
}
</script>
And I also have iframe in my html file which is something like below:
<iframe id="showSkill" scrolling="yes" src="http://localhost/POSkill/skillshow.aspx?user_id = ReturnURL()" height="350" runat="server" ></iframe>
Now all I want to do is to send the urlID value of javasrcipt as the user_id value in iframe. I have tried by using user_id = ReturnURL() but its not working.
How can I do this?
Thanks in Advance.
I answered something very similar at enter link description here
The answer is that you must set the "src" value on the JS rendering.
This means that somewhere in your javascript you should have the following code
...
document.getElementById("showSkill").src="http://localhost/POSkill/skillshow.aspx?user_id =" + ReturnURL()
...
This should work just fine.

Categories

Resources