Jump to content
cam503

Adding JS to specific pages

Recommended Posts

Hey folks,

I've never used ProcessWire before. I took a quick look at the API documentation, but wasn't able to find anything that met my needs.

I would like to add a JavaScript snippet to specific pages. We're implementing a heatmapping tool, and each page that it will be implemented on will have a unique JS code that can only appear on that page.

My first thought was to look into the template file for the actual page, but I'm not quite sure which method to use to say "Only add this Javascript code to this page."

Any help would be greatly appreciated. I've attached a screenshot of one of the template pages in question. I didn't write it, but perhaps it could be helpful.

post-1914-0-49808200-1383946792_thumb.pn

Share this post


Link to post
Share on other sites

Hi cam503.

There are several ways this could be done, and there probably won't be a right or wrong answer. I probably won't be able to give you the best answer, because I don't know how your site is structured, but I'll try to point you in the right direction :)

In your example above, it looks like the $helpers->renderPage() function handles the final output of the page based on the data you set above. You could extend that to say:

$page->javascript = '<script>var something = 1;</script>';

You could then access that in the same way you do for the "layout" property.

Another way might be to add a new field to your page template(s) where the javascript could be entered in the control panel, and you could easily access this from the $page variable within the template.

Another way could involve javascript files named after the page's "name" field value, and you could then use this as a basis for loading a script via <script src="..."> after a quick file_exists() check.

Share this post


Link to post
Share on other sites

Thanks Craig.

I just checked the API, and it appears renderPage() is not a native function. Any idea where custom functions are stored?

Edit: Nevermind. Just found it under "Modules." Man, this is a lot different than Wordpress. Lol...

Edited by cam503

Share this post


Link to post
Share on other sites

Edit: Nevermind. Just found it under "Modules." Man, this is a lot different than Wordpress. Lol...

and that's why it's so awesome :D

Share this post


Link to post
Share on other sites

I'd simply add a textarea field in your templates, and check if there's any content, e.g. 

if(strlen($page->extraJS) > 3)) { 
    echo $page->extraJS;
} 

And in that field, either enter the JS code. Or, if the JS files are already in your site/templates/scripts/ folder, just specify the .js file-name.

if(strlen($page->extraJS) > 3)) { 
    echo '<script src="' . $config->urls->templates . 'scripts/' . $page->extraJS . '"></script>';
} 
  • Like 1

Share this post


Link to post
Share on other sites

I like Dragan's approach if you don't mind mixing JS into the CMS side of things. Whether that's a good practice or not really depends on who's going to be using the admin.

If you want to keep this on the development side rather than the content side, one approach I've used is to keep JS files named with the ID of the page. When a JS file existed that matched the ID of the page, it would be included in the <head> section. Example:

<?php
$file = "scripts/$page->id.js";
if(is_file($config->paths->templates . $file)) {
  echo "<script src='{$config->urls->templates}$file'></script>";
} 

More often, I use this approach with the template file, i.e. have a file named basic-page.js that gets included on any pages using the basic-page template. 

  • Like 5

Share this post


Link to post
Share on other sites

I usually identify the page using the template name or page title something like this:

if ($page->template == 'home'){
 echo "<script src='path/to/js'></script>";
}
//or

if ($page->title == 'home'){
 echo "<script src='path/to/js'></script>";
}

cheers.

Share this post


Link to post
Share on other sites

Hello,

I'm working on my first project with PW. Working with PW is amazing so far. As I am coming over from the Joomla world I am used to adding scripts to individual pages with a Joomla built in method.

Searching for the PW way of doing this, I came along that post where I found this snippet of code: 

$config->scripts->add($config->urls->templates . "scripts/lightbox.js");

Great, I thought. But using just that snippet wouldn't include the script. I had to add a second snippet

foreach($config->scripts as $url) echo "<script type='text/javascript' src='$url'></script>";

(which I also found in that other post) to actually load the script wherever I wanted in my template file.

