Friday, January 25, 2019

javascript: fadeIn() fadeOut() jQuery equivalents

Functions:
//fade out function
    function fade(element) {
    var op = 1;  // initial opacity
    var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
            element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
      }, 3); //set the time here
    }

    //fade in element function
    function unfade(element) {
      var $html = document.getElementsByTagName('html')[0];
      var op = 0.1;  // initial opacity
      element.style.display = 'block';
      var timer = setInterval(function () {
          if (op >= 1){
              clearInterval(timer);
          }
          element.style.opacity = op;
          element.style.filter = 'alpha(opacity=' + op * 100 + ")";
          op += op * 0.1;
        }, 3); //set the time here
    }
Applied to a menu item
    //define elements by class name
    var $menu = document.getElementsByClassName("navbar-toggler");
    var $rightMenu = document.getElementsByClassName("main-menu-ul");
    //error handler in case classes/elements are not available
    if ($menu !== null && $menu !== 'undefined' && $menu !== undefined) {
      $menu[0].onclick = function () {
        var $menu_overlay = document.getElementsByClassName("menu-overlay");
        var $body = document.getElementsByTagName("body");
        if ($menu_overlay !== null && $menu_overlay !== 'undefined' && $rightMenu !== null && $rightMenu !== 'undefined') {
          setTimeout(function(){
             $rightMenu[0].classList.toggle("open-menu"); //this will add the "open-menu" class ONLY IF it is not present
          },50);
          unfade($menu_overlay[0]);
        }
      };
    }

No comments:

Post a Comment