Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Kamusz

Alerta Personalizavel

Recommended Posts

Olá pessoal, pensei em compartilhar com vocês um script meu de alerta personalizado, espero que seja útil.

 

Nesse script você pode adicionar mensagens, botões e até mesmo campos de texto, checkbox e etc...

 

Segue abaixo o código da classe, e abaixo uma pequena explicação de como se usar, mais a classe é bem customizavel, você poderá configura-la como quiser:

 

function Alertar(msg,titulo) {
	var msg = msg || null;
	var titulo = titulo || 'Aviso!';
	var btns = [];
	var fields = [];
	var div = null;
	var tituloDiv = null;
	var msgDiv = null;
	var btnDiv = null;
	var fieldsDiv = null;
	var cssclass = null;
	var parent = this;
	var data = new Date();
	
	this.getScrollXY = function () {
	  var scrOfX = 0, scrOfY = 0;
	  if( typeof( window.pageYOffset ) == 'number' ) {
	    scrOfY = window.pageYOffset;
	    scrOfX = window.pageXOffset;
	  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	    scrOfY = document.body.scrollTop;
	    scrOfX = document.body.scrollLeft;
	  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	    scrOfY = document.documentElement.scrollTop;
	    scrOfX = document.documentElement.scrollLeft;
	  }
	  return { x : scrOfX, y : scrOfY };
	}
	
	this.setMsg = function(message) {
		msg = message;
	}
	
	this.setTitulo = function(tit) {
		titulo = tit;
	}
	
	this.setStyle = function(classe) {
		cssclass = classe;
		div.removeAttribute('style');
		div.className = classe;
		div.style.position = 'absolute';
	}
	
	this.addButton = function() {
		var value = null;
		var style = null;
		var id = null;
		var onkeypress = '';
		var onkeyup = '';
		var onkeydown = '';
		var onclick = '';
		var onmouseover = '';
		var onmouseout = '';
		
		this.setValue = function(valor) {
			value = valor;
		}
		this.setStyle = function(valor) {
			style = valor;
		}
		this.setId = function(valor) {
			id = valor;
		}
		this.setOnKeyPress = function(valor) {
			onkeypress = valor;
		}
		this.setOnClick = function(valor) {
			onclick = valor;
		}
		this.setOnKeyUp = function(valor) {
			onkeyup = valor;
		}
		this.setOnKeyDown = function(valor) {
			onkeydown = valor;
		}
		this.setOnMouseOver = function(valor) {
			onmouseover = valor;
		}
		this.setOnMouseOut = function(valor) {
			onmouseout = valor;
		}
		this.add = function() {
			var button = document.createElement('input');
			button.setAttribute('type','button');
			button.setAttribute('id',id);
			button.setAttribute('value',value || '');
			button.setAttribute('class',style || '');
			button.setAttribute('onclick',onclick || '');
			button.setAttribute('onkeypress',onkeypress || '');
			button.setAttribute('onkeyup',onkeyup || '');
			button.setAttribute('onkeydown',onkeydown || '');
			button.setAttribute('onmouseover',onmouseover || '');
			button.setAttribute('onmouseout',onmouseout || '');
			
			btns.push(button);
			
			btnDiv.appendChild(button);
		}
	}
	this.addField = function() {
		var name = '';
		var id = '';
		var type = '';
		var maxlength = '';
		var value = '';
		var label = '';
		var style = '';
		var onkeypress = '';
		var onkeyup = '';
		var onkeydown = '';
		var onclick = '';
		var onmouseover = '';
		var onmouseout = '';
		
		this.setName = function(valor) {
			name = valor;
		}
		this.setId = function(valor) {
			id = valor;
		}
		this.setType = function(valor) {
			type = valor;
		}
		this.setMaxLength = function(valor) {
			maxlength = valor;
		}
		this.setStyle = function(valor) {
			style = valor;
		}
		this.setValue = function(valor) {
			value = valor;
		}
		this.setLabel = function(valor) {
			label = valor;
		}
		this.setOnKeyPress = function(valor) {
			onkeypress = valor;
		}
		this.setOnClick = function(valor) {
			onclick = valor;
		}
		this.setOnKeyUp = function(valor) {
			onkeyup = valor;
		}
		this.setOnKeyDown = function(valor) {
			onkeydown = valor;
		}
		this.setOnMouseOver = function(valor) {
			onmouseover = valor;
		}
		this.setOnMouseOut = function(valor) {
			onmouseout = valor;
		}
		this.add = function() {
			var lab = document.createElement('label');
			if (id) {
				lab.setAttribute('for',id);
			}
			lab.innerHTML = '<b>'+label+'</b><br>';
			
			if (type == 'select') {
				var field = document.createElement('select');
			} else {
				var field = document.createElement('input');
				field.setAttribute('type',type || '');
				field.setAttribute('value',value || '');
				field.setAttribute('maxlength',maxlength || '');
			}
			field.setAttribute('name',name || '');
			field.setAttribute('id',id || '');
			field.setAttribute('class',style || '');
			field.setAttribute('onclick',onclick || '');
			field.setAttribute('onkeypress',onkeypress || '');
			field.setAttribute('onkeyup',onkeyup || '');
			field.setAttribute('onkeydown',onkeydown || '');
			field.setAttribute('onmouseover',onmouseover || '');
			field.setAttribute('onmouseout',onmouseout || '');
			
			var br = document.createElement('br');
			br.setAttribute('clear','all');
			
			lab.appendChild(field);
			
			fields.push(lab);
			fieldsDiv.appendChild(lab);
			fieldsDiv.appendChild(br);
			
			return field;
		}
	}
	
	this.addOption = function(select) {
		var text = '';
		var value = '';
		
		this.setText = function(valor) {
			text = valor;
		}
		this.setValue = function(valor) {
			value = valor;
		}
		this.add = function() {
			var option = document.createElement('option');
			option.setAttribute('value',value);
			option.innerHTML = text;
			
			select.appendChild(option);
		}
	}
	
	this.criar = function() {
		if (!div) {
			div = document.createElement('div');
			div.id = 'AlertaDiv'+data.getTime();
			if (cssclass) {
				div.className = cssclass;
			} else {
				div.style.border = '2px solid #000';
				div.style.padding = '3px';
				div.style.width = '250px';
				div.style.minHeight = '100px';
				div.style.backgroundColor = '#fff';
				div.style.left = '50%';
				div.style.marginLeft = '-'+(div.style.width.substr(0,div.style.width.length-2) / 2)+'px';
			}
			
			div.style.position = 'absolute';
			div.style.display = 'none';
			
			tituloDiv = document.createElement('div');
			tituloDiv.id = 'AlertaTitulo'+data.getTime();
			tituloDiv.className = 'AlertaTitulo';
			tituloDiv.innerHTML = titulo;
			
			msgDiv = document.createElement('div');
			msgDiv.id = 'AlertaMsg'+data.getTime();
			msgDiv.className = 'AlertaMsg';
			msgDiv.innerHTML = msg;
			
			btnDiv = document.createElement('div');
			btnDiv.id = 'AlertaBtn'+data.getTime();
			btnDiv.style.width = '100%';
			btnDiv.className = 'AlertaBtn';
			
			fieldsDiv = document.createElement('div');
			fieldsDiv.id = 'AlertaFields'+data.getTime();
			fieldsDiv.style.width = '100%';
			fieldsDiv.className = 'AlertaFields';
			
			var br = document.createElement('br');
			br.setAttribute('clear','all');
			
			div.appendChild(tituloDiv);
			div.appendChild(br);
			div.appendChild(msgDiv);
			div.appendChild(br);
			div.appendChild(fieldsDiv);
			div.appendChild(br);
			div.appendChild(btnDiv);
			
			document.body.appendChild(div);
		}
	}
	
	this.mostrar = function() {
		var pos = this.getScrollXY();
		
		div.style.display = 'block';
		div.style.top = (pos['y'] + 100) + 'px'
	}
	
	this.getDivId = function() {
		return 'AlertaDiv'+data.getTime();
	}
	
	this.fecharAlerta = function() {
		div.style.display = 'none';
	}
	
	this.criar();
}

