Download
We're evolving to serve you better! This current forum has transitioned to read-only mode. For new discussions, support, and engagement, we've moved to GitHub Discussions.

Javascript JS files

  • #9352
    Avatar photo[anonymous]

    How and where to upload Javascript JS files?

    I have website created on Publii but I am not able to put any Javascript JS files. Kindly Help!

    #9353
    Avatar photo[anonymous]

    Perhaps the discussion thread at: https://forum.getpublii.com/topic/i-want-to-run-javascript-on-my-pages/ will help.

    #9423
    Avatar photo[anonymous]

    Hey there! Can you provide more info and context on what you’re trying to do (link to the JavaScript, theme used, what you’ve already tried to do, etc.)?

    #9431
    Avatar photo[anonymous]

    <span style=”font-weight: 400;”>So basically I want to use custom CSS and javascript on some of the posts only. I don’t want it in the entire theme. I want it specifically for a single post which will then become a page. I am not a web developer and I don’t have a lot of coding skills but if there is a YouTube video or step-by-step instructions, then I can certainly follow that.  So far publii has been great and I love this tool but I am stuck on this issue of custom CSS and JavaScript for specific posts. Please advise.</span>

    #9432
    Avatar photo[anonymous]
    #9434
    Avatar photo[anonymous]

    msn77a: do you have a link to the CSS and Javascript you want to add? This will help with assisting you as we don’t know where the JS and CSS is meant to go (inline vs external).

    If you’re not using an existing library, you could use Pastebin or Gist to share your code, since this forum isn’t ideal for code sharing.

    #9439
    Avatar photo[anonymous]

    Its not inline, its external.

    #9441
    Avatar photo[anonymous]

    Tools & Plugins > File Manager to conveniently upload the files.

    Is the custom Javascript always the same? If yes, I’d do it this way:

    1. Create overrides for your theme’s config.json and post.hbs files
    2. Edit the copied config.json and add a “select” type custom option, call it CustomJS or whatever
    3. Edit the copied post.hbs and near the closing body tag add your custom .js like so:
    {{#if @config.post.CustomJS}}
       <script src="/yourcustomscript.js"></script>
     {{/if}}

    Now when creating posts you’ll have a new toggle under Other options that will enable or disable your custom Javascript for that specific post only:

    If each post has to have different custom Javascript, well, it’s very similar except instead of “select” you add a custom “text” field and paste in a link to your .js file for each post.

    #9442
    Avatar photo[anonymous]

    privii, you’ve got the right idea.

    I just wanted to add: if the JS has to be added to the head of a particular post, the process will be a little different. It would be similar to the steps outline here, in a Gist I made for someone else: https://gist.github.com/candidexmedia/6304251e0bc2baf7ee07565b4f6fac49

    I’m also a fan of adding external JS code that I’m hosting on my server in my input folder. Otherwise, if it’s a CDN link, uploading yourself doesn’t matter.

    For the CSS: It could either be the same process, or Tools & Plugins > Custom CSS. OP may also have to add custom classes to HTML elements in the post using the WYSIWYG Source Code editor, or using the Block Editor’s HTML block. It’s hard to give further guidance without actual code snippets… :/

    #9619
    Avatar photo[anonymous]

    Sorry for replying so late but got caught up in other work.

    This is what I did so far step-by-step

    I am using theme – simple

    Step 1 – I created “simple-override” folder in input – themes

    step1

    Step 2 – In the override folder – I copied config.json and made a copy of post.hbs and renamed it as post_rabbit.hbs

    Step 3 – Made changes to post_rabbit.hbs and config.json

    step2

    Step 4 – When I got to publii, I don’t see any post templates and all my post options are gone.

    step3

    #9623
    Avatar photo[anonymous]

    I am not a developer so I am struggling with this. It would be great if we had youtube tutorial videos around these stuff.

    #9627
    Avatar photo[anonymous]

    I don’t think you necessarily need a custom post template. If you override post.hbs like I said in my previous post it would just add an option to enable the custom JavaScript or not, while everything else stays the same.

    Specifically, you’d put this into the config.json in the override folder, under postConfig:

     {
     "name": "CustomJS",
            "label": "Custom JavaScript",
            "value": "0",
            "type": "select",
      "options": [
      {
        "label": "Enabled",
        "value": 1
      },
      {
        "label": "Disabled",
        "value": 0
      }
    ]	
    }

    And this into post.hbs also in the override folder:

    {{#if @config.post.CustomJS}}
       <script src="/yourcustomscript.js"></script>
    {{/if}}

    And if your post options disappeared, you’re likely missing a comma in config.json, perhaps following the previous element under which you added the new one.

    (If you do want a custom post template, replace post_rabbit with rabbit in your config.json, and probably the same issue with the comma.)

    #9650
    Avatar photo[anonymous]

    config.json for custom templates should look like this:

    "postTemplates": {
            "rabbit": "A template about rabbits"
        },

    Here’s an example of how that looks in context:

    Capture-1234

    Save your config file.

    Then, copy your “post.hbs” file from the simple folder and paste it into your simple theme override. Rename your pasted file to “post-rabbit.hbs”.

    Close Publii, and then reopen Publii. It should appear in your Post options.

    In terms of lost config options: I echo what privii said about checking the commas. Based on your screenshots, it looks like you’re using VS Code/VS Codium, and it looks like it flagged two errors/problems in your config file.

    Now, whether you need a custom post template or not depends on what you’re working on. The example I sent earlier had a separate template because I imagined a website with a separate look and layout for recipe pages vs standard blog pages. privii’s suggestion might suffice for your needs, and their 2nd code snippet will either go in head.hbs, post.hbs, or footer.hbs depending on where your custom scripts and css should be referenced.

    #9652
    Avatar photo[anonymous]

    Thanks privii and candidexmedia for your help. I will try the suggestions given by you and update about the results. Thanks again.

    #9653
    Avatar photo[anonymous]

    I am getting blocked by wordfence when I try to put any code.

    #9655
    Avatar photo[anonymous]

    Dear privii and candidexmedia, I implemented your suggestions and it worked!

    custom-post

    but facing issues with simple custom css and javacript.

    (please note that I am not able to paste actual code as it gives me a wordfence block 403 error)

    CSS (I added the css style abc123 to style. css in the override folder), this is code that i used

    2023-03-21-11_58_25-_Untitled-Notepad

    Javascript

    2023-03-21-11_51_18-_Untitled-Notepad

    I uploaded this javascript using file manager to media files

    jsuploaded

    my post html

    2023-03-21-11_53_12-_Untitled-Notepad

    Issues I am facing,

    CSS style is not getting applied
    Javascript is not working

    When I use the above in any online html editor then it works but not in Publii. What am I doing wrong? Pls advise.

    #9661
    Avatar photo[anonymous]

    You shouldn’t be editing the style.css because it will get overwritten every time the website gets rendered.

    Instead put your custom css code in main.css

    See this reply by Bob
    https://forum.getpublii.com/topic/publii-overwrites-style-css-in-simple-override-assets-css-directory/#post-6240

    Never override style.css as this is the output file, instead, you should use main.css.

    The style.css is a sum of:

    1. theme-variables.js output
    2. main.css
    3. GDPR popup CSS
    4. visual-overrides.js output
    5. custom CSS

    More about how the Publii renders the theme files: https://getpublii.com/dev/how-the-theme-is-rendered/

    #9662
    Avatar photo[anonymous]

    Ok, I will put in the main.css and check.

    Any input around the javascript issue?

    #9663
    Avatar photoBob

    Since you have already created the override folder, please use it to load the script. Place your script at /simple-override/assets/js/your_script.js, copy the footer.hbs file to /simple-override/partials/footer.hbs, and edit this file by adding the following line:

    <script src="{{js "your_script.js"}}"></script>

    This should work.

    #9666
    Avatar photo[anonymous]

    Dear Bob,

    I followed your suggestion and placed the script at /simple-override/assets/js/rabbitjs.js,
    then copied the footer.hbs file to /simple-override/partials/footer.hbs,
    and edited this file as per your comment above.
    2023-03-21-13_50_02-_footer.hbs-Notepad

    Now how do I call this javascript in my post?

    If I put this syntax

    2023-03-21-16_37_26-Javascript-JS-files

    then its not working

    #9669
    Avatar photo[anonymous]

    Looks like you already called the Javascript with the https://getpublii.com/dev/js-helper/ in footer.hbs.

    That said, you’re calling the JavaScript for all posts. If you only need to call that script for certain posts, use the #if technique described by privii earlier, or create a new partial similar to footer.hbs in the override that has the script that you need, and invoke it in in your rabbit post emplate instead of footer.hbs. The #if will be easier to maintain and upgrade later, but you’ll have to add more post config options for it, if you haven’t already.

    #9670
    Avatar photo[anonymous]
    [anonymous] wrote:

    Looks like you already called the Javascript with the https://getpublii.com/dev/js-helper/ in footer.hbs.

    That said, you’re calling the JavaScript for all posts. If you only need to call that script for certain posts, use the #if technique described by privii earlier, or create a new partial similar to footer.hbs in the override that has the script that you need, and invoke it in in your rabbit post emplate instead of footer.hbs. The #if will be easier to maintain and upgrade later, but you’ll have to add more post config options for it, if you haven’t already.

    Now I am confused…which option should I follow because both not working for me currently.

    #9671
    Avatar photoBob

    In my example, the rabbitjs.js script is applied to all pages. If you want to enable or disable it for specific posts, you need to wrap it with the condition from the Privi example e.g.

    {{#if @config.post.CustomJS}}
      <script src="{{js "rabbitjs.js"}}"></script>
    {{/if}}

    That’s it.

    #9672
    Avatar photo[anonymous]
    [anonymous] wrote:

    ok, I made the required changes to the footer.hbs

    But still CSS style is not getting applied and Javascript is not working

    This is what I am writing in the post html

    2023-03-21-22_27_43-_Untitled-Notepad

    #9674
    Avatar photo[anonymous]

    just few additional inputs…don’t know if it will help…

    my css style – abc123 added in main.css (in override folder)

    2023-03-21-22_32_40-main.css-Visual-Studio-Code

    my js – rabbitjs.js (in override folder plus footer.hbs modified) which has function rabbit()

    2023-03-21-22_33_00-rabbitjs.js-Visual-Studio-Code

    #9677
    Avatar photoBob

    attach your website backup in PM

    #9686
    Avatar photo[anonymous]
    This reply has been marked as private.
    #9687
    Avatar photoBob

    I got it. I’ve identified a few issues; since the thread is quite long and several people participated in it, I will briefly explain why it didn’t work.

    1. When you overwrite the original file, maintain the same folder structure, thus, the footers.hbs file should be placed within the partials folder: /simple-override/partials/footer.hbs
    2. The script is being loaded in the wrong place,  You are loading it within the lazyload condition, and this is why it does not load on the site:
      {{#if @config.site.mediaLazyLoad}}
          <script>        
              var images = document.querySelectorAll('img[loading]');
      
              for (var i = 0; i < images.length; i++) {
                  if (images.complete) {
                      images.classList.add('is-loaded');
                  } else {
                      images.addEventListener('load', function () {
                          this.classList.add('is-loaded');
                      }, false);
                  }
              }
          </script>
      
         {{#if @config.post.CustomJS}}
           <script src="{{js "rabbitjs.js"}}"></script>
         {{/if}}
      
      {{/if}}
    3. The CSS rules (123abc) were incorrectly added to the overridden main.css file; the ID attribute requires a hash character (#) in the CSS file, so it should appear as: #123abc {….}
    4. The onclick event is removed from the WYSIWYG editor, so the button no longer triggers the intended action when clicked. Therefore you should modify the script to work with, e.g., class added to the toggle button.

    And a few of my comments that will help address it in a slightly more user-friendly way 🙂

    1. You can avoid using the additional post template, as the script is already being loaded from the footer.hbs file.
    2. You don’t need to override the main.css file since there is only one rule for styling the hidden block. Instead, apply this rule using the Custom CSS tool.
    3. Do not wrap the CSS rules in <style> tag when using the Custom CSS tool.
    4. I recommend adjusting your script to avoid using inline style tags to hide the block and ensure that it can be used multiple times on the same page:

      rabbitjs.js file:

      function rabbit(target) {
        target.classList.toggle("hidden");
        target.classList.toggle("visible");
      }
      
      document.addEventListener("DOMContentLoaded", function() {
        var buttons = document.getElementsByClassName("toggle-button");
      
        for (var i = 0; i < buttons.length; i++) {
          buttons.addEventListener("click", function() {
            var targetId = this.getAttribute("data-target");
            var target = document.getElementById(targetId);
            rabbit(target);
          });
        }
      });

      The post content:

      <p><button class="toggle-button" data-target="abc123">Toggle 1</button></p>
      <div id="abc123" class="hidden-area hidden">Content to be toggled 1</div>
      <p><button class="toggle-button" data-target="def456">Toggle 2</button></p>
      <div id="def456" class="hidden-area hidden">Content to be toggled 2</div>

      Custom CSS tool:

      .hidden-area {
        width: 100%;
        padding: 50px 0;
        text-align: center;
        background-color: lightblue;
        margin-top: 20px;
        }
      
      .hidden-area.hidden {
        display: none;
       }
      
      .hidden-area.visible {
        display: block;
      }

      I will include a full site backup with all my changes in the next post.

    #9688
    Avatar photoBob
    This reply has been marked as private.
    #9689
    Avatar photo[anonymous]

    Ok, Thanks Bob. I will go through all the changes. Thanks a lot!

    #9691
    Avatar photo[anonymous]
    This reply has been marked as private.
    #9692
    Avatar photoBob

    It also works online, just clear the browser cache.

    #9703
    Avatar photo[anonymous]

    Its not working online, I cleared browser cache, tried different browsers, tried different laptops, mobile devices, different wifi connections but its the same result. Works on localhost but not online.

    https://cloudtutor.in/rabbit-test2/

    #9704
    Avatar photoBob

    For me, it works very well. Do you have any errors in dev console?

    #9706
    Avatar photo[anonymous]

    No, please see attached

    #9708
    Avatar photoBob

    It seems like a caching issue to me. Based on your screenshot, I can see unstyled blocks labeled ‘Content to be toggled 1/2,’ which should be hidden and displayed on a blue background, so the updated CSS is also not being loaded.

    #9709
    Avatar photo[anonymous]

    Ok, Thanks! Sorry for bothering so much.