Adding Facebook Pixel event to Squarespace button click - javascript

I'm trying to add a Facebook pixel event -- "ViewContent" -- to my Squarespace site. I have one page with one button, and I want to fire the event on the button click. It feels like it should be simple, but I'm consistently getting an error in Facebook Pixel Helper with my current setup.
I'm referencing this post: Add FB pixel event code into button - Squarespace
And as recommended in the answer, I'm using a per-page code injection in the header on this page: https://www.wearpapercrane.com/survey
This is what I have --
<script>
(function() {
var btns = document.getElementsByClassName("sqs-block-button-element");
var i, I;
for (i=0, I=btns.length; i<I; i++) {
btns[i].addEventListener("click", function() {
fbq("track", "ViewContent");
});
}
})();
</script>
But here's what I get on the other end when I use Facebook Pixel Helper to validate --
(This is after the click, by the way ... the button opens the link in a separate tab, so this is going back to the page after the click and looking at Pixel Helper).
Is there something I'm missing that is resulting in this error?
I have the pixel installed and I have a "lead" event working properly on another page (using Squarespace's Form Embed feature), so I'm pretty sure it's a problem with this specific code injection.
Would love any and all recommendations. Thank you!!

The event is not firing because the answer you referenced (which I wrote) did not account for the fact that, when injecting the code via header injection (site-level or page-level), one must wait for the DOM to be loaded before attaching events to the elements.
The answer you have referenced has been updated, notably the following section:
<script>
window.Squarespace.onInitialize(Y, function() {
var btns = document.getElementsByClassName("sqs-block-button-element");
var i;
for (i=btns.length-1; i>=0; i--) {
btns[i].addEventListener("click", function() {
fbq("track", "AddToCart");
});
}
});
</script>

Related

Delete a single URL from a chrome-extension popup-window seems not working with adding event listeners (the event listener might be scoped?)

Background information
I am trying to make a functional chrome-extension popup-window that enables the user to add links (based on the open tab's URL) when he desires it, and deletes one link or delete all of the links in just one click. Down below are all of my files! I must say in advance that I am not very good (and not experienced) with using jQuery's library but if that's the only solution that I have, than I will use it in my code.
The problem
The buttons to delete all the links and the button to add one link does work perfectly without bugs. However, the button to which one link should be deleted doesn't work, I tried various ways including splicing. I am trying to remove the link from the DOM and from the chrome.storage.local, both actions do not work. In the following code you can see all of the files I have thus far. The code of when the 'X' button is pressed doesn't get executed (see these pictures): https://i.stack.imgur.com/gg1Dy.png and https://i.stack.imgur.com/4oGdI.png
The code
manifest.json:
gist.github.com/kobrajunior/78acda830c2d1c384333542422f1494d
popup.js:
functions to look at: addToDom and removeMe and the very first event listener when the DOM is fully loaded
gist.github.com/kobrajunior/4852f85ae18cfb9edbe542a820b8c107
For extra information (if needed), the popup.html:
gist.github.com/kobrajunior/1c26691734c19391c62dc336ed2e1791
Thank you in advance.
For the following lines in popup.js, you want to restore (show all the items/buttons) and bind listeners, however don't forget addToDom is called inside the callback of chrome.storage.local.get, that means by the time you assign value to allButtons, they're not added to DOM, that causes allButtons.length === 0 and you didn't bind anything in fact.
Try to move the binding logic inside the callback of restore (You may encounter other issues however that's not covered in this quesions).
document.addEventListener('DOMContentLoaded', function () {
restore();
var allButtons = document.getElementsByClassName('buttons');
function listenI(i) {
allButtons[i].addEventListener('click', () => removeMe(i));
}
for (var i = 0; i < allButtons.length; i++) {
listenI(i);
}
});
function restore() {
// get the tab link and title
chrome.storage.local.get({ urlList: [], titleList: [] }, function (data) {
urlList = data.urlList;
titleList = data.titleList;
// add the titles and url's to the DOM
for (var i = 0, n = urlList.length; i < n; i++) {
addToDom(urlList[i], titleList[i]);
}
});
}

How to use phantomjs to take screen shot with dynamic data visualization

When I follow this tutorial (http://phantomjs.org/screen-capture.html) to do a screen capturing, I got some problem about dynamic data visualization.
In that tutorial, it uses some code like:
var page = require('webpage').create();
page.open('http://localhost:8080/index.html', function() {
page.render('screenshot.png');
phantom.exit();
});
But this seems work only with static page. I wonder if I have some some user interaction and make that page changed(like mouse click change color etc.), how can I make that capturing which show current screen?
If phantomjs can not work in this way, could anyone suggest some other solutions?
Sure, just add the functionality you want after page.open() and before page.render().
page.open('http://localhost:8080/index.html', function() {
/**
* Add your events and actions here...
* or call JS functions of the page itself...
*/
page.evaluate(function() {
/**
* Inject a <style text/css> tag in the head,
* which set the bgcolor
*/
var style = document.createElement('style'),
text = document.createTextNode('body { background: red }');
style.setAttribute('type', 'text/css');
style.appendChild(text);
document.head.insertBefore(style, document.head.firstChild);
});
page.render('screenshot.png');
phantom.exit();
});
Keep in mind that you are working with Javascript here and that you can inject arbitrary helper scripts, like CasperJS or jQuery, and use their functionality on the loaded page.
For inspiration:
PhantomJS; click an element
How to retrieve the ajax data whose loading requires a mouse click with PhantomJS or other tools
see especially this answer for clicking, screenshot-after-click and ajax stuff: https://stackoverflow.com/a/18274644/1163786
Browse a bit, then screenshot: https://stackoverflow.com/a/17506213/1163786

Infinite Scroll + Swipe.js

Background:
I'm making a portfolio site utilising both Swipe.js and Infinite Ajax Scroll (JQ).
Problem:
When the content from extra pages is loaded into the current page, it is not processed by the already-loaded Swipe.js script. This means that the new content doesn't have it's mark-up changed (needed for the swipe functionality to work).
I think I need to get the Swipe.js script to fire after each page re-load. Would that fix it? Please explain this to me like I'm an 8yr old. JS is not a strong suit...
Demo:
http://hatchcreative.co.nz/tomo
You can see that as the page loads new content, the buttons on either side of the sliders no longer work.
Yes you're right, after the images are loaded you have to create a new Swipe instance on these new elements (as they weren't there at the beginning, when the page was loaded).
Based on the docs of infinite scroll you can use onRenderComplete.
So you had your jQuery.ias constructor like this:
jQuery.ias({
// ... your settings...
onRenderComplete: function(items) {
$(items).each(function(index, element) {
new Swipe(element);
});
}
});
This should work this way somehow, but I am not exactly sure; I haven't worked with these libraries yet.
Edit:
After some more inspection of your code, I saw you had some inline click handler like: onclick='two.prev();return false;'.
You need to remove this and add your onclick handle in the same onRenderComplete function.
onRenderComplete: function(items) {
var swipe;
$(items).each(function(index, element) {
swipe = new Swipe(element);
});
// find tags with the class 'forward' inside the current element and add the handler
$(element).find('.forward').on('click', function() {
swipe.next();
});
// ... also for previous
}
By the way: Usually you should provide a jsFiddle with your important code parts, so it's easier for us to get the problem, and the question is not getting obsolote when the linked page changes.

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

Javascript uniform postback

Good afternoon all
Here is my scenario:
I have user controls within a master page and within a user control, I may have an update panel. I have the following bit of code I place within a usercontrol that maintains various control styling during partial postback i.e. those controls affected within by an asp update panel.
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
$("select, span, input").uniform();
Indeed, when an update panel does its thing, the Fancy Dan styling is maintained.
However, I have one gripe - when a 'large' partial postback occurs, occassionally you'll see the default, generic control styling reappear breifly and then the uniform kicks in to reapply the new fancy styles.
Is there any way I can avoid seeing the nasty old, default, bland stylings?
Any suggestions greatly appreciated.
Check out working with PageManagerRequests: MSDN Working With PageRequestManager
Sys.WebForms.PageLoadingEventArgs Class
Sys.WebForms.PageRequestManager pageLoading Event
$(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(beautify);
});
function beautify(sender, eventArgs) {
// If we have event args
if (eventArgs != null) {
// for each panel that is being updated, update the html by adding color red
// to select, span, input elements
// must remember to call .html() to put html back into the panelsUpdating[i], otherwise it puts in the jQuery Object
for (var i = 0; i < eventArgs.get_panelsUpdating().length; i++) {
//My test code
//var content = eventArgs._panelsUpdating[i].outerHTML;
//var jContent = $(content);
//$("input", jContent).css("color", "red");
//jContent = $('<div>').append(jContent)
//var jContentToContent = jContent.html();
//alert(jContentToContent);
//eventArgs._panelsUpdating[i].outerHTML = jContentToContent;
//Cleaned up
var jContent = $(eventArgs._panelsUpdating[i].outerHTML);
$("select, span, input", jContent).uniform();
jContent = $('<div>').append(jContent);
eventArgs._panelsUpdating[i].outerHTML = jContent.html();
}
}
}
Edit: I think you understood that the issue was the elements were being placed into the DOM (and therefore painted) before your javascript had a chance to make them uniform(). This intercepts the UpdatePanel and uniform()'s the code prior to it inserted into the DOM
Edit 2 Alright, I've updated it a bunch, I tested this with my test code there and then included the code you're likely to add. Also, I took a short cut in eventArgs._panelsUpdating - i should really be using the get and set functions, but this works.

Categories

Resources