Lots of useful functions in Javascript
// JavaScript Document
//00##### $.getUrlParameter
//01##### $.getUrlVars()
//02##### $.abre_foto_nova_janela(url_img,img_base,img_altu,titulo) | Abre uma imagem em uma nova janela
//03##### $.preload() | Images Pré carrega as imagens do site
//04##### $.insere_camada(nome da janela) | Insere uma camada transparente sobre a interface.
//04.5### $.aviso(texto) | Insere uma DIV com a classe .aviso e inclui um html dentro, podendo ser model ou não[padrão]
//05##### $.edita_imagem(imagem id) | Permite editar a imagem ELEMENTO sobre uma camada transparente (insere camada) sobre a interface.
//06##### $.fn.extend = function(elemento, folha_de_estilos) | Troca a folha de Estilos Específica
//07##### $.include("path/arquivo.js"); | Inclui o arquivo JS dinamicamente
//08##### $.include_once("path/arquivo.js"); | Inclui o arquivo JS dinamicamente evitando Redundancia
//09##### $.link_para_topo() | Acrescenta o Link Flutuante para o TOPO em páginas muito compridas
//10##### $.destaques() | Destaca o Texto entre span.destaque - Gera dinamicamente uma caixa flutuante com texto EM DESTAQUE, após o parágrafo atual, com o texto dentro da tag < span class="destaque"> texto < / span>;
//11##### $.random_topo() | Carrega uma imagem aleatória, dentro das pre-estipuladas, no topo do site
//12##### $.rwdTest() | Muda o tamanho do Container de acordo com o tamanho desejado e adiciona um fundo com medidas
//13##### $.fn.fade1by1 | Carrega os elementos um por um com o efeito de fade
//14##### $.fn.AJAXSTART
//15##### function loadCSS(url)
//16##### function include(file_path)
//17##### $.floatLink = function($divId = "link_new_location", $divClass = "floating-link", $aHref = "../core/new_location.php", $aTitle = "New Location", $imgSrc = "../images/new_location.png")
//00 $.getUrlParameter = function(sParam)
$.getUrlParameter = function(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
//01 getUrlVars
// http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
// http://css-tricks.com/snippets/javascript/get-url-variables/
$.getUrlVars = function()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//02 Abre uma imagem em uma nova janela
$.abre_foto_nova_janela = function (url_img,img_base,img_altu,titulo)
{
var px = (screen.availWidth/2)-(img_base/2) ;
var py = (screen.availHeight/2)-(img_altu/2);
var jscript_parametros = 'height='+img_altu+'; width='+img_base+'; top='+py+'; left='+px+'; menubar=no; location=no; resizeable=no; scrollbars=no; statusbar=no; toolbar=no; titlebar=no';
var jan = window.open('','janela',jscript_parametros);
jan.document.write('<html><head><title>'+titulo+'</title></head><body leftmargin="0" topmargin="0"><a href="javascript:this.close();" target="_self"><img border="0" src="' + url_img + '" alt="" title=""></a></body></html>');
jan.focus();
}
//03 Pré carrega as imagens do site
$.preloadImages = function()
{
for(var i = 0; i<arguments.length; i++)
{
$("<img />").attr("src", arguments[i]);
}
}
//04 Insere uma camada transparente sobre a interface.
$.insere_camada = function(parametros)
{
var config = {
'nomejanela':'janela_modal'
};
if(parametros)
{
config.nomejanela = parametros;
}
var docHeight = $(document).height();
$("body")
.append("<div id='janela_modal' style='display:none;'><div id='overlay'></div></div>")
.find("#janela_modal")
.height(docHeight)
.css({
'position': 'absolute',
'top': 0,
'left': 0,
'width': '100%',
'z-index': 5000
})
.find('#overlay')
.on('click',function()
{
$(this)
.parent()
.fadeOut('slow', function(){
$(this).remove();
});
})
.height(docHeight)
.css({
'position': 'absolute',
'top': 0,
'left': 0,
'width': '100%',
'z-index': -100,
'background-color': 'black'
})
.addClass('transparente')
.end()
.fadeIn('slow')
.append($(config.nomejanela))
.find(config.nomejanela)
.show();
console.log(config.nomejanela);
}
//04.5 Insere uma DIV com a classe .aviso e inclui um html dentro, podendo ser model ou não[padrão]
$.aviso = function(arg){
$("#container_principal").append('<span class="aviso">'+arg+'</span>');
}
//04.5 Insere uma DIV com a classe .importante e inclui um htl dentro, podendo ser model ou não[padrão]
$.importante = function(arg){
$("#container_principal").append('<span class="importante">'+arg+'</span>').find('.importante').on('click',function()
{
$elemento = $(this)
$elemento.fadeOut(function(){
$elemento.remove();
});
});
}
// TODO: $.galeria de imagens - http://codepen.io/kaioe/details/kaCrm
//05 Permite editar a imagem ELEMENTO sobre uma camada transparente (insere camada) sobre a interface.
$.edita_imagem = function(elemento)
{
if(elemento.is('IMG')){
$(elemento).css(
{
'height':'',
'width':''
});
var topo = '2em';
var esquerda = parseInt((window.innerWidth/2)-(($(elemento).css('width').replace('px',''))/2));
$.insere_camada('janela_modal');
$('html, body').animate({ scrollTop: 0 }, 'slow');
$(elemento)
.clone()
.appendTo('#janela_modal')
.css(
{
'position':'absolute',
'top':topo+'px',
'left':esquerda+'px',
'height':'',
'width':'',
'max-height':'80%'
})
.end()
.css(
{
'height':'100%'
});
}
}
//06 Troca a folha de Estilos Específica
$.fn.extend = function(elemento, folha_de_estilos)
{
// link = $(elemento);
// link.attr('href', folha_de_estilos);
}
//07 Inclui o arquivo JS dinamicamente
$.include = function(file_path)
{
var j = document.createElement("script"); /* criando um elemento script: <script></script> */
j.type = "text/javascript"; /* informando o type como text/javacript: <script type="text/javascript"></script>*/
j.src = file_path; /* Inserindo um src com o valor do parâmetro file_path: <script type="javascript" src="+file_path+"></script>*/
if(document.getElementsByTagName("head")[0].appendChild(j))
{ /* Inserindo o seu elemento(no caso o j) como filho(child) do HEAD: <html><head><script type="javascript" src="+file_path+"></script></head></html> */
return true;
}
}
//08 Inclui o arquivo JS dinamicamente evitando Redundancia
$.include_once = function(file_path)
{
var sc = document.getElementsByTagName("script");
for (var x in sc)
if ((sc[x].src !== null) && (sc[x].src.indexOf(file_path) != -1)) return;
$.include(file_path);
}
//09 Acrescenta o Link Flutuante para o TOPO em páginas muito compridas
$.link_para_topo = function(topText)
{
var caption = topText === undefined ? 'top' : topText;
$(window).scroll(function(){
if ($(this).scrollTop()) {
if($('#link_topo').length){
$('#link_topo:hidden').stop(true, true).fadeIn("slow");
}else{
$('body')
.append('<div id="link_topo">'+caption+'</div>')
.find("#link_topo")
.css
({
"cursor":"pointer",
"position":"fixed",
"text-align":"center",
"bottom":"2em",
"right":"2em",
"width":"6em",
"text-decoration":"none",
"background-color":"#ee6727",
"color":"white",
"padding":"0.5em",
"opacity": ".5",
"display":"none",
"z-index":"1000"
})
.addClass('round')
.bind("click",function(){
$('html, body').animate({ scrollTop: 0 }, 'slow');
})
.bind("mouseenter",function(){
$(this).animate({ opacity: 1 }, "slow" );
})
.bind("mouseout",function(){
$(this).animate({ opacity: .5 }, "slow" );
});
}
} else {
$('#link_topo').stop(true, true).fadeOut("fast");
}
});
}
//10 Gera dinamicamente uma caixa flutuante EM DESTAQUE, APÓS o parágrafo em que for encontrado, com o texto dentro da tag < span class="destaque"> texto < / span>;
$.destaques = function()
{//Busca todos as tags SPAN com a classe destaque;
$('p').find('span.destaque')
.each(function()
{
var $this = $(this);
var $elemento = '<div class="container_notepaper"><section class="notepaper"><figure class="quote"><blockquote class="curly-quotes">'+$(this).text()+'</blockquote></figure></section><div>';
$($elemento).appendTo($this.closest('p'));
});
}
//11 Carrega uma imagem aleatória no topo do site
$.random_topo = function()
{
// num = Math.round(Math.random()*4); // Gera um número aleatório qualquer
// imagem = '/imagens/img_topo_0' + eval(num) + '.jpg'; // Define qual a imagem a ser carregada no topo de site
// $('#img_topo').attr('src',imagem); // Troca a imagem do topo de site
}
//12##### $.rwdTest() | Muda o tamanho do Container de acordo com o tamanho desejado e adiciona um fundo com medidas
$.rwdTest = function($tam)
{
$("body").css(
{
"width":$tam,
"background":"url(/imagens/bk_responsive_guide.jpg)",
"border":"1px solid #666"
});
}
//13##### $.fn.fade1by1 | Carrega os elementos um por um com o efeito de fade
/*
$('.itens').fade1by1({
speed: 400,
delay: 200
});
*/
$.fn.fade1by1 = function (options) {
var opt = $.extend({
'delay': 500,
'speed': 500,
'ease': 'linear'
}, options);
this.hide();
var that = this;
for (var i = 0, d = 0, l = that.length; i < l; i++, d += opt.delay)
{
that
.eq(i)
.delay(d)
.fadeIn(opt.speed, opt.ease);
}
};
//14###### AJAXSTART
// $.fn.showLoading = function()
// {
// $(document).ajaxStart(function()
// {
// $("#smallModal").modal({
// backdrop: 'static',
// keyboard: false // to prevent closing with Esc button (if you want this too)
// });
// $("#smallModal").find('.modal-header').hide();
// $("#smallModal").find('.modal-footer').hide();
// $("#smallModal").find('.modal-body').html('Processing...');
// $("#smallModal").modal('show');
// }).ajaxComplete(function() {
// $("#smallModal").modal('hide');
// });
// }
//15###### loadCSS(url)
function loadCSS(url) {
var lnk = document.createElement('link');
lnk.setAttribute('type', "text/css" );
lnk.setAttribute('rel', "stylesheet" );
lnk.setAttribute('href', url );
document.getElementsByTagName("head").item(0).appendChild(lnk);
}
//15###### loadCSS(url)
function loadCSS(url) {
var lnk = document.createElement('link');
lnk.setAttribute('type', "text/css" );
lnk.setAttribute('rel', "stylesheet" );
lnk.setAttribute('href', url );
document.getElementsByTagName("head").item(0).appendChild(lnk);
}
//16###### function include(file_path)
function include(file_path){
var j = document.createElement("script"); /* criando um elemento script: </script><script></script> */
j.type = "text/javascript"; /* informando o type como text/javacript: <script type="text/javascript"></script>*/
j.src = file_path; /* Inserindo um src com o valor do parâmetro file_path: <script type="javascript" src="+file_path+"></script>*/
document.getElementsByTagName("head").item(0).appendChild(j); /* Inserindo o seu elemento(no caso o j) como filho(child) do BODY: <html><body><script type="javascript" src="+file_path+"></script></body></html> */
}
//17##### $.floatLink = function($divId = "link_new_location", $divClass = "floating-link", $aHref = "../core/new_location.php", $aTitle = "New Location", $imgSrc = "../images/new_location.png")
$.floatLink = function(divId, divClass, aHref, aTitle, imgSrc)
{
divId = (divId.length === 0)?"link_new_location":divId;
divClass = (divClass.length === 0)?"floating-link":divClass;
aHref = (aHref.length === 0)?"../core/new_location.php":aHref;
aTitle = (aTitle.length === 0)?"New Location":aTitle;
imgSrc = (imgSrc.length === 0)?"../images/new_location.png":imgSrc;
$('<div>', {
id: divId,
class: divClass })
.append($('<a>',{
href: aHref,
title: aTitle })
.append($('<img>', {
src: imgSrc,
alt: aTitle
})))
.appendTo('body');
};