* * *

| Url | https://templates.webcoredev.webcore.app/snippets-js-en/ |
| --- | --- |
| MetaTitle | JS Snippets - JS Snippets |
| --- | --- |
| MetaDescription | JS Snippets |
| --- | --- |

- ## Flickity

    - Add Flickity Navigation on Custom position

	
[Demo](https://codepen.io/LLE-MUM/pen/yLXgvmY)


Show CodeHide Code

	
`
			var flkty = new Flickity('.packages-slider', {  // options  imagesLoaded: true,  lazyLoad: 1,  pageDots: false,  cellAlign: 'left',  prevNextButtons: false});$(".slide-next").on("click", function () {    flkty.next();});$(".slide-prev").on("click", function () {    flkty.previous();});
		`
    - Disable carousel if single image

		
check how many "carousel-cell" there are. If there is only one image, doesnt call the flickity script and add a "src"

	
Demo


Show CodeHide Code

	
`
			$('.entry-carousel').each(function () {    cellCount = $(this).find('div.carousel-cell').length;    if (cellCount > 1) {        $(this).addClass("multiple-images");    } else {        $(this).addClass("single-image");        $(this).find('.carousel-cell-image').each(function () {            imgUrl = $(this).attr('data-flickity-lazyload');            $(this).attr("src", imgUrl);        });    }});
		`
    - Flickity Custom Drag Cursor

		
Custom drag cursor animation

	
[Demo](https://codepen.io/LLE-MUM/pen/QWPprRq)


Show CodeHide Code

	
`
			
		`
		
            
[zip Flickity Custom Drag Cursor](/files/16181.zip)
    - Infinity logo slider(s)\*

		
Flickity infinity logo slider  
  
\*"pure" css alternative https://codepen.io/IrtezaAsad/pen/bGOLLvm

	
Demo


Show CodeHide Code

	
`
			// speed of tickerlet tickerSpeed = 2;let flickity = null;let isPaused = false;const slideshowEl = document.querySelector('.logoslider');// functionsconst update = () => {    if (isPaused) return;    if (flickity.slides) {        flickity.x = (flickity.x - tickerSpeed) % flickity.slideableWidth;        flickity.selectedIndex = flickity.dragEndRestingSelect();        flickity.updateSelectedSlide();        flickity.settle(flickity.x);    }    window.requestAnimationFrame(update);};const pause = () => {    isPaused = true;};const play = () => {    if (isPaused) {        isPaused = false;        window.requestAnimationFrame(update);    }};// create flickity instanceflickity = new Flickity(slideshowEl, {	autoPlay: false,	pageDots: false,	draggable: true,	wrapAround: true,	cellSelector: '.carousel-cell',	prevNextButtons: false,	selectedAttraction: 0.015,	friction: 0.25});flickity.x = 0;// event listenersslideshowEl.addEventListener('mouseenter', pause, false);slideshowEl.addEventListener('focusin', pause, false);slideshowEl.addEventListener('mouseleave', play, false);slideshowEl.addEventListener('focusout', play, false);flickity.on('dragStart', () => {    isPaused = true;});// start tickerupdate();
		`
- ## Scroll related

    - "Color changing logo"

		
Change Body Class according to background Color of HTML Element to adapt SVG Color of fixed Logo on different Sections

	
[Demo](https://codepen.io/LLE-MUM/pen/bGRgMvo)


Show CodeHide Code

	
`
			$(window).scroll(function () {  var windowTop = Math.max($('body').scrollTop(), $('html').scrollTop());  $('section, nav, .stage, .mailform, .legalinfo, footer').each(function (index) {    if (windowTop > ($(this).position().top - 100)) { //customize according Logo      if ($(this).hasClass('white')) {        $('body').addClass('bg-white');      }      else {        $('body').removeClass('bg-white');      }    }  });}).scroll();
		`
    - Scroll to section

		
/!\ jQuery\_Full required

	
[Demo](https://codepen.io/LLE-MUM/pen/RwgKJoL)


Show CodeHide Code

	
`
			var headerheight = $("#header").outerHeight();$('.indicator-down').on('click', function (e) {  e.preventDefault();  $('html, body').animate({    scrollTop: $($(this).attr('href')).offset().top - headerheight  }, 400, 'swing');});
		`
    - Add visible class on Elements when in Viewport

	
Demo


Show CodeHide Code

	
`
			$.fn.isInViewport = function () {  var elementTop = $(this).offset().top;  var elementBottom = elementTop + $(this).outerHeight();  var viewportTop = $(window).scrollTop();  var viewportBottom = viewportTop + $(window).height();  return elementBottom > viewportTop && elementTop < viewportBottom;};$(window).on('resize scroll', function () {  $('.scroll-el').each(function () {    if ($(this).isInViewport()) {      $(this).addClass("visible");    }  });});
		`
    - Move one div faster to top on scroll when in viewport

		
Required Scripts: gsap.min.js and ScrollTrigger.min.js

	
Demo


Show CodeHide Code

	
`
			gsap.to(".parallax_scroll", {  yPercent: -40,  ease: "none",  scrollTrigger: {    trigger: ".highlights",    scrub: true  },});
		`
    - Smooth parallax Effect on Background Images

		
Required Scripts: gsap.min.js and ScrollTrigger.min.js

	
Demo


Show CodeHide Code

	
`
			gsap.utils.toArray(".grid-parallax .bg_image").forEach((section, i) => {  const heightDiff = section.offsetHeight - section.parentElement.offsetHeight;  gsap.fromTo(section, {    y: -heightDiff  }, {    scrollTrigger: {      trigger: section.parentElement,      scrub: true    },    y: 0,    ease: "none"  });});//Required CSS.grid-parallax {    position: relative;    overflow: hidden;//  height: Fixed Height or calculate height with JS    .bg_image {        width: 100%;
		`
    - Subnav items get "selected" when in viewport

	
[Demo](https://www.palm-ag.be/carriere/)


Show CodeHide Code

	
`
			$(document).ready(function () {    var topOffset = 100;    var bottomOffset = 300;    var anchorNavClass = "anchor-nav";    //is in vieport function    $.fn.isInViewport = function (topOffset = 0, bottomOffset = 0) {        var elementTop = $(this).offset().top;        var elementBottom = elementTop + $(this).outerHeight();        var viewportTop = $(window).scrollTop() + topOffset;        var viewportBottom = viewportTop + $(window).height() - bottomOffset;        return elementBottom > viewportTop && elementTop < viewportBottom;    };    //check if anchor parent is in viewport    $(window).on('load resize scroll', function () {        $('.anchor').each(function () {            var anchorname = $(this).attr('name');            var $parent = $(this).parent();            if ($parent.isInViewport(topOffset, bottomOffset)) {                var $anchorlink = $("." + anchorNavClass + " a[href='#" + anchorname + "']");                if (!$anchorlink.parent().hasClass("selected")) {                    $("." + anchorNavClass + " li").removeClass("selected");                    $anchorlink.parent().addClass("selected");                }            }        });    });	});
		`
- ## Forms

    - Change DOM Order of Input and Label

		
insert Label after input  
Check Input Values to Style Label accordingly

	
Demo


Show CodeHide Code

	
`
			$('.form-group label').each(function () {  $(this).insertAfter($(this).next('input, textarea'));});$('.form-group input, .form-group textarea').each(function () {  var val = $(this).val();  if (val) {    $(this).parent('.form-group').addClass('has-val');  }});$('body').on('change', '.form-group input, .form-group textarea', function () {  var val = $(this).val();  if (val) {    $(this).parent('.form-group').addClass('has-val');  }  else {    $(this).parent('.form-group').removeClass('has-val');  }});
		`
- ## Video

    - Prevent video from loading on Smartphones

		
Load video with data-src and transform to src when on Desktop device, use display: none in CSS to hide on Mobile devices

	
Demo


Show CodeHide Code

	
`
			$("video").each(function () {    var bgv = $(this);    //je récupère le check de taille de la video    if (bgv.is(':visible')) {        $('source', bgv).each(            function () {                var el = $(this);                el.attr('src', el.data('src'));            }        );        bgv[0].load();    }    var bgvDom = bgv.get(0);    bgvDom.addEventListener("playing", function () {        if (bgvDom.readyState == 4) {            bgvDom.classList.add("isloaded")        }    });    bgvDom.addEventListener("suspend", function (e) {        if (bgvDom.readyState == 4) {            bgvDom.classList.add("isloaded")        }    });});
		`
- ## Animations

    - Split string in 1-character-span and add incremental delay

		
vanilla js

	
Demo


Show CodeHide Code

	
`
			let toSplit = document.querySelector(".string-to-split")        splitAndClone(toSplit);        function splitAndClone(elem) {            var text = elem.textContent.split("");            var result = "";            var index = 0;            // Loop over the array            text.forEach(function (char) {                // Append a new span only if the current char is not a space                result += (char.trim() === "") ? " " : "" + cha
		`
- ## Layout

    - Main minimum height related to windows height

	
Demo


Show CodeHide Code

	
`
			var headerHeight = document.querySelector('header').offsetHeight;var footerHeight = document.querySelector('footer').offsetHeight;var viewHeight = window.innerHeight;var main = document.querySelector('main');main.style.minHeight = viewHeight - headerHeight - footerHeight +"px";
		`
- ## Other

    - WebCore Languages Drop Down

	
Demo


Show CodeHide Code

	
`
			"HTML"    <%=SiteRequest.Language.Code%>    JS('#languages .current').click(function () {    $(this).parent().toggleClass('show');});LESS#languages {    .transition;    display: inline-block;    color: white;    position: relative;    font-size: @font-size-smaller;    .current {        display: block;        background: transparent;        text-transform: uppercase;        padding: 10px 5px 10px 15px;        height: 40px;        width: 40px;        line-height: 20px;        cursor: pointer;        color: white;        background: @brand-primary;        position: relative;        .transition;        &:after, &:before {            position: absolute;            top: 50%;            left: 5px;            content: "";            width: 5px;            height: 1px;            background-color: white;            .transition;        }        &:after {            transform: rotate(-40deg);            left: 8px;        }        &:before {            transform: rotate(40deg);        }        &:hover {            background: black;        }    }    .languagelinks {        background: transparent;        text-align: center;        position: absolute;        top: 40px;        left: 0;        right: 0;        overflow: hidden;        max-height: 0;        z-index: 210;        .transition;        color: @text-color;        a {            width: 40px;            display: block;            color: white;            padding: 10px 5px;            height: 40px;            line-height: 20px;            text-transform: uppercase;            background-color: @brand-primary;            &:hover,            &:active,            &:focus {                color: @brand-secondary;            }            &.selected {                display: none;                color: @brand-primary;            }        }    }    &.show {        color: white;        z-index: 300;        .current {            &:after {                transform: rotate(40deg);            }            &:before {                transform: rotate(-40deg);            }        }        .languagelinks {            max-height: 80px;            a:hover {                background-color: black;                color: white;            }        }    }}
		`