O uso é bem simples ( eu acho =p ) Segue abaixo um tutorialzinho:

 

Antes de mais nada, instancie o obj, já no construtor é possivel passar as váriaveis da mensagem e do titulo respectivamente, você poderá adicionar botões e campos, e setar classes css para cada objeto.

var alerta = new Alertar('Mensagem','Titulo'); // Instancie a classe, se quiser pode passar já aqui a Mensagem e o Titulo do aviso
alerta.setStyle('classeCSS'); // Aqui você, caso desejar, configura uma classe CSS para o aviso
alerta.setMsg('Mensagem'); // Você pode configurar a mensagem usando esta função também
alerta.setTitulo('Titulo'); // Você pode configurar o titulo usando esta função também

// É possivel adicionar botões ao aviso, para isso utilize a classe addButton que se encontra dentro da classe Alerta
var button = new alerta.addButton(); // Instancie a classe addButton
button.setValue('Clique para fechar!'); // Value do Botão
button.setStyle(''); // Classe CSS caso deseje personalizar o Botão
button.setId('btnId1'); // ID do Botão
button.setOnClick('alerta.fecharAlerta();'); // Comando a ser executado quando o event onclick do botão for ativado, no caso utilizei uma função da classe que esconderá o Alerta quando clicado
button.setOnKeyPress('alert("keypress");'); // Comando a ser executado quando o event onkeypress do botão for ativado
button.setOnKeyUp('alert("keyup");'); // Comando a ser executado quando o event onkeyup do botão for ativado
button.setOnKeyDown('alert("keydown");'); // Comando a ser executado quando o event onkeydown do botão for ativado
button.setOnMouseOver('alert("mouseover");'); // Comando a ser executado quando o event onmouseover do botão for ativado
button.setOnMouseOut('alert("mouseout");'); // Comando a ser executado quando o event onmouseout do botão for ativado
button.add(); // Finalmente adicione ele ao Aviso

