Skip to content

Instantly share code, notes, and snippets.

@amitabhaghosh197
Last active March 13, 2018 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitabhaghosh197/71088a4f067e53cf818d to your computer and use it in GitHub Desktop.
Save amitabhaghosh197/71088a4f067e53cf818d to your computer and use it in GitHub Desktop.
jQuery importants #jquery #important

Instantiate Bootstrap selectpicker for Ajax HTML

function getstatenext(cId, controllerName)
    {
       $.ajaxSetup({cache: false});
        var loadUrl = js_site_url + "getstatenew/" + cId;
        $.ajax({
            type: "POST",
            url: loadUrl,
            dataType: "html",
             success: function(responseText)
            {
                document.getElementById('state').innerHTML = responseText;
                $('.center-select').selectpicker('refresh');

            },
            error: function(jqXHR, exception) {
                return false;
            }
        });
        return false;
    }
    

Instantiate inside success object inside Ajax and add 'refresh' to refresh the select options in the selectpicker

###When I load Bootstrap popver content with ajax, the popover is not showing

$(document).ajaxComplete(function() {
 $("#example").popover();
});

http://stackoverflow.com/questions/22277300/bootstrap-popover-not-working-when-loaded-with-ajax

###How can I make a page redirect using jQuery?

window.location.href = "http://stackoverflow.com";

###How can I refresh a page with jQuery?


$('#something').click(function() {
    location.reload();
});

###How to Get Element Distance From Top with jQuery offset()


$(document).ready(function(){
   $(window).bind('scroll', function() {
      var scrollTop = $(window).scrollTop();
      var elementOffset = $('your-element').offset().top;
      var currentElementOffset = (elementOffset - scrollTop);
   });
});

Reff: https://stanhub.com/how-to-get-element-distance-from-top-jquery-offset/

###jQuery ScrollTo a position

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

Reff: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element

Filter for every 3rd element in jQuery

I started to add a div for every 3rd element. There are two ways

First Option with .filter

$('.features_list .row .col-md-4').filter(function(index){
        return(index %4 == 2);
   }).after('<div class="clearfix" />');
   

Reff:

  1. http://stackoverflow.com/questions/12025931/every-nth-element-in-a-jquery-set
  2. http://lukasz.io/uncategorized/add-class-every-3rd-element-jquery/
  3. http://stackoverflow.com/questions/5006604/how-do-i-select-every-nth-of-a-specific-child-element-in-jquery

2nd Option with (nth)

$('.features_list .row .col-md-4:nth-child(3n+3)').after('<div class="clearfix col-md-12" />');

Reff:

  1. http://stackoverflow.com/questions/3068480/how-can-i-add-a-class-to-every-4th-1-element

How to remove placeholder on focus

$('input,textarea').focus(function () {
  $(this).data('placeholder', $(this).attr('placeholder'))
    .attr('placeholder', '');
                }).blur(function () {
                $(this).attr('placeholder', $(this).data('placeholder'));
                });

Reff: http://stackoverflow.com/questions/19676084/how-to-remove-placeholder-on-focus

Twitter Bootstrap 3 dropdown menu disappears when used with prototype.js

Add this before jQuery scripts


(function() {
    var isBootstrapEvent = false;
    if (window.jQuery) {
        var all = jQuery('*');
        jQuery.each(['hide.bs.dropdown', 
            'hide.bs.collapse', 
            'hide.bs.modal', 
            'hide.bs.tooltip',
            'hide.bs.popover',
            'hide.bs.tab'], function(index, eventName) {
            all.on(eventName, function( event ) {
                isBootstrapEvent = true;
            });
        });
    }
    var originalHide = Element.hide;
    Element.addMethods({
        hide: function(element) {
            if(isBootstrapEvent) {
                isBootstrapEvent = false;
                return element;
            }
            return originalHide(element);
        }
    });
})();

jQuery.noConflict();

Reff:

  1. http://stackoverflow.com/questions/19139063/twitter-bootstrap-3-dropdown-menu-disappears-when-used-with-prototype-js
  2. http://www.softec.lu/site/DevelopersCorner/BootstrapPrototypeConflict

Image onClick show and start Youtube video

$('#Video').on('click', function(e){
		
		$(this).css('background-image','');
		$('#iFram').show();
		
		var iframeSrc= $(this).find('iframe').attr('src');

		 $(this).find('iframe').attr('src', iframeSrc+'?rel=0&autoplay=1');
		
		});

