Javascript: load AddThis upon clicking - javascript

I have been puzzling with this for quite a while and can't get it to work. Here is the situation. I want a SOCIAL MEDIA bar to ONLY appear if people click some DIV. It should not be loaded unless people click the div. For Social Media I have ADD THIS, and the GOOGLE+1 icon. But I can not get them to load by such an external call. Here is the code so far:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=ISO-8859-1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#socialmedia").live('click',function(){
$("#loadhere").load('html-part.html');
$.getScript('js-part.js');
});
});
</script>
</head>
<body>
<div id="socialmedia">
Show the Social Media
</div>
<div id="loadhere">
</div>
</body>
</html>
In the HTML part I have the HTML info that needs to be loaded:
html-part.html:
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<!-- AddThis Button END -->
<g:plusone size="medium" id="gg"></g:plusone>
</div>
For the JS part I am struggling. Here is what needs to be loaded:
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ID"></script>
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
I have tried to call them one by one:
$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#pubid=ID');
$.getScript('https://apis.google.com/js/plusone.js');
But I guess this is a crossdomain problem...?
If I use PHP to obtain the content, and load a local PHP file, it still does not work. Before spending one more day on this... is this possible to achieve?

The problem here is that addthis code fires on dom ready event. When you load it with jQuery the dom has already been loaded so the code is not executed. The fix is to use addthis.init() method to force the code execution after you load the code. There is no cross domain problem or anything.
Note that according to addthis documentation it should be possible by just passing a get variable through the widget url like this http://s7.addthis.com/js/250/addthis_widget.js#pubid=[PROFILE ID]&domready=1 but it didn't work for me.
I would also recommend you store the html in a string variable, that way you don't have to do unnecesary requests for a little static html.
See working demo here: http://jsfiddle.net/z7zrK/3/
$("#socialmedia").click(function(){
var add_this_html =
'<div class="addthis_toolbox addthis_default_style ">'+
'<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>'+
'<a class="addthis_button_tweet"></a>'+
'<a class="addthis_counter addthis_pill_style">'+
'</a>'+
'</div>'+
'<g:plusone size="medium" id="gg"></g:plusone>';
$("#loadhere").html(add_this_html);
$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#pubid=xxx',
function(){
addthis.init(); //callback function for script loading
});
$.getScript('https://apis.google.com/js/plusone.js');
});

Just used amosrivera's answer (huge kiss to you btw :) and ran into another issue :
Addthis object can only be loaded once, so when you have multiple addthis toolboxes on the same page it may only work for the first clicked toolbox.
The workaround is to do :
if (window.addthis){ window.addthis = null; }
before calling
addthis.init();
Here's what I've just done to start loading the buttons only when an article is hovered long enough :
HTML:
<article data-url="someUrl" data-title="someTitle" data-description="someDesc">
.....
<div class="sharing">
<div class="spinner"></div>
<div class="content"></div>
</div>
</article>
JS :
// Only throw AJAX call if user hovered on article for more than 800ms
// Then show the spinner while loading buttons in a hidden div
// Then replace the spinner with the loaded buttons
$(function() {
var t;
$("article").hover(function() {
var that = this;
window.clearTimeout(t);
t = window.setTimeout(function () {
sharing_div = $('.sharing', that);
add_this_html =
'<div class="addthis_toolbox addthis_default_style "> \
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> \
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a> \
</div>';
if (sharing_div.find('.content div').length == 0) {
sharing_div.find('.spinner').show();
sharing_div.find('.content').html(add_this_html);
sharing_div.find('addthis_toolbox').attr({
'addthis:url': $(that).attr('data-url'),
'addthis:title': $(that).attr('data-title'),
'addthis:description': $(that).attr('data-description'),
})
if (window.addthis){ window.addthis = null; } // Forces addthis to reload
$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#pubid=xxx&async=1',
function(){
addthis.init();
setTimeout(function() {
sharing_div.find('.spinner').hide();
sharing_div.find('.content').show();
}, 2500);
});
}
}, 800);
});
});

