/ Gists / jQuery

Gists - jQuery

On gists

Close on document, but not on this element.

jQuery Helpers-Filters-Plugins

on-document-click-close.js #

    $(document).on('click', function(e){

    	if ($(e.target).closest('.user-sign-in-form').length === 0) 
    	{
       		$('.user-sign-in-form').fadeToggle();
    	}

    });

On gists

Jquery - replace tag with another

jQuery Helpers-Filters-Plugins

replace-tag-by-another.js #

$('li').replaceWith(function(){
  return $("<div />").append($(this).contents());
});

On gists

Stay on top

jQuery

fixed-nav-stay-on-top.js #

$(function(){
	var $win = $(window)
	var $nav = $('.mytoolbar');
	var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top;
	var isFixed=0;
 
	processScroll()
	$win.on('scroll', processScroll)
 
	function processScroll() {
	var i, scrollTop = $win.scrollTop()
 
	if (scrollTop >= navTop && !isFixed) { 
		isFixed = 1
		$nav.addClass('subnav-fixed')
	} else if (scrollTop <= navTop && isFixed) {
		isFixed = 0
 		$nav.removeClass('subnav-fixed')
	}
}

On gists

Move between two select

JavaScript jQuery

move.html #

<select id="from" style="float: left; width: 200px;" multiple>
	
	<option value="1">AA</option>
	<option value="2">BB</option>
	<option value="3">CC</option>
	<option value="4">DD</option>
	<option value="5">EE</option>

</select>

<button style="float: left; margin-left: 10px; margin-right: 10px;" id="a">&gt;</button>
<button style="float: left; margin-left: 10px; margin-right: 10px;" id="b">&lt;</button>
<select id="to" style="float: left;  width: 200px;" multiple></select>




<script>
	var $from = $("#from");
	var $to = $("#to");


	$("#a").click(function(){

		moveOptions($from, $to);
	});	

	$("#b").click(function(){

		moveOptions($to, $from);

	});


	function moveOptions(from, to)
	{
		$("option:selected", from).appendTo(to);
		var x = $("#from option").sort(function(a, b){

			a = a.value;
			b = b.value;

			return a-b;
		});	



		var y = $("#to option").sort(function(a, b){

			a = a.value;
			b = b.value;

			return a-b;
		});


		$("#from").html(x);
		$("#to").html(y);
	}

</script>

On gists

Use event with function and data // ukazka pouziti eventu, funkce, data

JavaScript jQuery

use-events-with-data.js #

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>TEST</title>
	<script src="jquery.js"></script>
	<style>
	


	</style>
</head>
<body>




<div id="result"></div>


<button id="button1" data-color="red">Červené</button>
<button id="button2" data-color="green">Zelené</button>




<script>

//------------------------------------------------------------
//1 zpusob - data atribut
$('button').on('click', function(){

	$("#result").text($(this).text()).css("color", $(this).data('color'));
});




//------------------------------------------------------------
//2 zpusob - vlastni funkci
var handler = function(text, color) {

	$("#result").text(text).css("color", color);
};

$('#button1').on('click', function(){
	handler('Červené', 'red'); // misto Červené muzu pouzit $(this).text(), ale demonstruji ukazku parametru viz dale
});

$('#button2').on('click', function(){
	handler('Zelené', 'green'); // misto Červené muzu pouzit $(this).text(), ale demonstruji ukazku parametru viz dale
});


//------------------------------------------------------------
//3 zpusob - vlastni funkci ale ne pomoci anonymni, ale trosku ugly
var handler = function(text, color) {

	return function() {

		$("#result").text(text).css("color", color);
	}
};

$('#button1').on('click', handler('Červené', 'red'));
$('#button2').on('click', handler('Zelené', 'green'));


//------------------------------------------------------------
//4 zpusob pres user data / bindovani / trigger
$("button").on("setColor", function(e, color, txt){

	$("#result").text(txt).css("color", color);

});

$("#button1").on("click", function(){

	$(this).trigger("setColor", ['red', 'Červené']);
});

$("#button2").on("click", function(){

	$(this).trigger("setColor", ['green', 'Zelené']);
});



//------------------------------------------------------------
//5 event data
var handler = function(e) {
	
	$("#result").text(e.data.text).css("color", e.data.color);
	
};

$("#button1").on("click", {text:'Červené', color:'red'}, handler);
$("#button2").on("click", {text:'Zelené', color:'green'}, handler);



//------------------------------------------------------------
// 6 event, ale ne v data ale rovnou do e.nazev
$("#button1").on("click", function(e){
	$("#result").text(e.text).css("color", e.color);
});

$("#button1").trigger({type:'click', text:'Červené', color:'red'});




//------------------------------------------------------------
// 7 $.event object, vlastni data soucasti eventu, @link: https://jsbin.com/memoriyate/edit?html,js


$('body').on('logged logged2', function(e) {

	console.log(e);
});

// 1 moznost
var event = jQuery.Event( "logged" );
event.user1 = "a";
event.pass1 = "b";
$( "body" ).trigger( event );

// 2 moznost
$( "body" ).trigger({
  type:"logged2",
  user:"a2",
  pass:"b2"
});



</script>

</body>
</html>

On gists

Get the share counts from various APIs

jQuery

gistfile1.md #

Share Counts

I have always struggled with getting all the various share buttons from Facebook, Twitter, Google Plus, Pinterest, etc to align correctly and to not look like a tacky explosion of buttons. Seeing a number of sites rolling their own share buttons with counts, for example The Next Web I decided to look into the various APIs on how to simply return the share count.

If you want to roll up all of these into a single jQuery plugin check out Sharrre

Many of these API calls and methods are undocumented, so anticipate that they will change in the future. Also, if you are planning on rolling these out across a site I would recommend creating a simple endpoint that periodically caches results from all of the APIs so that you are not overloading the services will requests.

Twitter

GET URL:

http://cdn.api.twitter.com/1/urls/count.json?url=http://stylehatch.co

Returns:

{
    "count":528,
    "url":"http://stylehatch.co/"
}

Facebook

GET URL:

http://graph.facebook.com/?id=http://stylehatch.co

Returns:

{
   "id": "http://stylehatch.co",
   "shares": 61
}

Pinterest

GET URL:

http://api.pinterest.com/v1/urls/count.json?callback=&url=http://stylehatch.co

Result:

({"count": 0, "url": "http://stylehatch.co"})

LinkedIn

GET URL:

http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json

Returns:

{
    "count":17,
    "fCnt":"17",
    "fCntPlusOne":"18",
    "url":"http:\/\/stylehatch.co"
}

Google Plus

POST URL:

https://clients6.google.com/rpc?key=YOUR_API_KEY

POST body:

[{
    "method":"pos.plusones.get",
    "id":"p",
    "params":{
        "nolog":true,
        "id":"http://stylehatch.co/",
        "source":"widget",
        "userId":"@viewer",
        "groupId":"@self"
        },
    "jsonrpc":"2.0",
    "key":"p",
    "apiVersion":"v1"
}]

Returns


[{
    "result": { 
        "kind": "pos#plusones", 
        "id": "http://stylehatch.co/", 
        "isSetByViewer": false, 
        "metadata": {
            "type": "URL", 
            "globalCounts": {
                "count": 3097.0
            }
        }
    } ,
    "id": "p"
}]

StumbledUpon

GET URL:

http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://stylehatch.co

Result:


{
    "result":{
        "url":"http:\/\/stylehatch.co\/",
        "in_index":true,
        "publicid":"1iOLcK",
        "views":39,
        "title":"Style Hatch - Hand Crafted Digital Goods",
        "thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/941\/72725941.jpg",
        "thumbnail_b":"http:\/\/cdn.stumble-upon.com\/bthumb\/941\/72725941.jpg",
        "submit_link":"http:\/\/www.stumbleupon.com\/submit\/?url=http:\/\/stylehatch.co\/",
        "badge_link":"http:\/\/www.stumbleupon.com\/badge\/?url=http:\/\/stylehatch.co\/",
        "info_link":"http:\/\/www.stumbleupon.com\/url\/stylehatch.co\/"
    },
    "timestamp":1336520555,
    "success":true
}

On gists

Caret

jQuery

jquery.caret.js #

// Set caret position easily in jQuery
// Written by and Copyright of Luke Morton, 2011
// Licensed under MIT
(function ($) {
    // Behind the scenes method deals with browser
    // idiosyncrasies and such
    $.caretTo = function (el, index) {
        if (el.createTextRange) { 
            var range = el.createTextRange(); 
            range.move("character", index); 
            range.select(); 
        } else if (el.selectionStart != null) { 
            el.focus(); 
            el.setSelectionRange(index, index); 
        }
    };

    // The following methods are queued under fx for more
    // flexibility when combining with $.fn.delay() and
    // jQuery effects.

    // Set caret to a particular index
    $.fn.caretTo = function (index, offset) {
        return this.queue(function (next) {
            if (isNaN(index)) {
                var i = $(this).val().indexOf(index);
                
                if (offset === true) {
                    i += index.length;
                } else if (offset) {
                    i += offset;
                }
                
                $.caretTo(this, i);
            } else {
                $.caretTo(this, index);
            }
            
            next();
        });
    };

    // Set caret to beginning of an element
    $.fn.caretToStart = function () {
        return this.caretTo(0);
    };

    // Set caret to the end of an element
    $.fn.caretToEnd = function () {
        return this.queue(function (next) {
            $.caretTo(this, $(this).val().length);
            next();
        });
    };
}(jQuery));

On gists

HTML seznam do selectboxu (např. pro responsivní navigaci)

jQuery

ordered-list-2-selectbox.js #

$(function(){

    var select = $("select");
    $("nav a").each(function(){
        
        var $this = $(this);
        var text = $this.text();  
        var level = $this.parents("ul").length;
        var indent = '';
        if (level > 1)
        {
            indent = str_repeat("\u2013", level);
        }
        select.append('<option>'+indent + text+'</option>');
    
    
    });   



});



function str_repeat (input, multiplier) {
  // http://kevin.vanzonneveld.net
  // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // +   improved by: Ian Carter (http://euona.com/)
  // *     example 1: str_repeat('-=', 10);
  // *     returns 1: '-=-=-=-=-=-=-=-=-=-='

  var y = '';
  while (true) {
    if (multiplier & 1) {
      y += input;
    }
    multiplier >>= 1;
    if (multiplier) {
      input += input;
    }
    else {
      break;
    }
  }
  return y;
}

On gists

Ajaxové načítaní při onscrollu

jQuery

LoadNext-Onscroll.js #

    if($('.load-next').length > 0) {

        var $window = $(window);

        $(window).scroll(function(){

            var $loadNext = $('.load-next');

            if($loadNext.length) {

                var winHeight = $window.height();
                var scrollTop  = $window.scrollTop();
                var loadNextOffset = $loadNext.offset();

                if((winHeight + scrollTop + 200) > loadNextOffset.top) {
                    $loadNext.trigger('click').remove();
                }

            }


        });

    }

On gists

Toogle input value -- better than placeholder (browser support)

jQuery

toggle input value.js #

$.fn.toggleInputValue = function(){
    return $(this).each(function(){
		var input        = $(this);
		var defaultValue = input.val();

        input.focus(function() {
           if(input.val() == defaultValue) input.val("");
        }).blur(function(){
            if(input.val().length == 0) input.val(defaultValue);
        });
    });
}