Lets assume you are working with the default PW Profile on a fresh install and want to load the lightbox.js only on the homepage and the template file for your homepage is home.php.

Then you would include the first snippet in your home.php.

The second snippet goes either in your head.inc into the head section or in your foot.inc at the bottom (whereever you prefer to load your js).

This is a quite generic way to include scripts. If you wanted to have another script loaded only, lets say, on a contact page with template file contact.php the you just need to add a snippet, e.g.

$config->scripts->add($config->urls->templates . "scripts/contact.js"); 

to contact.php.

The second snippet

foreach($config->scripts as $url) echo "<script type='text/javascript' src='$url'></script>"; 

already sits in your head.inc or foot.inc where you put it before and it will take care of including also contact.js because of the foreach loop.

I guess that most of you already know this. But for a newbie like me I had to write this down to properly digest it and maybe it is helpful to someone else.

Cheers

gerhard

  • Like 5

Share this post


Link to post
Share on other sites

Greetings,

Hey, I thought your avatar looked familiar!  Of course... gerhard!  Welcome to another former Joomla guy.  Even better, a former Seblod guy!  There are a few of us here.

Some links that might be of interest to you:

http://processwire.com/talk/topic/4844-joomla-vs-pw/

http://processwire.com/talk/topic/3917-importing-users-and-content-from-joomla/

http://www.noupe.com/cms/processwire-cms-with-a-difference-77309.html

http://processwire.com/talk/topic/2129-justifying-diy-coding-vs-installing-modules/?p=20438

I understand what it's all about to transition from Joomla to ProcessWire.  If you need help, just post and we'll jump in.

Welcome again,

Matthew

  • Like 2

Share this post


Link to post
Share on other sites

Hi Matthew,

great to see you here and thanks for the warm welcome. Yes, my avatar is almost the same as in Seblod forum, only different color.

The links you've posted are interesting and I totally understand some of the frustration with J! and Seblod.

Working with PW is just so much smoother although the conversion will take me a while.

So I might indeed throw some questions at the forum until I know my ways around this great piece of software better.

So see you around.

Cheers

gerhard

  • Like 1

Share this post


Link to post
Share on other sites

Welcome gebeer,

There're some ProcessWire addicts over here, watch out, so you've been warned now!

if(count($page->images)) {
    foreach($page->images as $img) {
        if($img->width > 600) {
            $config->styles->append('/path/to/popup.css');
            $config->scripts->append('/path/to/popup.js');        
            break;
        }
    }
}
  • Like 4

Share this post


Link to post
Share on other sites

@Martijn

cheers for the welcome.

I can already see how PW can be addictive. Was sitting and playing around with it late last night, the night before and the night before...

  • Like 1

Share this post


Link to post
Share on other sites

Kop khun maak krap.  :)

Bai pratheet Thai boi mai?

  • Like 1

Share this post


Link to post
Share on other sites

I was asking if you visit Thailand often  ;)

Ko Lipe is nice, indeed. I live in Ranong and love the little Island Koh Chang in the Andaman sea.

  • Like 1

Share this post


Link to post
Share on other sites

Do you make a 3 months visa boarder run or get a stamp for a whole year ?

Share this post


Link to post
Share on other sites

@pwired

I stay there for max 5 month a time. So I get a tourist visa for 60 days with 3 entries which gives me 180days total and at the moment costs 90€.

@Martijn

I know that feeling.

Share this post


Link to post
Share on other sites