Section fade on scroll

.fadeInBlock {
    opacity:0;
}

//JQUERY

$(function() {
    $(window).scroll( function(){
    
       
        $('.fadeInBlock').each( function(i){
            
            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            
            /* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it  */
            bottom_of_window = bottom_of_window + 200;  
          
            if( bottom_of_window > bottom_of_object ){
                
                $(this).animate({'opacity':'1'},500);
                    
            }
        }); 
    
    });
});

Reff: http://www.ordinarycoder.com/jquery-fade-content-scroll/

Image to Canvas

<section>

<!--<div id="IMG"></div> -->

<style>
.cans{
  width: 90px;
  height: 110px;
  overflow: hidden;
  display: block;
}
  .MyCanvas{
   width: 100%;
   position: absolute;
   top: 50%;
   left: 50%;
   display: block;
   transform: translate(-50%, -50%);
  }
</style>

  

  <script>
    
    var $img = $('#img_a').attr('src');
     //$img = $img.replace('url(','').replace(')','');

  

$('#IMG').html('<p><img src="' + $img+ '" id="neIMG"></p>');

 function convertImage(canvas) {
    var canvasContext = canvas.getContext('2d');

            var img = new Image();
            // Replace the url for your image!
            img.src = $('.img_a').attr('src');       
             
            img.onload = function() {
              canvas.width = img.width;
              canvas.height = img.height;
                canvasContext.drawImage(img, 0, 0);
                var imgSrc = canvas.toDataURL("image/png");
                $('.img_a').attr('src', imgSrc);
        };
    }

    var can = $('.MyCanvas')[0];
    convertImage(can);
  </script>

    
  </section>

Slick Slider Accessing Current SLides for event

Though the pupose of the event function is wrong here, but the slick current slides work like this example: kenwheeler/slick#1036, http://jsfiddle.net/3b4kqy9p/2/

function iframeStop(){
var $videoContainer = $('.video-carousel');
         $videoContainer.on('afterChange', function(event, slick, currentSlide, nextSlide){

         var $slides = $videoContainer.slick("getSlick").$slides;
         var iframe = $slides.eq(currentSlide).find('iframe');
         var currentSlide = $videoContainer.slick('slickCurrentSlide');
         console.log( iframe.attr('class'));

         var video = iframe.attr('src');

         if(!currentSlide){
           iframe.attr('src','');
         } else {

            iframe.attr('src',video);

         }


       });


       };//iframeStop()

      //iframeStop();

Pause/ Stop Youtube video through javascript in slick slider and bootstrap tabs

  1. Main objects for Youtube video are 1. .contentWindow and .postMessage
  2. What is ContentWindow: The contentWindow property returns the Window object generated by an iframe element link: http://www.w3schools.com/jsref/prop_frame_contentwindow.asp
  3. Where postMessage used: To send a message to another window referenced by win, the postMessage method is used. Link: http://javascript.info/tutorial/cross-window-messaging-with-postmessage, https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
  4. Get the actual Dom: to get the actual window DOM element iframe : reff: http://stackoverflow.com/questions/28211384/postmessage-generates-error-undefined-is-not-a-function
  5. How do I pull a native DOM element from a jQuery object? : link : https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/

Script for slick slider:

var $videoContainer = $('.video-carousel');
function iframeStop(){
  $videoContainer.on('beforeChange', function(event, slick, currentSlide, nextSlide){
     var data = {"event":"command","func":"pauseVideo","args":""};
     var message = JSON.stringify(data);
      $("iframe", slick.$slides[currentSlide])[0].contentWindow.postMessage(message, '*');

       });



       };//iframeStop()

      iframeStop();

Script for Bootstrap tab

function stopIframeonTabClick(){

        $('.video-nav-tab a').click(function (e) {

           var selected = $(this).parent().index();

        $('.video-nav-tab a').each(function(index){

        if(index != selected){

        var iframe = $(".video-tab-content.tab-content .tab-pane.active .slick-active .video-wrapper ").find('iframe');
        var iframeID = iframe.attr('id');
        console.log(iframeID);


        var data = {"event":"command","func":"stopVideo","args":""};
      var message = JSON.stringify(data);
      $('#'+iframeID )[0].contentWindow.postMessage(message, '*');

      }
        });
      });
      };//stopIframeonTabClick()

      stopIframeonTabClick();

Help Links:

  1. http://stackoverflow.com/questions/39978087/slick-carousel-how-to-pause-and-play-embedded-youtube-videos-on-slide-change

