/ Gists / JavaScript

Gists - JavaScript

On gists

Colorpicker + event

JavaScript

ex.html #

<body>
	<input type="color" id="color" value="#c1e0ff" />
</body>


<script>

const color = document.querySelector('#color')
const div = document.body

color.addEventListener('input', () => {
	div.style.backgroundColor = color.value
})

color.dispatchEvent(new Event('input'));

</script>

On gists

Function object with inside small functions

JavaScript-OOP JavaScript

example.js #

var Wrapper = (function () {
	this.A = () => {
		console.log('A');
	}
	this.B = () => {
		console.log('B');
	}
	
	return {
		A2: this.A,
		B2: this.B
	}

	// or return this
})();


Wrapper.B2(); // B

On gists

native js + trigger event

JavaScript

event.js #

const e = new Event('change')
const element = document.querySelector('#' + this.fakeFileId)
element.dispatchEvent(e)

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>