Namespacing issue - Using a page's custom JS alongside global JS

Hi,

I’ve written a whole host of jQuery functions I’d like to put in my site’s global JS, so that I can call those functions on each page’s custom JS. In the global JS, I made a constructor called newPromo (plus about 100 other lines of relatedcode) that I’d like to call on each page so I don’t have to repeat. Please keep in mind all of this functions correctly in ONE page’s JS. I’m just having trouble splitting scripts between the two locations.

I am wrapping both global and page JS in the following wrapper: jQuery().ready(function ($) {...});

I’m getting errors such as Cannot read property 'newPromo' of undefined or function newPromo is not defined in the console when I’m trying to call the newPromo function.

I tried adding a half dozen iterations of namespacing, including using a global namespace such as var window.PromoEngine = window.PromoEngine || {}; but that was giving me similar errors.

Here’s a truncated version of the current global script:

jQuery().ready(function ($) {
  var window.PromoEngine = window.PromoEngine || {};
  promo = function (name, start, end) {
    this.name = name;
    this.startDate = new Date(start);
    this.endDate = new Date(end);
  }
  window.PromoEngine.newPromo = function (name, start, end) {
    promoList.push(new promo(name, start, end));
  }
 // more code here...
});

Here’s what I’d like to do on my individual pages:
window.PromoEngine.newPromo('.apr27', 'April 25, 2018, 11:37:00', 'April 28, 2018, 11:47:00');

I’m not very familiar with namespacing. Is there something specific to X Theme that I’m missing with my namespacing? Or is it something completely different?

Thanks

Hi arissmiller,

I’m sure that the page specific “Content” JS codes are loaded before the Global JS codes, so I don’t think writing your main code in the Global area then calling functions in Content area will work. I suggest adding your main code to the head area by adding this snippet into child theme’s functions.php file: (you can follow this guide to create a child theme)

function custom_js_code() { ?>

  <script>
   
  // Your JS code here.
  </script>

<?php }

add_action( 'wp_head', 'custom_js_code' );

By this way, the code will be loaded in the head, so I assume you can call these functions any where after that.

Thanks.

Hi Alaa,

Thanks so much for your help - that worked!

On behalf of my colleague, you’re welcome. Cheers! :slight_smile:

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.