I'm trying to achieve a countdown timer, where the value it counts down from is populated from a Advanced Custom Field date time picker. Ideally I'd like to use http://countdownjs.org/ , or similar to power the timer.
I can simply output the time date value on the page template by calling the ACF field like so.
<p>Event starts: <?php the_field('featured_event_date','options'); ?></p>
However, in order to use a JS/jQuery countdown I need to be able to use to value from ACF inside JS, not PHP? Does this sound correct as a methodology so far? Something like the example below.
var countdown = new Countdown({
selector: '#timer',
msgBefore: 'Will start at Christmas!',
msgAfter: 'Happy new year folks!',
msgPattern:
'{days} days, {hours} hours and {minutes} minutes before new year!',
dateStart: new Date('2013/12/25 12:00'),
dateEnd: new Date('Jan 1, 2014 12:00'),
onStart: function() {
console.log('Merry Christmas!')
},
onEnd: function() {
console.log('Happy New Year!')
}
})
It's pushing my knowledge out of the comfort zone, so advice, experience or examples or this would be much appreciated and help me on my way. Thanks in advance!
I've created a google content experiment without redirects using the docs.
The basic implementation involves a javascript snippet that uses the following code to choose the version of the experiment:
<!-- Load the Content Experiment JavaScript API client for the experiment -->
<script src="//www.google-analytics.com/cx/api.js?experiment=YOUR_EXPERIMENT_ID"></script>
<script>
// Ask Google Analytics which variation to show the user.
var chosenVariation = cxApi.chooseVariation();
</script>
<!-- Load the JQuery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
// Define JavaScript for each page variation of this experiment.
var pageVariations = [
function() {}, // Original: Do nothing. This will render the default HTML.
function() { // Variation 1: Banner Image
document.getElementById('banner').src = 'bay-bridge.jpg';
},
function() { // Variation 2: Sub-heading Text
document.getElementById('heading').innerHTML = 'Look, a Bridge!';
},
function() { // Variation 3: Button Text
document.getElementById('button').innerHTML = 'Learn more';
},
function() { // Variation 4: Button Color
document.getElementById('button').className = 'button button-blue';
}
];
// Wait for the DOM to load, then execute the view for the chosen variation.
$(document).ready(
// Execute the chosen view
pageVariations[chosenVariation]
);
</script>
However, when I visit the page using an incognito window, I only see the first variation of the experiment. When I check chosenVariation in the console, it's always 0. In fact, when I call cxApi.chooseVariation(); in the console, it always returns 0.
Is this because google recognizes my incognito browser windows, or is something broken with cxApi.chooseVariation(); or in my implementation?
I had the same problem, 100% of the sessions were given the original (0) variation. In order to fix the problem, I added the javascript code provided by the experiment. Go to your experiment (edit), click Setting up your experiment code, manually insert the code, copy the code in there.
Now since you (and I) don't want to have a redirect, remove this part at the end of the code <script>utmx('url','A/B');</script>. If your page is templated, you can use a variable and insert your experiment key (not experiment id) where you see var k='########-#'
Now either very few people use the experiments in a client-only fashion or we're totally stupid because it would seem to me that the guide is wrong and there's absolutely no documentation that shows a working client-only setup.
I'm using Google Analytics to track my pages, and I've added, last week, this code which I've found to try to track my PDF downloads, but this doesn't work :
Link to PDF :
<a href="pdf/my-pdf.pdf"
onClick="javascript:pageTracker._trackEvent('PDF','Download','My New PDF');
void(0);">
PDF
</a>
GA Tracking Code (minified) :
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
Of course, I changed my UA Values for the same of this post.
How can I edit this to allow for file download tracking ?
Edit
PDF
function trackLink(e)
{
e.preventDefault();
_gaq.push(['_trackEvent','Download','PDF', e.target.href]);
window.setTimeout('location.href="'+e.target.href+'"',100);
return false;
}
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
Note: XX's have been added for the purpose of the post and are not in the actual code.
Okay so a couple things here. Firstly, as gerl pointed out, you are using the wrong GA syntax for the version of the core code you have. So you need to fix your code according to that answer, regardless. But there is another issue to consider: timing.
First, more often than not, the GA code isn't going to have enough time to execute, before the browser redirects to the target URL. There are 2 ways you can get around this: force a timeout of ~100ms before redirect, or make your pdf open up in a separate tab/window.
Personally, I think the latter is a better solution. Since the pdf is loaded into a separate window, you don't need to worry about delaying the redirect to give GA a chance to execute. Also, most people prefer things like pdfs to open up in a separate tab/window, so that they aren't taken away from the page they are on. To do this, add a `target='_blank' to the link:
PDF
But if you really want to stick with having the pdf open in the same window/tab, then you will need to force a timeout. I don't like this option as much as the first, because what ~100ms is usually enough time to wait, it's not a guarantee that it's enough time. You can increase the timeout, but the more you do, the longer the visitor has to wait before the redirect occurs, which makes for a bad user experience. But this is one way you could do it:
PDF
<script type="text/javascript">
function trackLink(e) {
e.preventDefault();
_gaq.push(['_trackEvent','Download','PDF', e.target.href]);
window.setTimeout('location.href="'+e.target.href+'"',100);
return false;
}
var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
Also note that if you upgrade to universal analytics, that version has timeout/callback funcationality built in to link tracking (that article talks about outbound link tracking but the principle of using the callback function to do the redirect is the same).
You have pageTracker instead of _gaq.. Try this instead:
onclick="_gaq.push(['_trackEvent','Download','PDF', 'pdf/my-pdf.pdf']);"
Instead of writing a function, you can just add something into the html of the element... perhaps something like this?
<a href="pdf/my-pdf.pdf" onClick="_gaq.push(['_trackEvent', 'PDF','Download','My New PDF']);">
That ought to do it.
I had a similar problem with this sort of thing when trying to decide which type of GA code to use.
This question I posted might help (using ga vs. _gaq.push):
ga or _gaq.push for Google Analytics event tracking?
pdf
That should do the job! More info here: https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
Also, you can always test if your event tracking is working by looking in Real Time Analytics.
See this link: https://support.google.com/analytics/answer/1136920?hl=en
It shows how to use the hitCallback to help with the issue of the browser redirecting before the event gets pushed.
I think this would be how to modify your code:
PDF
<script type="text/javascript">
function trackLink(e) {
e.preventDefault();
ga('send', 'event', 'Download', 'click', 'PDF', {'hitCallback':
function () {
document.location = e.target.href;
}
});
return false;
}
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');
</script>
I am developing a Server Custom Control (.NET), a "DatePicker" with the jQueryUI Plugin.
So, i have the next script, that is loaded as a webResource:
JavaScript
$(function () {
$("#" + ctrlInput).datepicker({
maxDate: MaxDate,
minDate: MinDate
});
});
As you can see, i have javascript variables, so, for loading the script and the variables, i do the next:
C#
string javascriptVariables = String.Format(
"var MinDate = '{0}'; var MaxDate = '{1}'; var ctrlInput = '{2}';",
MinDate ?? DateTime.MinValue.ToShortDateString(),
MaxDate ?? DateTime.MaxValue.ToShortDateString(),
_textBox.ClientID
);
// Load javascript variables (it will be load every time i add a control)
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dateValues" + _textBox.ClientID, javascriptVariables, true);
// Load jQueryPlugin (it is loaded only once, and this is the problem)
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "[[resourceName]]");
It works fine. The problem is when i add this control to a page more than once.
And it is because the script variables are loaded fine, but the RegisterClientScriptResource doesn't load the jQuery Plugin again! And i don't know how i can force the load! Because i can't set the resource key to the RegisterClientScriptResource
Does anybody know how to solve this?
Thanks
I don't think you're taking the problem the right way.
Using global variables (in js) especially when they're actually only used locally is a very bad idea. source
Loading jQuery or a jQuery plugin more than once can also be a source of bugs. source
What i would do is to think of another way of passing variables to your javascript, something like data attributes.
You're probably having an html input generated with from server control, add data attributes for your dates :
<input type="text" ... data-mindate="01/01/2013" data-maxdate="12/31/2013" />
Next step is, instead of feeding the global variables to the datepicker function, use the data attributes :
$('#whatever').data('mindate');
or
$('#whatever').attr('data-mindate');
And a fast demo : http://jsfiddle.net/JjemN/
I need to remove the following script from my page(ASP.NET 3.5), leaving all other scripts intact:
<script type="text/javascript">
//<![CDATA[
alert('Save Sucessful.');
</script>
Should be something like $('html').children('script').remove(':contains("alert")) but this exact syntax doesn't work.
Rather than a pop-up alert, why not provide feedback with a page element (in the DOM)?
It would be there still rather than be there again.
Okay, if you cannot change it you could replace the windows.alert function, if it's executed before the code in question (usually in DOM order).
BTW, you can't just test the string (my first thought) since "Successful" should have two 'c's and the owner of that code might fix it.
But you could mute all alerts for the first 10 seconds with:
var _alert = window.alert, _alertStart=new Date().getTime();
window.alert = function() {
var delay = (new Date().getTime()) - _alertStart;
if (delay > 10000)
_alert.apply( window, arguments );
};
Or, if you want to delete every inline script that contains "alert" you could use:
$('script:contains("alert")').remove();
Note that that pattern matches the script tag in which it occurs, so you could change it if it matters:
$('script:contains("al'+'ert")').remove();
$('html').children('script:contains("alert")').remove();