URL parameter value with js / javascript

Get URL parameter using JavaScript?

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

Cute Hide (show/hide element)

Smooth hiddinig elements with js:

    function cuteHide(el) {
        el.animate({opacity: '0'}, 130, function(){
            el.animate({height: '0px'}, 130, function(){
            });
        });
    }

    function cuteUnhide(el) {
        el.animate({height: '100%'}, 130, function(){
            el.animate({opacity: '1'}, 130, function() {
            });
        });
    }
    function cuteRemove(el) {
        el.animate({opacity: '0'}, 150, function(){
            el.animate({height: '0px'}, 150, function(){
                el.remove();
            });
        });
    }

Cookie JS

Custom Cookie banner JS

function cookieBanner() {

	var dropCookie = true;                      // false disables the Cookie, allowing you to style the banner
	var cookieDuration = 14;                    // Number of days before the cookie expires, and the banner reappears
	var cookieName = 'complianceCookie';        // Name of our cookie
	var cookieValue = 'on';                     // Value of cookie

	function showBanner(){
		$('#cookie-banner').show('slow');
		
		$('#cookie-banner .cookie-banner_close').on('click', function() {
			$('#cookie-banner').hide('slow');
			createCookie(cookieName,cookieValue, cookieDuration); // Create the cookie
		})
	}
	
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000)); 
			var expires = "; expires="+date.toGMTString(); 
		}
		else var expires = "";
		if(dropCookie) { 
			document.cookie = name+"="+value+expires+"; path=/"; 
		}
	}
	
	function checkCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	window.onload = function(){
		if(checkCookie(cookieName) != cookieValue){
			showBanner(); 
		}
	}
}

Anchor link – Header offset

Anchor Link Offset to Other Pages with Fixed Header Size:

jQuery(document).ready(function($) {

  // set a variable for the anchor link which is the location.hash
  var anchorLink = $(window.location.hash);
    // test to see if the link is a anchor link, if not the length will have no value, this is done to avoid js errors on non anchor links
		if ( anchorLink.length ) {
      // set an element as the fixed entity, header in this case and get its height
			var offsetSize = $("header").innerHeight();
      // fire the animation from the top of the page to the anchor link offsetting by the fixed elements height, the number is the speed of the animation
			$("html, body").animate({scrollTop: anchorLink.offset().top - offsetSize }, 500);
    }

});

Google Analytics – GDPR

Adding Google Anyltics code and adding option to disable it:

   <!-- Google Analytics -->
    <script async src='//www.google-analytics.com/analytics.js'></script>
    <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-xxxxxx-x', 'auto');
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');
    </script>
    <!-- End Google Analytics -->


    //HTML LINK
    <a class="ga-disable" href="#">Link</a>
    <a href="javascript:gaOptout()">Link</a>


    // Set to the same value as the web property used on the site
    var gaProperty = 'UA-xxxxxx-x';
    // Disable tracking if the opt-out cookie exists.
    var disableStr = 'ga-disable-' + gaProperty;
    if (document.cookie.indexOf(disableStr + '=true') > -1) {
        window[disableStr] = true;
    }
    // Opt-out function
    function gaOptout() {
        document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
        window[disableStr] = true;
        alert('Das Tracking durch Google Analytics wurde in Ihrem Browser für diese Website deaktiviert.');
    }




    jQuery(document).ready(function($) {
        $(".ga-disable").click(function(event) {
            event.preventDefault();
            gaOptout();
        });
    });

Explode text to repeater (ACF)

Explode text by “,” and add to fields (ACF repeater) -> VIVI.si recepti:

    $('#explode_recepti').click(function(){

        var items = $('#explode_recepti_textarea').val().split(',').length;
        var itemsArray = $('#explode_recepti_textarea').val().split(',');

        for(i=0;i<items;i++){
            $('.acf-field-54dbe3014c9ae .acf-actions .acf-button ').click();
        }

        $('.acf-field-54dbe3014c9ae .acf-table .acf-field-text input').each(function( index , element) {
            
            $(this).val(itemsArray[index]);
        });

    });

