Bobe
Bobe

Reputation: 2040

ShareThis - Buttons loaded after AJAX content not working

The site is built with ExpressionEngine (2.8.1), but because the content to be shared is loaded via AJAX I decided to use the generated code for "Website" on the ShareThis website rather than the probably outdated EE add-on.

So ShareThis generated the following markup, which I have placed in the EE template that is loaded via AJAX:

<span class="st_facebook_large" displayText="Facebook"></span>
<span class="st_twitter_large" displayText="Tweet"></span>
<span class="st_pinterest_large" displayText="Pinterest"></span>
<span class="st_googleplus_large" displayText="Google +"></span>
<span class="st_email_large" displayText="Email"></span>

In the header I am loading the scripts as provided:

<script type="text/javascript">var switchTo5x=true;</script>
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">stLight.options({publisher: "MY_PUBLISHER_ID", doNotHash: false, doNotCopy: false, hashAddressBar: false});</script>

Then in the JS I have the following script bound to the click event that loads the content:

$('#ajax-content').load('ajax/'+id, function() {
    if(window.stButtons) {
        stButtons.locateElements();
    }
}

However, while the buttons are generated properly, they don't seem to have any event handlers bound to them; clicking them does nothing. I've tried without checking if(window.stButtons), but it makes no difference.

If instead of stButtons.locateElements(); I use the following code, the buttons do not even show up:

$.getScript('http://w.sharethis.com/button/buttons.js', function(data, textStatus, jqxhr) {
    var switchTo5x = true;
    stLight.options({publisher: "MY_PUBLISHER_ID", doNotHash: false, doNotCopy: false, hashAddressBar: false});
});

Any ideas what's going wrong and what I can do to get it working?

Upvotes: 0

Views: 1675

Answers (1)

Marcus Lind
Marcus Lind

Reputation: 11450

Click Events only work on content loaded by the DOM. If you add content after the DOM has been loaded, then these elements will not have the Click-event on them.

To solve this you need to use jQuery Delegate Function. Which also works on "Future Elements", meaning elements that have been loaded afterwards by using for example Ajax.

Upvotes: 1

Related Questions