My brother is living there. Life and people are so much more easy there, not the hectic in the west, thai kitchen is fantastic, e.g. you can eat a kwitajouw soup on the corner of every street. Easy living.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By adisharma
      Hello Everyone, I am new in this community and I am learning typescript but my friend was suggested to me go with javascript profile because it is most popular scripting language for many web projects and huge community support with lots of documentation and support for solving issues. Can anyone clear this point which one is better for future points of view typescript or javascript?
    • By Majesrse
      Hey i have a problem with the code:
      $('a').click(function(link) { link.preventDefault(); location = this.href; $('body').fadeOut('slow', open); }); function more() { window.location = location; } It's writen in Jquery but i will convert it to vanilla js. Can somone help me with it?
    • By CareerTeam GmbH
      Hi there,
      We are an executive search agency based in Germany looking for a freelancer (2-5 days per week) supporting us with the development and design of our websites. The position will be located in Hamburg, Germany and it would be great if you are on short call. German language knowledge is mandatory. 
      You can reach me via email jobs@careerteam.de.
      Thank you!
      Regards
      Annemie
    • By Orkun
      Hi Guys
      I needed to add extended functionalities for the InputfieldDatetime Module (module is from processwire version 2.7.3) because of a Request of Customer.
      So I duplicated the module and placed it under /site/modules/.
      I have added 3 new Settings to the InputfieldDatetime Module.
      1. Day Restriction - Restrict different days based on weekdays selection (e.g. saturday, sunday) - WORKING

       
      2. Time Slots - Define Time slots based on custom Integer Value (max is 60 for 1 hour) - WORKING

       
      3. Time Range Rules per Weekday - Define a minTime and MaxTime per Weekday (e.g. Opening Hours of a Restaurant) - NOT WORKING PROPERLY

       
      The Problem
      Time Slots and Day Restriction working fine so far. But the Time Range Rules per Weekday doesn't work right.
      What should happen is, that when you click on a date, it should update the minTime and maxTime of the Time Select.
      But the change on the select only happens if you select a date 2 times or when you select a date 1 time and then close the datepicker and reopen it again.
      The time select doesn't get change when you select a date 1 time and don't close the picker.
      Here is the whole extended InputfieldDatetime Module.
      The Files that I have changed:
      InputfieldDatetime.module InputfieldDatetime.js jquery-ui-timepicker-addon.js (https://trentrichardson.com/examples/timepicker/) - updated it to the newest version, because minTime and maxTime Option was only available in the new version  
      Thats the Part of the JS that is not working correctly:
      if(datetimerules && datetimerules.length){ options.onSelect = function(date, inst) { var day = $(this).datetimepicker("getDate").getDay(); day = day.toString(); var mintime = $(this).attr('data-weekday'+day+'-mintime'); var maxtime = $(this).attr('data-weekday'+day+'-maxtime'); console.log("weekday: "+day); console.log("minTime: "+mintime); console.log("maxTime: "+maxtime); var optionsAll = $(this).datetimepicker( "option", "all" ); optionsAll.minTime = mintime; optionsAll.maxTime = maxtime; $(this).datetimepicker('destroy'); $(this).datetimepicker(optionsAll); $(this).datetimepicker('refresh'); //$.datepicker._selectDate($(this).attr("id"),date); //$.datepicker._base_getDateDatepicker(); // var inst = $.datepicker._getInst($(this)); // $.datepicker._updateDatepicker(inst); /*$(this).datetimepicker('destroy'); InputfieldDatetimeDatepicker($(this), mintime, maxtime); $(this).datetimepicker('refresh'); */ // $(this).datetimepicker('option', {minTime: mintime, maxTime: maxtime}); } } Can you have a look and find out what the Problem is?
      InputfieldDatetime.zip
       
      Kind Regards
      Orkun
    • By dragan
      What the f*ck JavaScript? A list of funny and tricky JavaScript examples
      Some really odd stuff there... worth scanning through. I chuckled more than once...
      "b" + "a" + +"a" + "a"; // -> 'baNaNa' NaN === NaN; // -> false (![] + [])[+[]] + (![] + [])[+!+[]] + ([![]] + [][[]])[+!+[] + [+[]]] + (![] + [])[!+[] + !+[]]; // -> 'fail' typeof NaN; // -> 'number' (It ain't new, so sorry if this has been posted previously here)
×
×
  • Create New...