Internal anchor smooth scroll

Internal URL smooth scroll from menu – anchor link:

        $("a[href*=#]:not([href=#])").click(function() {
            var kliknjeno = $(this);

            var calapse_mobile = kliknjeno.parent().parent().parent().parent();

            if (calapse_mobile.hasClass('collapse')) {
                calapse_mobile.collapse('hide');
            }

            if (!kliknjeno.hasClass( "nohref" )) {
                if (location.pathname.replace(/^\//, "") == this.pathname.replace(/^\//, "") && location.hostname == this.hostname) {
                    var a = $(this.hash);
                    if (a = a.length ? a : $("[name=" + this.hash.slice(1) + "]"), a.length) return $("html,body").animate({
                        scrollTop: a.offset().top - 30
                    }, 1000), !1
                }
            }

        })

Menu Dropdown / Submenu

Open Submenu:

    $('ul.desktop_menu li.menu-item-has-children').hover(function() {
        $(this).find('.sub-menu').stop(true, true).delay(100).fadeIn(200);
    }, function() {
        $(this).find('.sub-menu').stop(true, true).delay(100).fadeOut(200);
    });


    //WPML switcher
    $('ul.wpml_switch li.dropdown').hover(function() {
        $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn(200);
    }, function() {
        $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut(200);
    });

Sticky Header Scroll

Sticky Header on Scroll

    var showHeaderAt = 300;

    var win = $(window);
    var body = $('body');

    var sticky_visible = false;

    win.on('scroll', function(){

        if(win.scrollTop() > showHeaderAt) {

            if (sticky_visible == false) {
                body.addClass('header-stuck');
                setTimeout(function() {
                    body.addClass('fixed_active');
                }, 100);
                sticky_visible = true;
            }
        }
        else if (sticky_visible == true) {
            body.removeClass('fixed_active');
            body.removeClass('header-stuck');
            sticky_visible = false;
        }

    });

To Top Button

Scroll to top Button

    if ($('#back-to-top').length) {
        var scrollTrigger = 300, // px
            backToTop = function () {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > scrollTrigger) {
                    $('#back-to-top').addClass('show');
                } else {
                    $('#back-to-top').removeClass('show');
                }
            };
        backToTop();
        $(window).on('scroll', function () {
            backToTop();
        });
        $('#back-to-top').on('click', function (e) {
            e.preventDefault();
            $('html,body').animate({
                scrollTop: 0
            }, 700);
        });
    }

Check if is Internet Explorer

Checking if is Internet Explorer and run some function:

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    var logo_img = $('.logoslider .single-clients img');

    if (navigator.appName == 'Microsoft Internet Explorer' ||  !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {

        set_height_ie();

        $(window).resize(function() {
            set_height_ie();
        });

        function set_height_ie() {
            logo_img_sirina = logo_img.width();
            logo_img.height(logo_img_sirina);
        }
    } 

Replace SVG to inline

Replace image SVG to inline SVG

    $('img.svg').each(function(){
        var $img = jQuery(this);
        var imgID = $img.attr('id');
        var imgClass = $img.attr('class');
        var imgURL = $img.attr('src');

        jQuery.get(imgURL, function(data) {
            // Get the SVG tag, ignore the rest
            var $svg = jQuery(data).find('svg');

            // Add replaced image's ID to the new SVG
            if(typeof imgID !== 'undefined') {
                $svg = $svg.attr('id', imgID);
            }
            // Add replaced image's classes to the new SVG
            if(typeof imgClass !== 'undefined') {
                $svg = $svg.attr('class', imgClass+' replaced-svg');
            }

            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Check if the viewport is set, if the viewport is not set the SVG wont't scale.
            if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
                $svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
            }

            // Replace image with new SVG
            $img.replaceWith($svg);

        }, 'xml');
    });

Google analytics – tracking

Include the Google Analytics Tracking Code (ga.js) – HEADER

<script async src='https://www.googletagmanager.com/gtag/js?id=UA-40742215-1'></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){
        dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', 'UA-000000-1', { 'anonymize_ip': true });
</script>