// Você poderá adicionar quantos botões forem necessários desta forma e cada um poderá ter propriedades unicas, porém cuidado para não identifica-los com o mesmo ID

// É possivel também adicionar campos INPUT e SELECT
// Para adicionar um INPUT, utilize da seguinte forma:

var input = new alerta.addField(); // Instancie a classe addField
input.setName('campo1'); // Configure o name do campo
input.setId('campo1'); // Configure o id do campo
input.setType('text'); // Configure o type do campo
input.setMaxLength('100'); // Configure o maximo de caracteres permitidos
input.setStyle('style1'); // Configure uma classe CSS para personalização
input.setValue('valor padrão'); // Valor Padrão do campo
input.setLabel('Campo 1'); // Label, texto para identificar o campo
input.setOnKeyPress('alert("keypress");'); // Comando a ser executado no evento onkeypress
input.setOnClick('alert("click");'); // Comando a ser executado no evento onclick
input.setOnKeyUp('alert("keyup");'); // Comando a ser executado no evento onkeyup
input.setOnKeyDown('alert("keydown");'); // Comando a ser executado no evento onkeydown
input.setOnMouseOver('alert("mouseover");'); // Comando a ser executado no evento onmouseover
input.setOnMouseOut('alert("mouseout");'); // Comando a ser executado no evento onmouseout
input.add(); // Adicionar o campo ao alerta.

// Para adicionar um SELECT, utilize da seguinte forma:
var sel = new alerta.addField(); // Instancie a classe addField
sel.setType('select'); // Configure o type do campo
sel.setName('campo1'); // Configure o name do campo
sel.setId('campo1'); // Configure o id do campo
sel.setStyle('style1'); // Configure uma classe CSS para personalização
sel.setLabel('Campo 1'); // Label, texto para identificar o campo
sel.setOnKeyPress('alert("keypress");'); // Comando a ser executado no evento onkeypress
sel.setOnClick('alert("click");'); // Comando a ser executado no evento onclick
sel.setOnKeyUp('alert("keyup");'); // Comando a ser executado no evento onkeyup
sel.setOnKeyDown('alert("keydown");'); // Comando a ser executado no evento onkeydown
sel.setOnMouseOver('alert("mouseover");'); // Comando a ser executado no evento onmouseover
sel.setOnMouseOut('alert("mouseout");'); // Comando a ser executado no evento onmouseout
var select = sel.add(); // Adicionar o campo ao alerta, PS: Quando select, guarde o retorno desta função para usar nas opções.

// Adicionar Options ao Select
var option = new alerta.addOption(select); // Instancie a classe addOption e passe como parametro o retorno da função add da classe addInput
option.setValue('1'); // Configure o valor do option
option.setText('Valor 1'); // Configure o texto do option
option.add(); // Adicione ao select

// Você poderá adicionar quantos options quiser, só repetir todo o processo:
var option2 = new alerta.addOption(select); 
option2.setValue('2');
option2.setText('Valor 2');
option2.add();
		
var option3 = new alerta.addOption(select);
option3.setValue('3');
option3.setText('Valor 3');
option3.add();

// Por Fim, execute
alerta.mostrar();

// Fechar Alerta
alerta.fecharAlerta(); // Pode ser utilizado em algum botão, adicione este comando a algum evento (onclick, onkeypress...)

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.