Inline tumblr 'post' script preventing external jQuery from triggering - javascript

I've implemented a tumblr post button following their docs, and the popup works great. However, I need to pass in an image URL that is dynamically created on the page, rather than hardcoding in an image url. I'm trying to do this with jQuery.
HOWEVER, the inline script required to launch the 'post' popup fires, and prevents my jQuery (being triggered by clicking the 'post' button) from firing. I tried moving the inline tumblr script to my js, which allowed my jQuery to fire, but not the tumblr popup.
Ideally, the inline script would fire AFTER my jQuery, since the jQuery is the bit that generates the image URL I need to pass in.
Is there a way to do this, maybe with onLoad or something?
My button, as generated by Tumblr is this (sorry I can't get it on multiple lines for some reason):
<a class='tumblr-share-button' data-color='blue' data-notes='right' data-posttype='photo' data-content='image URL will go here' href='https://embed.tumblr.com/share'></a> <script>!function(d,s,id){var js,ajs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src='https://assets.tumblr.com/share-button.js';ajs.parentNode.insertBefore(js,ajs);}}(document, 'script', 'tumblr-js');</script>
And my jQuery (that is not executing) is:
$('.tumblr-share-button').click(function(e){
var svg = $("#svg")[0];
svg.toDataURL("image/png", {
callback: function(img) {
var img = img.replace("data:image/png;base64,", "");
var imgurTitle = $("meta[property='og:title']").attr("content");
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {'Authorization': 'Client-ID ******'},
type: 'POST',
data: {'image': img, 'type': 'base64', 'title': imgurTitle},
success: function(result) {
imageURL = result.data.link;
$('.tumblr-share-button').data('data-content',imageURL);
},
error: function(){
console.log('error');
}
});
}
});
});
Any help would be tremendously appreciated!!!

Related

Why the Ajax content of this jQuery plugin (Tooltipster) is shown only after mouse hover 2 times?

I can't find a solution for this plugin since I cannot find any working demo or documentation for external content via Ajax.
Basically I have a simple div with a mouse hover JS function:
<div onmouseover="myFunct(this,'.$comment['id'].');" >Hover Me</div>
And this is my JS function:
function myFunct(element, id){
$(element).tooltipster({
contentCloning: true,
interactive:true,
maxWidth:250,
contentAsHTML:true,
content: 'Loading...',
// 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
functionBefore: function(instance, helper) {
var $origin = $(helper.origin);
// we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
if ($origin.data('loaded') !== true) {
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+id+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
// to remember that the data has been loaded
$origin.html('loaded', true);
}
});
}
}
});
}
Why the tooltip is shown only at the 2nd mouse hover?
Here is a similar Eg. JSFiddle
UPDATE
Thanks to the support this has solved my issue:
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
Anyway this doesn't work on Ajax dynamic content, and I don't know why (I tried to insert it on Ajax page, no way)
I'd recommend a few things: first, separate your JS from your HTML (this is considered best practice), second, initialize Tooltipster on page load, and last, remove the wrapper function. Once the tooltip is initialized your code will trigger by default on hover.
Separate JS from HTML
<div class="hover-me tool-tip" data-commentId="12345">Hover Me</div>
Initalize Tooltipster on Document Ready
$(document).ready(function() {
$('.tooltip').tooltipster();
});
Trigger Tooltipster with Hover
$('.hover-me').tooltipster({
// all of your code from above
functionBefore: function(){
var commentId = $(this).attr('data-commentId');
}
});
Note:
The default trigger for Tooltipster is hover (as seen in the documentation), however, you could explicitly set it by passing in trigger: hover, which would make your code slightly more readable and as such maintainable.
Tooltipster Support Recommendation (as seen in the comments)
I add this because it reinforces my solution above and adds context for future devs...that, and it might be overlooked in the comments section.
You initialize your tooltip when the mouseover event has already been fired, so Tooltipster cannot "hear" this first event and open the tooltip. You'd better initialize your tooltips at page load and put your comment id in a data-id attribute that you'll retrieve in functionBefore when you prepare your ajax call.

Using Twitter Bootstrap's Scrollspy to lazy load (load on scroll) async JavaScript?