To answer your official question, yes, I believe this is possible to achieve.
But, to further elaborate on this, I believe what you may want to try working with is the order in which your external scripts and external markup are loaded. An interesting situation we find when dealing with asynchronous actions such as these, is that they don't always complete, load, or execute in the order you would like unless you specifically say so. jQuery lets you do this through some callbacks you can pass to the getScript and load methods.
There also should not be a "cross-domain" problem with javascript files on other domains, though there certainly is when loading HTML.
I'm not sure if this will exactly solve the problem you're having, but it certainly feels like this is worth a try. You could try making sure the markup loads before the scripts do:
$(function(){
$("#socialmedia").live('click',function(){
$("#loadhere").load('html-part.html', function() {
// this waits until the "html-part.html" has finished loading...
$.getScript('js-part.js');
});
});
});
Now, we should also ask about how you are building your "js-part.js" file. (You only showed what you wanted, not what you've built.) If this is truly a JS file, you can't just use some HTML <script> tags to load other JS files. (You would instead want to continue calling getScript in this file, or use one of several other approaches to get your other JS stuff loaded, such as manually appending script elements to the document's head, or using another library, etc...)
Good luck!

Related

Loading Section not disappearing on first load

I made a loader that uses css and javascript to play an animation. On loading the site for the first time the animation sometimes doesn't play leaving a blank white screen. I believe it has something to do with caching on the second load that makes it work. Thanks in advance.
HTML:
<section id="loading">
<div class="circle spin"></div>
<img src="src/j2.svg" alt="J2 Logo">
</section>
<link rel="stylesheet" href="css/loading.css">
<script type="text/javascript" src="scripts/loading.js"></script>
loading.css:
https://pastebin.com/E16PMTtQ
loading.js:
https://pastebin.com/1X09KatC
The websites link is https://j2.business
With a quick look at your code it looks like all code is executed when the javascript-file gets loaded. This could be a timing-issue (your javascript-file is retrieved faster than your HTML-page: the elements it wants to act on are not available yet).
With jQuery you can quickly solve that by embedding your variables and functions in this holder:
$( document ).ready(function() {
// place code here, the document is waiting
});
Because you are not using jQuery you could use this:
add the "defer" attribute.
<script type="text/javascript" src="scripts/loading.js" defer></script>
This should be enough, specs found here:
https://www.w3schools.com/tags/att_script_defer.asp
Or if you want only some functions executed when the document is loaded you could use the function which all browsers support:
(function() {
// place code here, the document is waiting
})();

Includes taking a long time to load and you can see them loading

I’m including one HTML file in another, as a way to reuse my header and navigation generation logic.
The trouble is that when I browse to pages on my site, I can see the HTML that isn’t included in the include files load first. Only then you can see the menus and banners load afterwards. I’d like everything to appear to load at the same time.
Here's the rendered HTML.
And here’s a code snippet showing you how I generate these pages:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
<script>
$(function(){
$("#includeHeader").load("includes/templates/header.html");
$("#includeNavigation").load("includes/templates/navigation.html");
});
</script>
<div id="includeHeader"></div>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<div id="includeNavigation"></div>
I’m currently working with the code to try to move any external libraries / CSS to the bottom of the page vs. in the header. But so far, that hasn’t really changed or improved anything.
You should use one of the templating languages.
If your includes are simple HTML files then you could use Handlebars or Dust - you could just copy your code and that's it, then in Javascript you would need just render these templates - see the documentation.
You could use Jade/Pug instead, but its syntax is different from the HTML, so that's not just question of copy-paste.
You are using $(handler) to load them, which is a form for $.ready(). So it waits for the document to load everything before loading your header.html and navigation.html.
Try
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
</head>
<body>
<div id="includeHeader"></div>
<script>
$("#includeHeader").load("includes/templates/header.html");
$("#includeNavigation").load("includes/templates/navigation.html");
</script>
</body>
Your problem is that the load function does not run until the document.ready event has fired. Which is probably after your page has started rendering. To get everything to appear at the same time you could use the callback from .load to show everything. So everything is hidden,
$( "#result" ).load( "ajax/test.html", function() {
/// show your stuff
});
You will of course need to know both has loaded.
I would recommend not using javascript to render HTML from a static path and would use a server side lang instead for speed.
I think it make some level fast its not waiting for load all dom element, I am considering #includeNavigation element is under #includeHeader element
<head>
<script src="assets/js/jquery-2.1.3.min.js"></script>
</head>
<body>
<div id="includeHeader"></div>
<script>
$("#includeHeader").load("includes/templates/header.html", function(data){
console.log("header loaded");
$("#includeNavigation").load("includes/templates/navigation.html", function(data){
console.log("navigation loaded");
});
});
</script>
</body>

Loading content only

I am using a $_GET function to load content into the website,
what I want to do is add a Loading image into all that mess.
Right now it looks like it opens a whole new page.
Code:
<?php
if (isset($_GET['page']) || isset($_POST['page'])) {
$page = trim(isset($_POST['page']) ? $_POST['page'] : $_GET['page']);
if (preg_match("/a-z/", $page)) {
}
} else {
$page = "index";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="navigation">
<ul class="nav-items">
<li>Home</li>
<li>Test</li>
<li>Beta</li>
</ul>
</div>
<div id="content">
<?
if ($page != '')
include('pages/'.$page . '.php');
else
{
include('pages/error.php');
}
?>
</div>
</body>
</html>
Now, it works perfectly but I'd want it to show a Loading... image while loading the content , and instead of reloading whole page would be great to load the content div ONLY.
I did not try javascript solution since I didn't find anything that would work correctly and would keep the links working (for example http://example.com/index.php?page=test with already loaded the text.php file from pages folder). Plus I'm a real newbie in javascript so I have no idea what to start with.
The only solution to this problem is with JavaScript because PHP will only execute on the server and will only present HTML on the client side.
If you understand the HTTP request/response system, you will know that a request is sent to the server and then the server responds back with the page content, which will be the HTML (and CSS and any client-side scripts such as JavaScript). This method normally means having to reload the page but if you use AJAX (Asynchronous JavaScript and XML), this acts as a layer between the client and the server, allowing the user to request content without having to reload the page.
The most simple way of doing this is with jQuery. Be sure to include the jQuery library and put your code inside the $(document).ready(); function so that it executes when the page has finished loading.
Fortunately, this particular task is fairly simple, although it will require restructuring your website/application slightly. You will need to have the content echoed or printed onto a different page with PHP.
On your main page that will be used and seen by the users, you would simply write $("#container").load("page.html"); where container is the id of the container you want to load the content into.
If you want different content to be loaded with different buttons, you could do this (as long as you give your links the correct ids:
$(document).ready(function() {
$("#alpha").onclick(function() {
$("#container").load('page.html?page=alpha');
});
$("#beta").onclick(function() {
$("#container").load('page.html?page=beta');
});
});
Edit: I'm so sorry, I missed out the important part about the loading image, but the other answer demonstrates this well, so there is no point in repeating it.
It looks like it is opening a whole new page because it is. Your only option would be javascript. If I were wanting to do this, I would always only load the index page with nothing in your content div except the loading icon. Then once the page is loaded have jquery read the get variable and make an ajax request for the content of the page and load it into the div.
<div id="content">
<div id='page'></div>
</div>
Then, to make it easier on you since you are unfamiliar with javascript I would include the following jquery plugin: https://github.com/allmarkedup/purl
then in .js file:
$( document ).ready(function() {
var loading_annimation = "<div class='loading'></div>";
var page = $.url().param("page");
if(page){
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
} else {
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page=index');
}
$(document).on('click','.link', function(e){
e.preventDefault();
var page = $(this).attr("data-link");
$('#page').load(loading_annimation ).load('/special_php_file_that_includes_JUST_content.php?page='+page);
});
});
Then you will need to change your links to do something like this:
<a class='link' data-link='beta' href="/index.php?page=beta">Beta</a>

Best way to fire events when single elements in the document becomes ready

I'm developing a web application that because of performance concerns is heavily reliant on Ajax functionality. I'm attempting to make parts of each page available while longer running modules load.
The issue is that I want to kick off the Ajax requests as soon as possible (in the head of the document). This part works fine; the issue is on rare occasion, the Ajax call will come back before the area that I want to load the Ajax data into is present on the page. This causes the data to not be loaded.
To get around the issue I started using script tags below each of my containers that resolve a JQuery promise to let the code know that the area is available.
EDIT: I want to load the data into the area as soon as it becomes available (before full document load).
The current pseudo code looks like this:
<head>
<script>
var areaAvailablePromise = new $.Deferred();
$.when(areaAvailablePromise, myAjaxFunction()).then(function(){
// load data into the element.
});
</script>
</head>
<!-- much later in the document -->
<div class="divIWantToLoadAjaxContentInto"></div>
<script>
areaAvailablePromise.resolve();
</script>
My question is: is there ANY better way to handle this situation? Every one knows that inline scripts are blocking and are bad for performance. Also, I feel that this is going to lead to cluttered code with micro-script tags all over the place.
Put your (whole) <script> tag just after the element.
HTML is parsed from top to bottom, so the element will be loaded already.
No. There really is no better way to my knowledge.
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="q.min.js"></script>
<script>
var elD = Q.defer();
var dataP = Q($.ajax(…));
Q.spread([elD.promise, dataP], function (el, data) {
…
}).done();
</script>
</head>
<body>
…
<div id="foo"></div>
<script>elD.resolve($("#foo"));</script>
…
</body>
</html>
you can use:
$(document).ready( handler )
(recommended)and also has contracted form:
$(handler)
exemple:
$(function(){
alert("OK");
})
read more: http://api.jquery.com/ready/

Run javascript after page load

setup_account ui-mobile-viewport ui-overlay-c
When a page i make loads like this:
var location = location.href+"&rndm="+2*Math.random()+" #updatecomment0>*"
$("#updatecomment0").load(location, function(){});
I have multiple scripts running on the updatecomment0 div:
<div id="updatecomment0">
<div id="javascript1">hi</div>
<div style="float:right;" class="javascript2">delete</div>
</div>
I don't know how to make this other JavaScripts run after page load.
Can someone please tell me how to with this.
Thank you
Use $(document).ready().
Use jQuery, you can do this very easily.
jQuery(document).ready(function(){
alert('Your DOM is ready.Now below this u can run all ur javascript');
});
Here is a sample layout for you
<script type="text/javascript">
$(document).ready(function(){
/// here you can put all the code that you want to run after page load
function Javascript1(){
//code here
}
function Javascript2(){
// code here
}
$("#btnOK").live('click',function(){
// some codes here
Javascript1();
Javascript2();
});
});
</script>
<div id="MyDiv">
<input type="button" id="btnOK" value="OK"/>
</div>
write code inside ready
jQuery(document).ready(function(){
// write here
});
suggestion : use live or bind
Unless you need javascript to do something before the page is loaded, add your scripts to the bottom om the html document, just before the body end tag.
The page will load faster, and you can do whatever you need to, right in the js file, without the document ready functions.
If the scripts is the last to load, the DOM is already guaranteed to be "ready".
$(window).load(function() {
// code here
});
$(document).ready() is all you needed.
You can make JavaScript wait for a specified time using the setTimeout method:
.setTimeout("name_of_function()",time_in_millis);
I hope this can help you too, I had a similar issue and I fixed it by calling the following just after loading the content in the page (like after an AJAX request for a page to be shown inside a div):
(function($) {
$(document).ready(function() {
// your pretty function call, or generic code
});
}(jQuery));
Remember to not call this in the document you load, but in the function that load it, after it as been loaded.
Using vanilla Javascript, this can done thusly:
<html>
<head>
<script type="text/javascript">
// other javascript here
function onAfterLoad() { /*...*/ }
// other javascript here
</script>
</head>
<body>
<!-- HTML content here -->
<!-- onAfterLoad event handling -->
<div style="display:none;"><iframe onload="onAfterLoad();"></iframe></div>
</body>
</html>

Categories