Fixing JavaScript errors

When we created our homepage, we attached a couple of JavaScript libraries directly to our page--front.html.twig template. However, since we are loading our theme's custom scripts file globally, this can sometimes create unnecessary JavaScript errors.

If we inspect our About Us page, we will see one such error caused by our script trying to configure the FlexSlider library, which only exists on our homepage.

Fixing JavaScript errors

While we are not covering the fundamentals of JavaScript and how to write proper syntax, it is important to point out this issue. This can be a common error when using JavaScript with the different techniques used to theme Drupal 8. So, let's take a quick look at how to fix this to have this as part of our theming tools moving forward.

Begin by navigating to themes/octo/js and opening the octo.js file. From here, we can follow these steps to resolve the JavaScript error:

  1. Locate the Flexslider function call.
  2. Wrap the function in a conditional structure that will look to see if the flexslider library exists before configuring it. The revised structure should look like the following:
    //-- Flexslider
       (function() {
    
         if (typeof $.fn.flexslider === 'function'){
    
           $('.flexslider').flexslider({
             direction: "vertical",
             controlNav: false,
             directionNav: false
           });
    
         }
    
       })();
  3. Save octo.js.

The simple typeof operator can be used with any JavaScript library we may be referencing within our theme to ensure that we don't initialize a library unnecessarily. If we clear Drupal's cache and then reload our About Us page, we will no longer have any JavaScript function errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.208.97