First, this is how I'd normally load the comments.
The HTML markup:
<div id="comments">
<div id="disqus_thread">
<!-- Comments are dynamically loaded (via JS) here. -->
</div>
</div>
And the JavaScript code (custom.js):
$j=jQuery.noConflict();
$j(document).ready(function() {
$j('#displayComments');
var disqus_shortname = 'paulund';
$j.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
});
Now, coming to the point...
I'd like to load the comments, only when the user scrolls down to the comments section, i.e. div#comments.
Although not meant for this purpose, I've been told that Twitter Bootstrap's Scrollspy plugin could be used for doing this.
But I am not sure how.
(I've read the docs and tried various markups, but couldn't get it to work; and decided to start over from scratch.)
Here's a skeleton of the comments to test on: http://jsfiddle.net/MvTgk/ (and its respective demo)
PS: In case you don't have the time to write a full-fledged answer, please drop any hints/suggestions in the comments. I'll be happy to try them myself.
Well, considering that Twitter Bootstrap's Scrollspy isn't made for the purpose I am after, I've chosen to go with jQuery Waypoints. Lazy loading comments only when the section comes into view is very simple now.
Here's how I had to modify the JavaScript code:
$j = jQuery.noConflict();
$j(document).ready(function () {
$j('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$j.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}, { offset: '100%', triggerOnce: true });
});
NOTES:
The offset: '100%' is used to make sure that Javascript comments are displayed as soon as div#comments comes into view (from the bottom, as we scroll down) and not only when it gets to the top of the view-port, which is the default.
triggerOnce: true makes sure that the action is triggered only once, i.e. waypoint will destroy itself after its first trigger (i.e. won't be triggered every time the user scrolls up/down the page). This is the same as calling .waypoint('destroy') at the end of the callback function.
The ScrollSpy plugin is probably not what you should use.
According to the Bootstrap documentation "the ScrollSpy plugin is for automatically updating nav targets based on scroll position". Therefore, it should only be used for that.
Since you are using jQuery, you could use Sizzle to check when the comments box is visible.
$(window).on("scroll", function check() {
if( $('#displayComments').is(':visible') ) {
// Remove event listener as it is not needed anymore
$(window).off("scroll", check);
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}
});

Post preview - Passing data with AJAX and Fancybox

I'm trying to do a post preview, which will appears in a new Fancybox iframe. Since couple of weeks I'm looking for some help or best practices, but I can't find it.
My main problem is to pass the data from form (before updating database) to Fancybox window. My AJAX skills are very poor, so maybe my problem isn't so hard.
Please check the code:
$('.preview2').fancybox({
fitToView : false,
width : 905,
height : 505,
autoSize : false,
closeClick : false,
openEffect : 'none',
closeEffect : 'none',
ajax: {
type: "POST",
cache : false,
url: "preview.php",
data: $('#postp').serialize()
}
});
And a calling link:
<a class="preview2" data-fancybox-type="iframe" href="preview.php" id="preview2">Preview</a>
I'm almost sure everything is fine with preview.php file, just posting the variables and printing it in right places.
Can someone check Fancybox / AJAX part?
As I mentioned in my comments, your preview button should submit the form via ajax to get the POST preview values (we'll use ajax instead of iframe) so :
<a class="preview2" data-fancybox-type="ajax" href="preview.php" id="preview2">Preview</a>
Then you would need to bind the preview button to a manual on("click") method to submit the form via ajax firstly ....and then post the results in fancybox secondly like :
$(document).ready(function () {
$('.preview2').on("click", function (e) {
e.preventDefault(); // avoids calling preview.php
$.ajax({
type: "POST",
cache: false,
url: this.href, // preview.php
data: $("#postp").serializeArray(), // all form fields
success: function (data) {
// on success, post (preview) returned data in fancybox
$.fancybox(data, {
// fancybox API options
fitToView: false,
width: 905,
height: 505,
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none'
}); // fancybox
} // success
}); // ajax
}); // on
}); // ready
See DEMO (feel free to explore the source code)
I don't like the solution, so I will post my own investigation.
Why writing code with 1. .on("click", ... 2. e.preventDefault 3. $.ajax 4. this.href just to call fancybox on success, that already has all this functions inside?
If you decide to use ajax instead of iframe (like in accepted answer) you could simply add type property to fancybox() call, cause it's beening checked, and pass all other
$('.preview2').fancybox({
type: "ajax",
ajax: {
data: $('#postp').serialize()
// url: "someurl.php" not needed here, it's taken from href
// if you need it, e.g. you have a button, not a link
// use "href" property that overrides everything
// not attribute, cause it's invalid
}
// href: "url_to_add_or_override_existing_one",
// all other effects
// afterLoad: function () { // other cool stuff }
});
EDIT As #JFK pointed it's not enough, you have to get form data each time you click the link, so beforeLoad() needed instead of data. Finnaly:
$('.preview2').fancybox({
type: "ajax",
beforeLoad: function() {
this.ajax.data = $('#postp').serialize();
}
});
You can remove all data-* atrributes too
FIDDLE
KISS
I have tried a more interesting way with fancybox that works,
in the fancybox page
var myvar;
$(document).ready(function(){
myvar = parent.$("#formvariwant").val();
});

Adding HTML to a page element with ajax onclick

To have an indicator while doing an ajax request, I got information saying that I should have the indicator with the animated gif placed in the page element, then on success of the ajax function replace the data.
If I add the indicator source with src="ajax-loader.html", the ajax call leaves it in place and doesn't replace it with the data. If I add the indicator source with .load("ajax-loader.html"), before the ajax call it isn't shown at all. If I add it in the ajax call in the beforesend event, it isn't shown either. If I make two ajax calls, one to load the indicator, one to load the data the same happens. There must be a way to show the indicator in this simple code.
This is the HTML for the page element.
<iframe id="lcupco" style="position: relative; top: 5px; width: 100%; height: 200px; border: 2px solid grey; margin-bottom: 15px;"></iframe>
This is the HTML for the indicator.
<html>
<head></head>
<body>
<img src='images/ajax-loader.gif'/>
</body>
</html>
This is the code
Calling .load
$(document).ready(function(){
$('#lcupco').load("ajax-loader.html");});
$.ajax({
url: 'luxcal/index.php?cP=40',
cache: false,
async: true,
success: function(data) {
$('#lcupco').html(data);
},
});
Using beforesend
`
$.ajax({
url: 'luxcal/index.php?cP=40',
cache: false,
async: true,
beforeSend: function() {
$('#lcupco').load('ajax-loader.html');
// $('#lcupco').html('<html>Initializing calendar...</html>'); //simple text didn't load either.
},
success: function(data) {
$('#lcupco').html(data);
},
});
Using two ajax calls: one for indicator and one for data
`
$.ajax({
url: 'ajax-loader.html',
cache: false,
async: true,
success: function(data) {
$('#lcupco').html(data);
},
});
$.ajax({
url: 'luxcal/index.php?cP=40',
cache: false,
async: true,
beforeSend: function() {
$('#lcupco').html('<html>Initializing calendar...</html>');
},
success: function(data) {
$('#lcupco').html(data);
},
});
`
You can add the pre-loader gif to the index page. No need of loading it separately. Then on the load of iframe you can hide or remove it. You can see a demo here : http://jsfiddle.net/diode/dAdtU/ . Here iframe source is set when load button is clicked. This can be done on page ready, or even you can set the source directly. When the load even gets triggered preloader is removed.
Using ajax you can load html content for replacing/modifying the inner html of a particular element in the page ( div, p, ul etc..). But using it to load the entire page is not recommended.
Try that:
$.ajax({
url: 'luxcal/index.php?cP=40',
cache: false,
async: true,
beforeSend: function() {
$('#lcupco').append($('<img class="indic" src="images/ajax-loader.gif"/>'));
},
success: function(data) {
$('#lcupco', '.indic').remove();
$('#lcupco').html(data);
},
});
Also dont forget that the src attribute takes double quotes (") instead of single (')
A possible explanation for all the effects could simply be that you can't set the inner HTML or load the content of an iframe, because the browser determines the content of an iframe based on its src attribute.
Usually you wouldn't use iframe for an asynchronous call anyway, a simple div should work. With a div, setting the html before (be it with a html() or load() functions) and replacing it in complete handler will work out fine.

fancybox ajax post to iframe

is it possible using fancybox to post a var to the iframe when opens?
I currently have:
function fancyBoxLoad(element) {
var elementToEdit = $("#" + $(element).attr("class"));
var content = encodeURIComponent($(elementToEdit).outerHTML());
$.fancybox(
{ 'href': 'loadEditor.php' },
{
frameWidth: 750,
frameHeight: 430,
overlayShow: true,
ajax: {
type: "POST",
data: 'content=' + content
},
type: 'iframe'
}
);
}
It does seem that if I take away type: 'iframe' it will post data but it doesn't appear to be in the iframe and if I take away ajax: { type: "POST", data: 'content=' + content } instead it will open in an iframe but not post the data (the example above does the same)
So my question being can it be done?
If you're simply trying to put content in a iframe, why don't you use fancybox to create the iframe, and once you know it's been created, then access it via the reference that fancybox returns to you and set your content that way. I'm not sure you want to send the content to the server and back. Just wait for the iframe to load, then on ready, query an element within it and set the content.
Looking at the source for Fancybox v1.3.1 they are in fact mutually exclusive. If you don't feel comfortable diving into the source code and editing the plugin, you might try using GET variables in your HREF as a work around. It should effectively work like a post as it is an AJAX call, just make sure the backend can receive the GET variables.

Categories

Resources