Get a position of an element

 var collectionHeaderHeightSet = function(){
    
  
    
    var $collectionContainerHeader = $('.content-no-push .article-header');
    var $collectionContainerHeaderHeight = parseInt($collectionContainerHeader.outerHeight());
    var $collectionContainerHeaderImage = $collectionContainerHeader.find('img');
    var $collectionContainerHeaderImageHeight = $collectionContainerHeaderImage.height();
    
    if( $collectionContainerHeader.length ){
      var $collectionContainerHeaderPos = $collectionContainerHeader.offset().top;
    }
    
    if( $collectionContainerHeaderImage.length ){
    var $collectionContainerHeaderImagePos = $collectionContainerHeaderImage.offset().top;
    }
    
    
    var $remainingPosofContainerHeaderImagefromTop = parseInt( $collectionContainerHeaderImagePos - $collectionContainerHeaderPos );
    var $remainingHeaderHeightafterTopDeduction = parseInt( $collectionContainerHeaderHeight - $remainingPosofContainerHeaderImagefromTop);
    var $imageBottompositionHeight = parseInt( $collectionContainerHeaderImageHeight - $remainingHeaderHeightafterTopDeduction );
    var $finalTotalHeightofHeaderwithImage = parseInt( $collectionContainerHeaderHeight + $imageBottompositionHeight );
    //alert( $finalTotalHeightofHeaderwithImage );
    var $collectionContentWrapper = $('.content-no-push').find('.collection-container-content-block');
    
    setTimeout(function(){
     $collectionContentWrapper.show();
    
    },300);
    
    var $collectioncontainerContentBlock = $('.content-no-push .collection-container-content-block-header');
    $collectioncontainerContentBlock.css({
      'min-height' : $finalTotalHeightofHeaderwithImage
    
        });
    
  
     };

Referencing VideoJs Player

Ref: https://github.com/videojs/video.js/blob/stable/docs/guides/api.md

var myPlayer = videojs('example_video_1');

OOPS
  1. https://jsfiddle.net/amitabhaghosh197/n7fwc8wy/3/
  2. https://code.tutsplus.com/tutorials/the-basics-of-object-oriented-javascript--net-7670
  3. https://www.sitepoint.com/oriented-programming-1-4/
  4. https://toddmotto.com/mastering-the-module-pattern/

Understanding $.extend

  1. https://stackoverflow.com/questions/4528744/how-does-extend-work-in-jquery
  2. https://api.jquery.com/jquery.extend/

Understanding $.proxy

  1. https://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery

Localstorage

  1. https://www.webdesignerdepot.com/2013/04/how-to-use-local-storage-for-javascript/
  2. https://stackoverflow.com/questions/40791207/setting-and-getting-localstorage-with-jquery

Debounce

  1. https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript
    1. https://davidwalsh.name/javascript-debounce-function
  2. http://underscorejs.org/#debounce

Cookie jQuery

