Forum

Thread tagged as: Question

Using dynamic perch content within a script - issue with timing / page render

We have a fund raising ticker on a page, and we want to make a few values editable via Perch. These values sit inside a script tag in a variable array. We have tried $(document).ready and a few other approaches, but each time the perch content seems to be rendering after the JS so the ticker doesn't work/show. Hardcoding the ticker values works fine.

Any advice on best approach here?

Thanks.

Stuart Farrell

Stuart Farrell 0 points

  • 7 years ago
Rachel Andrew

Rachel Andrew 394 points
Perch Support

The Perch content is rendered on the server before delivery to the browser. It isn't possible for Perch content to be loaded somehow after all of the other HTML and JavaScript has been.

We can take a look but we'd need to see your code.

Right, so not sure what is happening then, since when we hard code it works and when Perch Content is populated to page in browser it looks exactly the same?

Below doesn't work:


<script> var addComma = function(num) { num += ''; var x = num.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; var counterOptions = { container: '#count-up', prefix: '$', <?php perch_content('Home-Counter');?> }; var counterContainer = document.getElementById('count-up'); counterContainer.innerHTML = counterOptions.prefix + addComma(counterOptions.start); $(document).ready(function() { new CountUp(counterOptions); }); </script>

Template is:


start: <perch:content id="text1" type="text" label="Start Value" required="true" />, end: <perch:content id="text2" type="text" label="End Value" required="true" />, increment: <perch:content id="text3" type="text" label="Increment" required="true" />, interval: <perch:content id="text4" type="text" label="Milliseconds" required="true" /> // milliseconds

Hard coded it works fine:


<script> var addComma = function(num) { num += ''; var x = num.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }; var counterOptions = { container: '#count-up', prefix: '$', start: 19455.00, increment: 19.17, interval: 100 // milliseconds }; var counterContainer = document.getElementById('count-up'); counterContainer.innerHTML = counterOptions.prefix + addComma(counterOptions.start); $(document).ready(function() { new CountUp(counterOptions); }); </script>

Any advice much appreciated.

Thanks, Stuart.

OMG.... our fault, the values entered in Perch had a comma in dollar value!!!! $%&#!

So ignore this one, all good.

:-/