Search code examples
javascripttransition

Get Href Link; if JPG to skip


I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin). Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.

Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.

function fadeInPage() {
    if (!window.AnimationEvent) { return; }
    var fader = document.getElementById('fader');
    fader.classList.add('fade-out');
  }

  document.addEventListener('DOMContentLoaded', function() {
    if (!window.AnimationEvent) { return }

    var anchors = document.getElementsByTagName('a'); 


******* for (var idx = 0; idx < anchors.length; idx += 1) {
      if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******

{

        continue;
      }
      anchors[idx].addEventListener('click', function(event) {

        var fader = document.getElementById('fader'),
            anchor = event.currentTarget;

        var listener = function() {



          window.location = anchor.href;
          fader.removeEventListener('animationend', listener);
        };
        fader.addEventListener('animationend', listener);

        event.preventDefault();
        fader.classList.add('fade-in');
      });
    }
  });

  window.addEventListener('pageshow', function (event) {
    if (!event.persisted) {
      return;
    }
    var fader = document.getElementById('fader');
    fader.classList.remove('fade-in');
  });


I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.


Solution

  • Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:

    
        for (var idx = 0; idx < anchors.length; idx += 1) {
               let fileType = anchors[idx].href.split('.').pop();
               //Do whatever
        }
    
    

    Or if you want to compare it to a preset list of extensions you can use a regex:

    
        for (var idx = 0; idx < anchors.length; idx += 1) {
               if (anchors[idx].href.match(/\.(jpg|png)$/)) {
                   //Do whatever
                 }
        }