Link : https://github.com/js-cookie/js-cookie https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies

 var openSidebarFabric= function(){
    
      
    $.each(FabricBtn, function(index, element){
     var $element = $(element);
      $element.on('click', function( e ){
      
      e.preventDefault();
       var $this = $(this);
       $this.closest( ProductPageForm ).toggleClass('sidebar-fixed-open');
      });
    
    });// btn click
    
    /*
   var ThemeProduct = new theme.Product;
         var Variant = ThemeProduct.selectors;
    var initVariant = ThemeProduct.initProductVariant();
    var v = initVariant.variants;
    console.log(v);
      */   
      
      var input = ProductPageForm.find('input[type="radio"]');
    
      var fabricDisplayDiv = input.closest(ProductPageForm).next('.fabric-index');
      var fabricDisplayHeadingText = fabricDisplayDiv.find('.article-header');
    
      $.each(input, function( index, element){
        $(this).on('change',function(e){
          e.preventDefault();
        if(input.is(':checked')){
         $(this).closest(ProductPageForm).removeClass('sidebar-fixed-open');
         
          var nextLabel = $(this).find('+ label');
          var nextLabelBGImg = nextLabel.css('background-image');
              nextLabelBGImg = nextLabelBGImg.replace('url(','').replace(')','').replace(/\"/gi, "");
          var nextLabelText = nextLabel.text();
          console.log(nextLabelText);
          
           Cookies.set('name', nextLabelBGImg );
           Cookies.set('label', nextLabelText );
           var img = Cookies.get('name');
           var text_label = Cookies.get('label');
          
          
          setTimeout( function(){
            
            fabricDisplayDiv.fadeIn();
            //fabricDisplayDiv.find('.featured-img').css('background-image','url(' + img + ')');
            //fabricDisplayDiv.find('.hidden-img').text( img );
            //fabricDisplayHeadingText.find('span').text(nextLabelText);
            location.reload();
            
            
          }, 400);
        }
        
        });
        
      });//input each
    var f_img = Cookies.get('name');
    var f_img_label = Cookies.get('label');
    if(f_img){
    fabricDisplayDiv.find('.featured-img').css('background-image', 'url(' + f_img + ')');
    } else {
    fabricDisplayDiv.find('.featured-img').css('display', 'none');
    }
    
    if(f_img_label){
    fabricDisplayHeadingText.find('span').text(f_img_label);
    } else{
    fabricDisplayHeadingText.find('span').parent().css('display', 'none');
    }
    
    
    
    var radioWrapperContainer = ProductPageForm.find('.product-form__item.sidebar-fixed .single-option-radio ');
     radioWrapperContainer.slimScroll({
        height: '90vh'
    });
    
   //var slateVariants = new theme.Product;
    
    //console.log(slateVariants );
  
  };

$.extend


<style>
  
  a{ display:  inline-block; padding: 25px; }
  #result{

    display: block;
    min-height: 50px;
  }
</style>
  <div id="result">Find the result</div>
  <div class="main-nav">
    <a href="">Me</a>
    <a href="">You</a>
  </div>
  <script>
   
    var Theme = function(){
      "use strict";
      
     var settings = settings || {};
     var options = options || {};
     
     
     settings = {
       mainDiv : $('.main-nav'),
       anchors : $('.main-nav').children('a'),
       resultDiv : $('#result')
     };
     
     options = {
       
       clickAnchor : function(i){
       
       var text = $(i).text(); 
      settings.resultDiv.text(text);
      return false;
    }
     };
     
     
var Actual = $.extend({}, settings, options );

     var moduleClick = function(){
   
     var anchors = Actual.mainDiv.children('a');

      $.each( anchors, function( index, element){
        $(this).click(function(e){
          e.preventDefault();
          Actual.clickAnchor($(element));
        })
      });
      
      

     }
      
     return{
       init: function(){
         
         moduleClick();
       }
     };
    }();
    
    $(document).ready(function(){
      Theme.init();
    })
    

Mobile multilevel accordion type dropdown navigations

var MobileNavs = function(){
  
    function mobileNavDisplay(){
      
      var $mobileBtnTrigger = $('.mob-nav-icon');
      var $mobileNavContainer = $('#mobNav');
      var $dropdownLinks = $mobileNavContainer.children('ul.nav').find('li.has--dropdown');
      
      $mobileBtnTrigger.on('click',function(){
      $('body').toggleClass('mob-nav-open');
      
      });
      
      $.each($dropdownLinks,function(index,element){
      
        var $droplistItems = $(element);
        $droplistItems.on('click',function(e){
        
          $(this).toggleClass('has--dropdown-open');
          e.stopPropagation();
          
          // Remove the dropdown open class from all sibling li element
          // when children ul is visible
          
          var $dropdown_ul = $(element).children('.dropdown--menus');
          
          if( $dropdown_ul.is(':visible')){
            $(element).siblings().removeClass('has--dropdown-open');
          }
        
        });
        
        //Remove the href redirection on the Parent li anchors
        
        var this_anchors = $droplistItems.children('a');
          this_anchors.click(function(e){
            e.preventDefault();
            
          });
      
      });
      
      
    };
    
    enquire.register("screen and (max-width:991px)",{
    
      match:function(){
      
      mobileNavDisplay();
      }
      
    });
  
  };
  

Get the Position Get the Bounding Rectangle in jQuery

var Panel = $('.panel');
								
								function offset(elem) {
								    var box = elem.getBoundingClientRect();

									  return {
									    top: box.top + pageYOffset,
									    left: box.left + pageXOffset
									  };

								    
								   
								    
								}


								for(var i = 0; i < Panel.length; i++){
															

									var ele = Panel[i];
									var Eloffset  = offset(ele);
									var b = {
										'index':i,
										'left': Eloffset.left,
										'top':Eloffset.top
										
									}
									console.log(b);


								}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment