/ Gists / JavaScript

Gists - JavaScript

On gists

Remove object from array of objects in Javascript

JavaScript

splice-object-array.js #

// source: http://stackoverflow.com/questions/16491758/remove-objects-from-array-by-object-property

// we have an array of objects, we want to remove one object using only the id property
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object
apps.splice(removeIndex, 1);

On gists

JS: patterns Singleton

JavaScript-OOP JavaScript Plugin patterns

singleton.js #

var mySingleton = (function () {

    // Instance stores a reference to the Singleton
    var instance;

    function init() {

        // Singleton

        // Private methods and variables
        function privateMethod(){
            console.log( "I am private" );
        }

        var privateVariable = "Im also private";

        return {

            // Public methods and variables
            publicMethod: function () {
                console.log( "The public can see me!" );
            },

            publicProperty: "I am also public"
        };
    }

    return {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function () {

        if ( !instance ) {
            instance = init();
        }

        return instance;
    }

    };

})();

On gists

Hook system

JavaScript

head.latte #

<html>
<head>
.
.
.

<script>
       var Hook = 
            {
                hooks: [],
                
                register: function ( name, callback ) {
                    if( 'undefined' == typeof( Hook.hooks[name] ) )
                        Hook.hooks[name] = [];
                    
                    Hook.hooks[name].push( callback )
                },
                
                call: function ( name, arguments ) {
                    if( 'undefined' != typeof( Hook.hooks[name] ) )
                    {
                        for( i = 0; i < Hook.hooks[name].length; ++i )
                            if( true != Hook.hooks[name][i]( arguments ) ) { break; }
                    }

                }
            }
   </script>         
            
  </head>

On gists

Nette toggle - JS

Nette JavaScript

toggle.js #

// @link: https://forum.nette.org/cs/32804-vyvolani-toggle-pri-zavreni-bootstrap-datepicker

$(':text[data-provide="datepicker"]').datepicker({
	language: 'cs'
})
.on('hide', function(e) {
	// `e` here contains the extra attributes
	var defaultValue = e.currentTarget.defaultValue;
	var value = e.currentTarget.value;

	if(defaultValue == value) {
		Nette.toggle('submit-container', false);
	} else {
		Nette.toggle('submit-container', true);
	}
});

On gists

Iframe - autoheight

JavaScript

iframe-autoheight.js #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    

</head>
<body>
    
    <h1>test iframu</h1>
    <iframe onload="resizeIframe(this)" src="http://localhost/xxx/b.php" frameborder="1"></iframe>


    <script type="text/javascript">
        function resizeIframe(iframe) {
          iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        }
    </script>
</body>
</html>

On gists

Youtube Iframe API - player

JavaScript Youtube API

example.js #

var player,
    time_update_interval = 0;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        width: 600,
        height: 400,
        videoId: 'Xa0Q0J5tOP0',
        playerVars: {
            color: 'white',
            playlist: 'taJ60kskkns,FG0fTKAqZ5g'
        },
        events: {
            onReady: initialize
        }
    });
}

function initialize(){

    // Update the controls on load
    updateTimerDisplay();
    updateProgressBar();

    // Clear any old interval.
    clearInterval(time_update_interval);

    // Start interval to update elapsed time display and
    // the elapsed part of the progress bar every second.
    time_update_interval = setInterval(function () {
        updateTimerDisplay();
        updateProgressBar();
    }, 1000);


    $('#volume-input').val(Math.round(player.getVolume()));
}


// This function is called by initialize()
function updateTimerDisplay(){
    // Update current time text display.
    $('#current-time').text(formatTime( player.getCurrentTime() ));
    $('#duration').text(formatTime( player.getDuration() ));
}


// This function is called by initialize()
function updateProgressBar(){
    // Update the value of our progress bar accordingly.
    $('#progress-bar').val((player.getCurrentTime() / player.getDuration()) * 100);
}


// Progress bar

$('#progress-bar').on('mouseup touchend', function (e) {

    // Calculate the new time for the video.
    // new time in seconds = total duration in seconds * ( value of range input / 100 )
    var newTime = player.getDuration() * (e.target.value / 100);

    // Skip video to new time.
    player.seekTo(newTime);

});


// Playback

$('#play').on('click', function () {
    player.playVideo();
});


$('#pause').on('click', function () {
    player.pauseVideo();
});


// Sound volume


$('#mute-toggle').on('click', function() {
    var mute_toggle = $(this);

    if(player.isMuted()){
        player.unMute();
        mute_toggle.text('volume_up');
    }
    else{
        player.mute();
        mute_toggle.text('volume_off');
    }
});

$('#volume-input').on('change', function () {
    player.setVolume($(this).val());
});


// Other options


$('#speed').on('change', function () {
    player.setPlaybackRate($(this).val());
});

$('#quality').on('change', function () {
    player.setPlaybackQuality($(this).val());
});


// Playlist

$('#next').on('click', function () {
    player.nextVideo()
});

$('#prev').on('click', function () {
    player.previousVideo()
});


// Load video

$('.thumbnail').on('click', function () {

    var url = $(this).attr('data-video-id');

    player.cueVideoById(url);

});


// Helper Functions

function formatTime(time){
    time = Math.round(time);

    var minutes = Math.floor(time / 60),
        seconds = time - minutes * 60;

    seconds = seconds < 10 ? '0' + seconds : seconds;

    return minutes + ":" + seconds;
}


$('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
});

On gists

Jsonp, json, js to html from another domain

JavaScript jQuery JSON

index.html #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>

    <!-- https://www.sitepoint.com/jsonp-examples/ -->

    <div style="background: goldenrod; padding: 1rem;">
        <script src="http://lab.rjwebdesign.cz/jsonp/js.php"></script>
    </div>

    <div style="background: burlywood; padding: 1rem;" id="jsonp">
    
    </div>
    <script>
   
        // 1 zpusob
        $.getJSON('http://lab.rjwebdesign.cz/jsonp/jsonp.php?callback=?', function(json){
            console.log(json);
        });

        // 2 zpusob
        function logResults(json) {
            console.log(json);
        }

        $.ajax({
        url: "http://lab.rjwebdesign.cz/jsonp/jsonp.php",
        dataType: "jsonp",
        jsonpCallback: "logResults"
        });
    </script>

</body>
</html>

On gists

Document, element, outside click, propagation

JavaScript jQuery

example.js #

// 1
$(document).click(function(e){

   if($(e.target).closest('#dropdownID').length != 0) return false;
   $('#dropdownID').hide();
});


// 2
$('body').click(function(e) {
    if ($(e.target).closest('.notification-container').length === 0) {
        // close/animate your div
    }
});


//3, https://www.tutorialrepublic.com/faq/hide-dropdown-menu-on-click-outside-of-the-element-in-jquery.php
$(document).ready(function(){
        // Show hide popover
        $(".dropdown").click(function(){
            $(this).find(".dropdown-menu").slideToggle("fast");
        });
    });
    $(document).on("click", function(event){
        var $trigger = $(".dropdown");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $(".dropdown-menu").slideUp("fast");
        }            
    });

// 4, http://benalman.com/projects/jquery-outside-events-plugin/
$(document).ready(function(){
    $(".notification-button").click(function(){
        $('.notification-container').toggle().animate({"margin-top":"0px"}, 75); 
    }); 

    $('.notification-wrapper').bind('clickoutside', function (event) {
        $('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
    });
});

On gists

JS / jQuery: Caching selectors

JavaScript

caching.js #

function Selector_Cache() {
    var collection = {};
    function get_from_cache( selector ) {
        if ( undefined === collection[ selector ] ) {
            collection[ selector ] = $( selector );
        }
        return collection[ selector ];
    }
    return { get: get_from_cache };
}

var selectors = new Selector_Cache();

// Usage $( '#element' ) becomes
selectors.get( '#element' );

On gists

JS - round, floor, ceil obj - Decimal precision

JavaScript-OOP JavaScript

decimalperecision.js #

var DecimalPrecision = (function(){
	if (Number.EPSILON === undefined) {
		Number.EPSILON = Math.pow(2, -52);
	}
	this.round = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.round((n + r) * o) / o;
	}
	this.ceil = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.ceil((n + r) * o) / o;
	}
	this.floor = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.floor((n + r) * o) / o;
	}
	return this;
})();