Ir para conteúdo
Fórum Script Brasil

Pesquisar na Comunidade

Mostrando resultados para as tags ''js''.

  • Pesquisar por Tags

    Digite tags separadas por vírgulas
  • Pesquisar por Autor

Tipo de Conteúdo


Fóruns

  • Programação & Desenvolvimento
    • ASP
    • PHP
    • .NET
    • Java
    • C, C++
    • Delphi, Kylix
    • Lógica de Programação
    • Mobile
    • Visual Basic
    • Outras Linguagens de Programação
  • WEB
    • HTML, XHTML, CSS
    • Ajax, JavaScript, XML, DOM
    • Editores
  • Arte & Design
    • Corel Draw
    • Fireworks
    • Flash & ActionScript
    • Photoshop
    • Outros Programas de Arte e Design
  • Sistemas Operacionais
    • Microsoft Windows
    • GNU/Linux
    • Outros Sistemas Operacionais
  • Softwares, Hardwares e Redes
    • Microsoft Office
    • Softwares Livres
    • Outros Softwares
    • Hardware
    • Redes
  • Banco de Dados
    • Access
    • MySQL
    • PostgreSQL
    • SQL Server
    • Demais Bancos
  • Segurança e Malwares
    • Segurança
    • Remoção De Malwares
  • Empregos
    • Vagas Efetivas
    • Vagas para Estágios
    • Oportunidades para Freelances
  • Negócios & Oportunidades
    • Classificados & Serviços
    • Eventos
  • Geral
    • Avaliações de Trabalhos
    • Links
    • Outros Assuntos
    • Entretenimento
  • Script Brasil
    • Novidades e Anúncios Script Brasil
    • Mercado Livre / Mercado Sócios
    • Sugestões e Críticas
    • Apresentações

Encontrar resultados em...

Encontrar resultados que...


Data de Criação

  • Início

    FIM


Data de Atualização

  • Início

    FIM


Filtrar pelo número de...

Data de Registro

  • Início

    FIM


Grupo


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

  1. Atualmente utilizo em meus códigos JS, a seguinte estrutura. var ysQuery = (function ($, window, document, undefined) { 'use-strict' // variáveis de acesso global var baseUrl = ''; // Métodos de acesso restrito var Private = {}, // Métodos de acesso público var Public = {} return Public }(Jquery, window, document)); Gostaria de sugestões em relação a performance na utilização deste tipo de estrutura, e melhorias. Abraço
  2. Fala "Jedais"; Quando do form mando inserir no bd e a chave primária é violado obtenho uma resposta, dou um feedback para o usuário dizendo cnpj já existe. Mas passei a fazer com ajax para evitar o carregamento da pagina, e o problema é o seguinte: JS e o Ajax $(document).ready(function() { $("#id_botao").click(function(e) { if (!validarForm()) { return; } var nome = $("#nome"); var nomePost = nome.val(); var cnpj = $("#cnpj"); var cnpjPost = cnpj.val(); var radioPost; if(document.getElementById('radio0').checked == true) { radioPost = 0; }else { radioPost = 1; } $.ajax({ url : 'emp-inserir.php', type : "POST", data: { nome: nomePost, cnpj: cnpjPost, radio: radioPost //chave:valor }, datatype: "html", beforeSend: function(){ // modal dizendo que esta salvando }, success : function(response) { // AQUI quero o retorno dizendo que foi gravado com sucesso ou se houve a violação da chave primária }, error : function(data) { alert('Erro: URL não encontrada!');// não achou a url (debug) }, }) });// fim botão }); A URL para o ajax <?php $resultadoDao = '0'; require_once('dao/crud-emp.php'); $dao = new DaoEmpresa(); $nome = $_POST['nome']; $cnpj = $_POST['cnpj']; $radio = $_POST['radio']; if ($dao->inserir($nome, $cnpj, $radio)) { $resultadoDao = 'SUCESSO';// NÃO CONSIGO PEGAR ESTE VALOR }else { $resultadoDao = 'ERRO';// NÃO CONSIGO PEGAR ESTE VALOR } echo $resultadoDao; ?> O arquivo dao/crud-emp-.php public function inserir($nome, $cnpj, $isAutomatico) { error_reporting(0); // retirar caracteres acentuados $nome = strtr($nome, $this->map); // forçar a gravar tudo em maiusculo. Se quiser apenas a primeira letra de cada palavra em maiusculo, usar ucwords($nome) $nome = strtoupper($nome); $sql = "INSERT INTO empresa (nome, cnpj, isAutomatico) VALUES ('$nome', '$cnpj', '$isAutomatico')"; // retorna falso quando há duplicidade na chave primária, no caso o campo cnpj if (!mysql_query($sql)) { //$this->conectar->desconecta(); return false; } $this->addAutomatico($nome); $this->conectar->desconecta(); return true; } Amigos, tudo funciona, grava no bd quando é para gravar e não gtva quando o cnpj (chave primária) foi violada. Mas eu tenho que dar um feedback para o usuário saber que foi ou não gravado. Percebi através do console.log, que o parâmetro da função sucess do ajax retorna uma pagina inteira, tem como eu pegar um true/false? Desde já agradeço.
  3. Pessoal sobre esse vídeo e a timeline, imagine que a timeline funcione como uma função seek em js sobre esse video. Por exemplo: supondo que o video tenha 30 minutos, cada fragmento dessa timeline apresenta um snapshot ou uma foto do momento daqueles 5 minutos. A ideia é que essa timeline abaixo do video facilita a localização de determinada ação do video em questão. Desde já agradeço a coloração de quem puder me ajudar!
  4. Preciso de uma pequena instrução com o código que criei. Esse código deve criar uma nova Issue no meu repositorio no GitHub, porém, eu creio que não estou nem perto disso, não estou obtendo nenhum erro pelo console, mas mesmo assim o POST não está funcionando. olhem: //function relacionada a um form no index.html function postarIssue() { var http = new XMLHttpRequest(); var posIssue = "get_data.php"; var params = {'token': 'token-aqui', 'title': 'teste', 'body': 'Beep boop.'}; http.open("POST", "https://api.github.com/repos/stn6mazia/BitchIssues/issues", true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", params.length); http.setRequestHeader("Connection", "close"); http.onreadystatechange = function postarIssue() { if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); }; não sei muito mais o que posso estar fazendo de errado, se puderem me ajudar, eu ficaria MUITO grato. Obrigado Att
  5. Boa noite pessoal, antes de mais nada eu já peço desculpas por esse tópico não ter um titulo claro e objetivo, e se já existir essa mesma dúvida em algum outro tópico, peço aos moderadores que removam este e se possível me indique o outro. Bom, sem mais delongas vamos ao caso. Comecei a estudar PHP, sou um estudante "autônono", estudo pela internet e por este motivo, sinto dificuldades em esclarecer algumas dúvidas que surgem durante o aprendizado e devido a isso eu estou aqui, postando uma dúvida que não encontrei na internet (Talvez por não ter pesquisado direito, rsrs). A dúvida é a seguinte, estou criando um formulário de cadastro para colocar em prática o que venho aprendendo no decorrer do curso que estou fazendo, esse formulário envia os dados para uma pagina PHP que faz as validações e se tudo ocorreu bem, ela exibe o alert do Javascript informando que o cadastro foi realizado. Em seguida, redireciona o usuário para uma pagina de login. Até ai está tudo bem, funcionando certinho, mas eu quero que, assim que ele redirecionar para login.html ele executará uma função JavaScript que está declarada neste arquivo (login.html). Queria algo mais ou menos assim: echo("<script>location.href='login.html'; myFunction('Essa função este declarada no login.html mas nao funciona dessa forma');</script>"); Desde já, eu peço desculpas por alguma ignorância em questão do código ou da forma que estou codificando, pois como disse, sou iniciante.
  6. Galera, estou com o seguinte erro no meu template: Type PaginatePipe is part of the declarations of 2 modules: Eu estou fazendo o import do pipe PaginatePipe em 2 modulos, o que eu achava que iria funcionar normalmente, porém não funcionou, alguém sabe o que está ocorrendo? Obrigado desde já!
  7. rafaelmoura

    bloqueio de URL

    Galera preciso de uma ajuda .. vou fazer de forma resumida de como está a estrutura de meu projeto bem simples admin index require index header footer login - Tenho uma classe que faz as validações do login e etc ... }else{ if($this->log && $this->log->rowCount() > 0){ foreach($this->log as $this->dds){ session_start(); $_SESSION['logado'] = $this->dds; //var_dump($_SESSION['logado']['nome']); // insere todo conteudo dentor da <p> na pagina de login header('location: ../../../../admin'); // SE FOR ADMINISTRADOR REDIRECIONO PARA ADMI echo "<meta HTTP-EQUIV='refresh' CONTENT='0;URL=/../admin/'>"; // SENÃO REDIRECIONO PARA ARE DE DISTRIBUIROD } }else{ return 'Acesso Negado'; ... como podem ver neste arquivo crio a $_SESSION['logado'] gostaria de saber como bloquear o acesso de quem não estiver logado, como posso fazer 1 - quem poder mostrar em código como fazer 2 - há a possibilidade de fazer no arquivo header tendo em vista que todos os demais arquivos dependem dele ? 3 - se não for no header, seria no index ? obs: na raiz do projeto apesar de ter o index, atravez do htaccess rediceriono sempre para o arquivo de login quem poder me ajudar agraderia muito ......
  8. Gente, estou criando um app com o PHONEGAP que transforma códigos web em um aplicativo. No meu aplicativo tem uma função para a pessoa responder questões, então pensei da seguinte forma: 1. Variável de respostas (Armazena a alternativa correta) 2. If/else para verificar se a resposta bate com a escolhida 3. Método randômico para ser inserido no case (Case não pode ser repitido) 4. Case com armazenagem das perguntas 5. Botão de verificação da resposta (Redireciona para outra pagina que informa se a questão é a certa ou errada) No caso as funções 1,2 e 5 já estão funcionando, porém estou com um problema para criar o metódo randomico, que não reconhece no meu código, e também atrelar ele com o case. PS.: Caso o case for ficar dentro do script, por favor me ajudem a colocar botões de seleção lá dentro também.
  9. Galera eu preciso carregas as fotos de uma pasta porém eu preciso muito que vocês me ajudem nisso. Eu quero carregar as fotos só quando eu clicar na palavra "mostrar fotos" que vem acompanhada de um scrypt toggle. Mais as fotos só devem ser carregadas após clicar e eu não estou conseguindo. A div onde as imagens se encontram se chama <div id="galeria"> sem atualizar pagina toda. Exemplo se eu clicar na palavra imagem1 ele carrega na div galeria todas imagens se eu clicar na imagem2 ele carrega e imprime na div galeria as imagens da imagem2 sem atualizar a pagina <?php $pasta = 'imagem/fotos eventos/fotosteste/'; $arquivos = glob("$pasta{*.JPG,*.JPEG,*.*,*.bmp}", GLOB_BRACE); foreach($arquivos as $img){?> <a href="<?php echo $img; ?>"> <img src="<?php echo $img; ?>"class="imagemalbum"> </a> <?php } ?> Muito obrigado!
  10. Quem já escreveu algum js com requisições ajax sabe que, vez ou outra, é necessário fazer referencias explicitas à páginas, variáveis e outros conteúdos que não seriam de bom grado caíssem em mãos malvadas. Nunca é demais um proteçãozinha extra (não digo aqui que o 'truque' adiante seja o método mais seguro, mas também, não é dos mais tolos) quando o assunto é dados vulneráveis em nossos sistemas web. Segue adiante uma dica de como podemos ocultar ('proteger') nosso js para que seu conteúdo não fique exposto à leitura de quantos queiram. E, para os amantes do código arreganhado, não trata-se de uma ação 'CodeEgoíca' (neologismo, nenhuma referencia no google até hoje hehehe), uma vez que não impede o desenvolvedor do código 'protegido' de participar, querendo, de comunidades voltadas ao compartilhamento de conhecimento, e lá, auxiliar ativamente a outros a desenvolverem seus próprios códigos. Javascript é uma linguagem de programação do lado do cliente (isso vocês já sabem), ele roda (é executado) na máquina do cara que tá cessando sistema web, o site etc.. Assim sendo, não se pode, efetivamente, 'esconder' algo que esteja ai, na sua máquina. Ocultar ou ofuscar seu o script (código) é uma boa solução, mas não é suficiente, porque, embora torne o processo mais complicado, algum mal intencionado sempre acaba decifrando o que quer decifrar, e aqui, não sejamos ingênuos, os ninjas entram nas máquinas do governo americano, de bancos referencia em segurança digital, imagina no teu scriptzinho 'protegido'. Não desanime, mesmo com essas injeção de desanimo, existem algumas soluções para deixar seu código ofuscado, 'oculto', difícil de ser roubado (eita! aqui é osso). Mas lembrem-se, como eu disse, nada é 100% em se tratando de segurança digital. Bem!, assim de cabeça, uma primeira ideia é restringir o acesso aos seus arquivos .js externos. Aqueles que você escreveu o código e esta chamando na index pela tag '<script type="text/javascript" src="exemplo.js"></script>'. Supomos que alguém tente acessar o 'exemplo.js' pelo navegador, e ao fazê-lo ele não deverá visualizar seu conteúdo, mas sim, uma mensagem de erro. Se sua página é escrita em PHP, pode incluir o script através da função 'include' e deixar o php decidir se é seguro mostrar o código. Para este exemplo, você vai precisar que seus arquivos .js externos estejam escritos em php 'exemplo.php', e neles, conter o código abaixo antes do 'echo' com o código em js: Vejamos: <?php //esse código vai dentro, e logo no início, do arquivo 'exemplo.php' (que é o arquivo que contém o código js, não vamos confundir tudo) //pode alterar de acordo com a necessidade $URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; if ($URL != "meudominio.br/index.php") die("/\*sry, tipo sem direito de acesso\*/"); ?> ... <script type="text/javascript"> //essa tag de chamada js vai dentro do arquivo index.php (arquivo que chama o js, que em nosso caso é o 'exemplo.php') <?php include "exemplo.php"; ?>; </script> Desta forma, apenas o navegador poderá ver o conteúdo do arquivo js. Outra ideia interessante é que no final do seu script js, você apague seu conteúdo excluindo o elemento dom, de modo que após o navegador ler o código, o código desapareça: <script id="codigoJs" type="text/javascript"> //seu código js aqui //apaga o elemento script com o código após a leitura do mesmo pelo browser document.getElementById('codigoJs').innerHTML = ""; </script> Estes são hack's simples que não podem, e eu já falei antes, proteger totalmente seu código js, mas com certeza, pode irritar alguém que está tentando 'ler' o seu código. Espero ter ajudado. Abraço a todos!
  11. Bom dia galera, Ai vai uma dúvida bem bobinha rs. Seguinte, eu n qr usar o alert do js na minha aplicação, qria usar um bootbox ou uma div q exibisse uma mensagem de sucesso ou erro p usuário. O porém é q n to sabendo fz isso, quando chamo o alert do bootbox, ele n aparece. O trecho do código atual esta assim: if(mysqli_query($con, $sql)){ echo "<script>alert('salvo com sucesso!'); location.href='consultar-usuario.php?nome=%'</script>"; }else{ echo "<script>alert('Erro ao salvar!'); location.href='consultar-usuario.php?nome=%'</script>"; } Se possivel vocês m ajudarem com a função js que terei q chamar a div ou o bootbox ficarei grato.OBS: com o alert funciona d boa.
  12. Pessoal não sei muito js, mas enfim... Tenho uma função e preciso retornar o valor dela, como fazer?
  13. Fala galera, beeeleza?! Estou começando a entender js, mas ainda tenho muitas coisas q não sei!!! Tenho um problema com o jqueryvalidation, pois se o usuário preencher os campos errados ira exibir uma mensagem de erro, caso contrario seria pra exibir uma mensagem de sucesso, mas essa ultima não está funcionando. Alguém poderia dar um help? segue abaixo o code: $(document).ready(function () { //mensagem de input valido jQuery.validator.setDefaults({ debug: true, success: "valid" }); //validação do formulário $("#formNovoUsuario").validate({ rules: { nome: {required: true, minlength: 10}, cpf: {required: true}, especialidade: {required: true, minlength: 5} }, messages: { //mensagem de input invalido nome: {required: "Preencha esse campo"}, cpf: {required: "Preencha esse campo"}, especialidade: {required: "Preencha esse campo"} }, //mensagem de form enviado com sucesso submitHandler: function(form) { alert("Sucesso!"); var $form = $(form); $form.submit(); } }); });
  14. Fala Pessoal, Tenho um Blog em WP, e queria um JS que abrisse o Popup por Trás da página principal. Que abrisse ou por temporizador ou quando o usuário cliquasse em algo no site. alguém pode me ajudar?
  15. Olá. Nós sabemos que o google tem o sistema Adsense (que coloca propagandas em um site). Também sabemos de outros sites com o mesmo fim (colocar propagandas em seu site). E outros agora que recomendam conteúdos (taboola, outbrain, samba ads). Todos eles tem algo em comum isso é feito com JS. Simplesmente um link assync + tags no HTML. Ai vem a pergunta, como isso funciona ? Onde posso encontrar material para estudar isso? Bobinas de Tesla já foram usadas em transmissores de rádio primitivos, dispositivos de eletroterapia e geradores de alta tensão para aplicações em Física de altas-energias. A aplicação mais comum atualmente é para demonstrações sobre eletricidade em alta tensão, gerando faíscas elétricas que podem ter vários metros de comprimento. Física Existe algum exemplo por ai ? Algo mais simples. O que devo estudar para criar algo assim? OBS, não quero criar nada para ser concorrentes deles. Quero apenas poder colocar meu conteúdo (meu site) em sites parceiros de conteúdo. Coisa simples e queria fazer com JS praticamente da mesma forma. Alguém tem alguma ideia de por onde começar ? Abraços
  16. Galera estou mandando 3 print de como está meu AngularJS, agora irei falar o que eu quero, esse código é apenas teste do AngularJS.. Eu possuo um campo chamado 'CNPJ', e quando eu estiver digitando ou sair desse campo ele irá automaticamente consultar o banco, sem clique sem nada, usando onBlur, ou outro evento do angular que seja simultâneo.. Ele irá consultar o banco e ver se existe, se ele existir ele irá retornar um outro valor do banco e colocar em outro input do form, que seria a 'Razão Social' desse CNPJ digitado. Só isso que irá fazer. Desde de já muito obrigado.
  17. Olá galera, estou precisando muito de uma ajuda. Eu possuo um formulário, nesse formulário eu tenho um input que recebe um resultado de um calculo através de outros input, porém quando eu entro dentro desse input e digito os números ele funciona a mascara, fiz com MaskMoney, agora quando esse input recebe um valor de um calculo ou de qualquer outro input ele fica apenas o valor recebido, ele fica sem mascara. Conclusão, a mascara funciona quando entro no input e digito os número, agora quando esse input recebe valores de fora ele fica sem mascara. obrigado galera;
  18. Pessoal criei uma conta nessa fórum para saber se algum pode me ajudar nesse codigo o que tem de errado nele segue apaixo <script src"cordova.js"></script> <script type="text/javascript"> var onDeviceReady=function(){ navigator.splashscreen.hide(); initiAdMob(); showAdMobInterestitial(); showAdMobBanner(); }; document.addEventListener("deviceready",onDeviceReady,false); function initAdMob(){ if(window.plugins && window.plugins.AdMob){ var admob_key_banner = "xxxxxxxxxxxx"; var admob_key_interstitial = "xxxxxxxx"; window.plugins.AdMob.setOptions({ publisherId: admob_key_banner, bannerAtTop: true, //set to true put banner at top overlap: false, //set to true, to allow banner overlap webview offsetTopBar: true,//set to true to avoid ios? stutus bar overlap intertitialAdid: admob_key_intertitial, autoShow: true, //autoshouw intertitial ad isTesting: false // receiving test ad }); }else{ alert("AdMob plugins not ready"); } } function showAdMobBanner(){ window.plugins.AdMob.createBannerView(); } function showAdMobInterestitial(){ window.plugins.AdMob.createInterestitialView(); } </script> <script type="application/javascript" src"admob/admob.js"></script> [code/]
  19. Olá! Gostaria de uma forma para obrigar que um campo seja preenchido pelo começo, sem espaços em branco antes do primeiro caractere. O que já faço: Em um input de celular, por exemplo, consigo colocar um máscara e obrigar o usuário a digitar uma quantidade específica de caracteres e no padrão que desejo, mas gostaria de também obrigar o mesmo a quando clicar no campo só poder digitar se for a partir do começo desde. Exemplo: 999... e que ele não possa fazer algo do tipo __999... Mesmo que minhas máscaras e validações não permitam que ele cadastre assim, gostaria de evitar que os usuários cometessem esse erro. As validações faço pelo próprio primefaces. <p:inputMask value="#{driverBean.driver.person.phones.get(0).number}" size="8" mask="999999999" styleClass="#{not component.valid ? 'invalid-field' : ''}" required="true" requiredMessage="Informe o celular." />
  20. t Sou novato como webdesing e estou enfretando um problema com um Popup do google maps. o erro é o seguinte, somente com o clique deveria aparece o popup, entretanto ele aparece mesmo sem clicar, poderia me ajuda? Segue o codigo abaixo: ----------------Pagina Html-------------------------------- <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Map</title> <script src="js/diego.js"></script> <link rel="alternate stylesheet" type="text/css" href="css/diego.css"> <div> <a href="#popupMap" data-rel="popup" data-position-to="window" class="ui-btn ui-corner-all ui-shadow ui-btn-inline">Open Map</a> </div> </head> <body> <div data-role="popup" id="popupMap" data-overlay-theme="a" data-theme="a" data-corners="false" data-tolerance="15,15"> <a href="#" data-rel="back" class="ui-btn ui-btn-b ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a> <iframe src="map.html" width="480" height="320" seamless=""></iframe> </div> </body> </html> -------------------------------------------------JS--------------------------------------------------- // popup examples $( document ).on( "pagecreate", function() { // The window width and height are decreased by 30 to take the tolerance of 15 pixels at each side into account function scale( width, height, padding, border ) { var scrWidth = $( window ).width() - 30, scrHeight = $( window ).height() - 30, ifrPadding = 2 * padding, ifrBorder = 2 * border, ifrWidth = width + ifrPadding + ifrBorder, ifrHeight = height + ifrPadding + ifrBorder, h, w; if ( ifrWidth < scrWidth && ifrHeight < scrHeight ) { w = ifrWidth; h = ifrHeight; } else if ( ( ifrWidth / scrWidth ) > ( ifrHeight / scrHeight ) ) { w = scrWidth; h = ( scrWidth / ifrWidth ) * ifrHeight; } else { h = scrHeight; w = ( scrHeight / ifrHeight ) * ifrWidth; } return { 'width': w - ( ifrPadding + ifrBorder ), 'height': h - ( ifrPadding + ifrBorder ) }; }; $( ".ui-popup iframe" ) .attr( "width", 0 ) .attr( "height", "auto" ); $( "#popupMap iframe" ).contents().find( "#map_canvas" ) .css( { "width" : 0, "height" : 0 } ); $( "#popupMap" ).on({ popupbeforeposition: function() { var size = scale( 480, 320, 0, 1 ), w = size.width, h = size.height; $( "#popupMap iframe" ) .attr( "width", w ) .attr( "height", h ); $( "#popupMap iframe" ).contents().find( "#map_canvas" ) .css( { "width": w, "height" : h } ); }, popupafterclose: function() { $( "#popupMap iframe" ) .attr( "width", 0 ) .attr( "height", 0 ); $( "#popupMap iframe" ).contents().find( "#map_canvas" ) .css( { "width": 0, "height" : 0 } ); } }); });
  21. Boa tarde.. estou alterando um site que está em PHP. Nele tem o jQuery Roundabout onde 3 figuras giram ao clicar nelas. Porém, essas figuras estão na diagonal e quero colocá-las uma ao lado da outra. Não acho o css ou js com as características para mudar.. se clico direto no site para ver o código aparece o element mas não o encontro nos arquivos do site. Alguém pode me dar uma dica de como mudar? segue parte do código JS. (function($) { "use strict"; var defaults, internalData, methods; // add default shape $.extend({ roundaboutShapes: { def: "lazySusan", lazySusan: function (r, a, t) { return { x: Math.sin(r + a), y: (Math.sin(r + 3 * Math.PI / 2 + a) / 8) * t, z: (Math.cos(r + a) + 1) / 2, scale: (Math.sin(r + Math.PI / 2 + a) / 2) + 0.5 }; } } }); defaults = { bearing: 0.0, tilt: 0.0, minZ: 100, maxZ: 280, minOpacity: 0.4, maxOpacity: 1.0, minScale: 0.4, maxScale: 1.0, duration: 600, btnNext: null, btnNextCallback: function() {}, btnPrev: null, btnPrevCallback: function() {}, btnToggleAutoplay: null, btnStartAutoplay: null, btnStopAutoplay: null, easing: "swing", clickToFocus: true, clickToFocusCallback: function() {}, focusBearing: 0.0, shape: "lazySusan", debug: false, childSelector: "li", startingChild: null, reflect: false, floatComparisonThreshold: 0.001, autoplay: false, autoplayDuration: 1000, autoplayPauseOnHover: false, autoplayCallback: function() {}, autoplayInitialDelay: 0, enableDrag: false, dropDuration: 600, dropEasing: "swing", dropAnimateTo: "nearest", dropCallback: function() {}, dragAxis: "x", dragFactor: 4, triggerFocusEvents: true, triggerBlurEvents: true, responsive: false }; internalData = { autoplayInterval: null, autoplayIsRunning: false, autoplayStartTimeout: null, animating: false, childInFocus: -1, touchMoveStartPosition: null, stopAnimation: false, lastAnimationStep: false }; methods = { // starters // ----------------------------------------------------------------------- // init // starts up roundabout init: function(options, callback, relayout) { var settings, now = (new Date()).getTime(); options = (typeof options === "object") ? options : {}; callback = ($.isFunction(callback)) ? callback : function() {}; callback = ($.isFunction(options)) ? options : callback; settings = $.extend({}, defaults, options, internalData); return this .each(function() { // make options var self = $(this), childCount = self.children(settings.childSelector).length, period = 360.0 / childCount, startingChild = (settings.startingChild && settings.startingChild > (childCount - 1)) ? (childCount - 1) : settings.startingChild, startBearing = (settings.startingChild === null) ? settings.bearing : 360 - (startingChild * period), holderCSSPosition = (self.css("position") !== "static") ? self.css("position") : "relative"; self .css({ // starting styles padding: 0, position: holderCSSPosition }) .addClass("roundabout-holder") .data( // starting options "roundabout", $.extend( {}, settings, { startingChild: startingChild, bearing: startBearing, oppositeOfFocusBearing: methods.normalize.apply(null, [settings.focusBearing - 90]), dragBearing: startBearing, period: period } ) ); // unbind any events that we set if we're relaying out if (relayout) { self .unbind(".roundabout") .children(settings.childSelector) .unbind(".roundabout"); } else { // bind responsive action if (settings.responsive) { $(window).bind("resize", function() { methods.stopAutoplay.apply(self); methods.relayoutChildren.apply(self); }); } } // bind click-to-focus if (settings.clickToFocus) { self .children(settings.childSelector) .each(function(i) { $(this) .bind("click.roundabout", function() { var degrees = methods.getPlacement.apply(self, ); if (!methods.isInFocus.apply(self, [degrees])) { methods.stopAnimation.apply($(this)); if (!self.data("roundabout").animating) { methods.animateBearingToFocus.apply(self, [degrees, self.data("roundabout").clickToFocusCallback]); } return false; } }); }); } // bind next buttons if (settings.btnNext) { $(settings.btnNext) .bind("click.roundabout", function() { if (!self.data("roundabout").animating) { methods.animateToNextChild.apply(self, [self.data("roundabout").btnNextCallback]); } return false; }); } // bind previous buttons if (settings.btnPrev) { $(settings.btnPrev) .bind("click.roundabout", function() { methods.animateToPreviousChild.apply(self, [self.data("roundabout").btnPrevCallback]); return false; }); } // bind toggle autoplay buttons if (settings.btnToggleAutoplay) { $(settings.btnToggleAutoplay) .bind("click.roundabout", function() { methods.toggleAutoplay.apply(self); return false; }); } // bind start autoplay buttons if (settings.btnStartAutoplay) { $(settings.btnStartAutoplay) .bind("click.roundabout", function() { methods.startAutoplay.apply(self); return false; }); } // bind stop autoplay buttons if (settings.btnStopAutoplay) { $(settings.btnStopAutoplay) .bind("click.roundabout", function() { methods.stopAutoplay.apply(self); return false; }); } // autoplay pause on hover if (settings.autoplayPauseOnHover) { self .bind("mouseenter.roundabout.autoplay", function() { methods.stopAutoplay.apply(self, [true]); }) .bind("mouseleave.roundabout.autoplay", function() { methods.startAutoplay.apply(self); }); } // drag and drop if (settings.enableDrag) { // on screen if (!$.isFunction(self.drag)) { if (settings.debug) { alert("You do not have the drag plugin loaded."); } } else if (!$.isFunction(self.drop)) { if (settings.debug) { alert("You do not have the drop plugin loaded."); } } else { self .drag(function(e, properties) { var data = self.data("roundabout"), delta = (data.dragAxis.toLowerCase() === "x") ? "deltaX" : "deltaY"; methods.stopAnimation.apply(self); methods.setBearing.apply(self, [data.dragBearing + properties[delta] / data.dragFactor]); }) .drop(function(e) { var data = self.data("roundabout"), method = methods.getAnimateToMethod(data.dropAnimateTo); methods.allowAnimation.apply(self); methods[method].apply(self, [data.dropDuration, data.dropEasing, data.dropCallback]); data.dragBearing = data.period * methods.getNearestChild.apply(self); }); } // on mobile self .each(function() { var element = $(this).get(0), data = $(this).data("roundabout"), page = (data.dragAxis.toLowerCase() === "x") ? "pageX" : "pageY", method = methods.getAnimateToMethod(data.dropAnimateTo); // some versions of IE don't like this if (element.addEventListener) { element.addEventListener("touchstart", function(e) { data.touchMoveStartPosition = e.touches[0] }, false); ; element.addEventListener("touchmove", function(e) { var delta = (e.touches[0] e.preventDefault(); methods.stopAnimation.apply($(this)); methods.setBearing.apply($(this), [data.dragBearing + delta]); }, false); - data.touchMoveStartPosition) / data.dragFactor; element.addEventListener("touchend", function(e) { e.preventDefault(); methods.allowAnimation.apply($(this)); method = methods.getAnimateToMethod(data.dropAnimateTo); methods[method].apply($(this), [data.dropDuration, data.dropEasing, data.dropCallback]); data.dragBearing = data.period * methods.getNearestChild.apply($(this)); }, false); } }); } // start children methods.initChildren.apply(self, [callback, relayout]); }); }, // initChildren // applys settings to child elements, starts roundabout initChildren: function(callback, relayout) { var self = $(this), data = self.data("roundabout"); callback = callback || function() {}; self.children(data.childSelector).each(function(i) { var startWidth, startHeight, startFontSize, degrees = methods.getPlacement.apply(self, ); // on relayout, grab these values from current data if (relayout && $(this).data("roundabout")) { startWidth = $(this).data("roundabout").startWidth; startHeight = $(this).data("roundabout").startHeight; startFontSize = $(this).data("roundabout").startFontSize; } // apply classes and css first $(this) .addClass("roundabout-moveable-item") .css("position", "absolute"); // now measure $(this) .data( "roundabout", { startWidth: startWidth || $(this).width(), startHeight: startHeight || $(this).height(), startFontSize: startFontSize || parseInt($(this).css("font-size"), 10), degrees: degrees, backDegrees: methods.normalize.apply(null, [degrees - 180]), childNumber: i, currentScale: 1, parent: self } ); }); methods.updateChildren.apply(self); // start autoplay if necessary if (data.autoplay) { data.autoplayStartTimeout = setTimeout(function() { methods.startAutoplay.apply(self); }, data.autoplayInitialDelay); } self.trigger('ready'); callback.apply(self); return self; }, // positioning // ----------------------------------------------------------------------- // updateChildren // move children elements into their proper locations updateChildren: function() { return this .each(function() { var self = $(this), data = self.data("roundabout"), inFocus = -1, info = { bearing: data.bearing, tilt: data.tilt, stage: { width: Math.floor($(this).width() * 0.9), height: Math.floor($(this).height() * 0.9) }, animating: data.animating, inFocus: data.childInFocus, focusBearingRadian: methods.degToRad.apply(null, [data.focusBearing]), shape: $.roundaboutShapes[data.shape] || $.roundaboutShapes[$.roundaboutShapes.def] }; // calculations info.midStage = { width: info.stage.width / 2, height: info.stage.height / 2 }; info.nudge = { width: info.midStage.width + (info.stage.width * 0.05), height: info.midStage.height + (info.stage.height * 0.05) }; info.zValues = { min: data.minZ, max: data.maxZ, diff: data.maxZ - data.minZ }; info.opacity = { min: data.minOpacity, max: data.maxOpacity, diff: data.maxOpacity - data.minOpacity }; info.scale = { min: data.minScale, max: data.maxScale, diff: data.maxScale - data.minScale }; // update child positions self.children(data.childSelector) .each(function(i) { if (methods.updateChild.apply(self, [$(this), info, i, function() { $(this).trigger('ready'); }]) && (!info.animating || data.lastAnimationStep)) { inFocus = i; $(this).addClass("roundabout-in-focus"); } else { $(this).removeClass("roundabout-in-focus"); } }); if (inFocus !== info.inFocus) { // blur old child if (data.triggerBlurEvents) { self.children(data.childSelector) .eq(info.inFocus) .trigger("blur"); } data.childInFocus = inFocus; if (data.triggerFocusEvents && inFocus !== -1) { // focus new child self.children(data.childSelector) .eq(inFocus) .trigger("focus"); } } self.trigger("childrenUpdated"); }); }, // updateChild // repositions a child element into its new position updateChild: function(childElement, info, childPos, callback) { var factors, self = this, child = $(childElement), data = child.data("roundabout"), out = [], rad = methods.degToRad.apply(null, [(360.0 - data.degrees) + info.bearing]); callback = callback || function() {}; // adjust radians to be between 0 and Math.PI * 2 rad = methods.normalizeRad.apply(null, [rad]); // get factors from shape factors = info.shape(rad, info.focusBearingRadian, info.tilt); // correct factors.scale = (factors.scale > 1) ? 1 : factors.scale; factors.adjustedScale = (info.scale.min + (info.scale.diff * factors.scale)).toFixed(4); factors.width = (factors.adjustedScale * data.startWidth).toFixed(4); factors.height = (factors.adjustedScale * data.startHeight).toFixed(4); // update item child .css({ left: ((factors.x * info.midStage.width + info.nudge.width) - factors.width / 2.0).toFixed(0) + "px", top: ((factors.y * info.midStage.height + info.nudge.height) - factors.height / 2.0).toFixed(0) + "px", width: factors.width + "px", height: factors.height + "px", opacity: (info.opacity.min + (info.opacity.diff * factors.scale)).toFixed(2), zIndex: Math.round(info.zValues.min + (info.zValues.diff * factors.z)), fontSize: (factors.adjustedScale * data.startFontSize).toFixed(1) + "px" }); data.currentScale = factors.adjustedScale; // for debugging purposes if (self.data("roundabout").debug) { out.push("<div style=\"font-weight: normal; font-size: 10px; padding: 2px; width: " + child.css("width") + "; background-color: #ffc;\">"); out.push("<strong style=\"font-size: 12px; white-space: nowrap;\">Child " + childPos + "</strong><br />"); out.push("<strong>left:</strong> " + child.css("left") + "<br />"); out.push("<strong>top:</strong> " + child.css("top") + "<br />"); out.push("<strong>width:</strong> " + child.css("width") + "<br />"); out.push("<strong>opacity:</strong> " + child.css("opacity") + "<br />"); out.push("<strong>height:</strong> " + child.css("height") + "<br />"); out.push("<strong>z-index:</strong> " + child.css("z-index") + "<br />"); out.push("<strong>font-size:</strong> " + child.css("font-size") + "<br />"); out.push("<strong>scale:</strong> " + child.data("roundabout").currentScale); out.push("</div>"); child.html(out.join("")); } // trigger event child.trigger("reposition"); // callback callback.apply(self); return methods.isInFocus.apply(self, [data.degrees]); }, // manipulation // ----------------------------------------------------------------------- // setBearing // changes the bearing of the roundabout setBearing: function(bearing, callback) { callback = callback || function() {}; bearing = methods.normalize.apply(null, [bearing]); this .each(function() { var diff, lowerValue, higherValue, self = $(this), data = self.data("roundabout"), oldBearing = data.bearing; // set bearing data.bearing = bearing; self.trigger("bearingSet"); methods.updateChildren.apply(self); // not animating? we're done here diff = Math.abs(oldBearing - bearing); if (!data.animating || diff > 180) { return; } // check to see if any of the children went through the back diff = Math.abs(oldBearing - bearing); self.children(data.childSelector).each(function(i) { var eventType; if (methods.isChildBackDegreesBetween.apply($(this), [bearing, oldBearing])) { eventType = (oldBearing > bearing) ? "Clockwise" : "Counterclockwise"; $(this).trigger("move" + eventType + "ThroughBack"); } }); }); // call callback if one was given callback.apply(this); return this; }, // adjustBearing // change the bearing of the roundabout by a given degree adjustBearing: function(delta, callback) { callback = callback || function() {}; if (delta === 0) { return this; } this .each(function() { methods.setBearing.apply($(this), [$(this).data("roundabout").bearing + delta]); }); callback.apply(this); return this; }, // setTilt // changes the tilt of the roundabout setTilt: function(tilt, callback) { callback = callback || function() {}; this .each(function() { $(this).data("roundabout").tilt = tilt; methods.updateChildren.apply($(this)); }); // call callback if one was given callback.apply(this); return this; }, // adjustTilt // changes the tilt of the roundabout adjustTilt: function(delta, callback) { callback = callback || function() {}; this .each(function() { methods.setTilt.apply($(this), [$(this).data("roundabout").tilt + delta]); }); callback.apply(this); return this; }, // animation // ----------------------------------------------------------------------- // animateToBearing // animates the roundabout to a given bearing, all animations come through here animateToBearing: function(bearing, duration, easing, passedData, callback) { var now = (new Date()).getTime(); callback = callback || function() {}; // find callback function in arguments if ($.isFunction(passedData)) { callback = passedData; passedData = null; } else if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } this .each(function() { var timer, easingFn, newBearing, self = $(this), data = self.data("roundabout"), thisDuration = (!duration) ? data.duration : duration, thisEasingType = (easing) ? easing : data.easing || "swing"; // is this your first time? if (!passedData) { passedData = { timerStart: now, start: data.bearing, totalTime: thisDuration }; } // update the timer timer = now - passedData.timerStart; if (data.stopAnimation) { methods.allowAnimation.apply(self); data.animating = false; return; } // we need to animate more if (timer < thisDuration) { if (!data.animating) { self.trigger("animationStart"); } data.animating = true; if (typeof $.easing.def === "string") { easingFn = $.easing[thisEasingType] || $.easing[$.easing.def]; newBearing = easingFn(null, timer, passedData.start, bearing - passedData.start, passedData.totalTime); } else { newBearing = $.easing[thisEasingType]((timer / passedData.totalTime), timer, passedData.start, bearing - passedData.start, passedData.totalTime); } // fixes issue #24, animation changed as of jQuery 1.7.2 if (methods.compareVersions.apply(null, [$().jquery, "1.7.2"]) >= 0) { newBearing = passedData.start + ((bearing - passedData.start) * newBearing); } newBearing = methods.normalize.apply(null, [newBearing]); data.dragBearing = newBearing; methods.setBearing.apply(self, [newBearing, function() { setTimeout(function() { // done with a timeout so that each step is displayed methods.animateToBearing.apply(self, [bearing, thisDuration, thisEasingType, passedData, callback]); }, 0); }]); // we're done animating } else { data.lastAnimationStep = true; bearing = methods.normalize.apply(null, [bearing]); methods.setBearing.apply(self, [bearing, function() { self.trigger("animationEnd"); }]); data.animating = false; data.lastAnimationStep = false; data.dragBearing = bearing; callback.apply(self); } }); return this; }, // animateToNearbyChild // animates roundabout to a nearby child animateToNearbyChild: function(passedArgs, which) { var duration = passedArgs[0], easing = passedArgs[1], callback = passedArgs[2] || function() {}; // find callback if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } return this .each(function() { var j, range, self = $(this), data = self.data("roundabout"), bearing = (!data.reflect) ? data.bearing % 360 : data.bearing, length = self.children(data.childSelector).length; if (!data.animating) { // reflecting, not moving to previous || not reflecting, moving to next if ((data.reflect && which === "previous") || (!data.reflect && which === "next")) { // slightly adjust for rounding issues bearing = (Math.abs(bearing) < data.floatComparisonThreshold) ? 360 : bearing; // clockwise for (j = 0; j < length; j += 1) { range = { lower: (data.period * j), upper: (data.period * (j + 1)) }; range.upper = (j === length - 1) ? 360 : range.upper; if (bearing <= Math.ceil(range.upper) && bearing >= Math.floor(range.lower)) { if (length === 2 && bearing === 360) { methods.animateToDelta.apply(self, [-180, duration, easing, callback]); } else { methods.animateBearingToFocus.apply(self, [range.lower, duration, easing, callback]); } break; } } } else { // slightly adjust for rounding issues bearing = (Math.abs(bearing) < data.floatComparisonThreshold || 360 - Math.abs(bearing) < data.floatComparisonThreshold) ? 0 : bearing; // counterclockwise for (j = length - 1; j >= 0; j -= 1) { range = { lower: data.period * j, upper: data.period * (j + 1) }; range.upper = (j === length - 1) ? 360 : range.upper; if (bearing >= Math.floor(range.lower) && bearing < Math.ceil(range.upper)) { if (length === 2 && bearing === 360) { methods.animateToDelta.apply(self, [180, duration, easing, callback]); } else { methods.animateBearingToFocus.apply(self, [range.upper, duration, easing, callback]); } break; } } } } }); }, // animateToNearestChild // animates roundabout to the nearest child animateToNearestChild: function(duration, easing, callback) { callback = callback || function() {}; // find callback if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } return this .each(function() { var nearest = methods.getNearestChild.apply($(this)); methods.animateToChild.apply($(this), [nearest, duration, easing, callback]); }); }, // animateToChild // animates roundabout to a given child position animateToChild: function(childPosition, duration, easing, callback) { callback = callback || function() {}; // find callback if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } return this .each(function() { var child, self = $(this), data = self.data("roundabout"); if (data.childInFocus !== childPosition && !data.animating) { child = self.children(data.childSelector).eq(childPosition); methods.animateBearingToFocus.apply(self, [child.data("roundabout").degrees, duration, easing, callback]); } }); }, // animateToNextChild // animates roundabout to the next child animateToNextChild: function(duration, easing, callback) { return methods.animateToNearbyChild.apply(this, [arguments, "next"]); }, // animateToPreviousChild // animates roundabout to the preious child animateToPreviousChild: function(duration, easing, callback) { return methods.animateToNearbyChild.apply(this, [arguments, "previous"]); }, // animateToDelta // animates roundabout to a given delta (in degrees) animateToDelta: function(degrees, duration, easing, callback) { callback = callback || function() {}; // find callback if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } return this .each(function() { var delta = $(this).data("roundabout").bearing + degrees; methods.animateToBearing.apply($(this), [delta, duration, easing, callback]); }); }, // animateBearingToFocus // animates roundabout to bring a given angle into focus animateBearingToFocus: function(degrees, duration, easing, callback) { callback = callback || function() {}; // find callback if ($.isFunction(easing)) { callback = easing; easing = null; } else if ($.isFunction(duration)) { callback = duration; duration = null; } return this .each(function() { var delta = $(this).data("roundabout").bearing - degrees; delta = (Math.abs(360 - delta) < Math.abs(delta)) ? 360 - delta : -delta; delta = (delta > 180) ? -(360 - delta) : delta; if (delta !== 0) { methods.animateToDelta.apply($(this), [delta, duration, easing, callback]); } }); }, // stopAnimation // if an animation is currently in progress, stop it stopAnimation: function() { return this .each(function() { $(this).data("roundabout").stopAnimation = true; }); }, // allowAnimation // clears the stop-animation hold placed by stopAnimation allowAnimation: function() { return this .each(function() { $(this).data("roundabout").stopAnimation = false; }); }, // autoplay // ----------------------------------------------------------------------- // startAutoplay // starts autoplaying this roundabout startAutoplay: function(callback) { return this .each(function() { var self = $(this), data = self.data("roundabout"); callback = callback || data.autoplayCallback || function() {}; clearInterval(data.autoplayInterval); data.autoplayInterval = setInterval(function() { methods.animateToNextChild.apply(self, [callback]); }, data.autoplayDuration); data.autoplayIsRunning = true; self.trigger("autoplayStart"); }); }, // stopAutoplay // stops autoplaying this roundabout stopAutoplay: function(keepAutoplayBindings) { return this .each(function() { clearInterval($(this).data("roundabout").autoplayInterval); $(this).data("roundabout").autoplayInterval = null; $(this).data("roundabout").autoplayIsRunning = false; // this will prevent autoplayPauseOnHover from restarting autoplay if (!keepAutoplayBindings) { $(this).unbind(".autoplay"); } $(this).trigger("autoplayStop"); }); }, // toggleAutoplay // toggles autoplay pause/resume toggleAutoplay: function(callback) { return this .each(function() { var self = $(this), data = self.data("roundabout"); callback = callback || data.autoplayCallback || function() {}; if (!methods.isAutoplaying.apply($(this))) { methods.startAutoplay.apply($(this), [callback]); } else { methods.stopAutoplay.apply($(this), [callback]); } }); }, // isAutoplaying // is this roundabout currently autoplaying? isAutoplaying: function() { return (this.data("roundabout").autoplayIsRunning); }, // changeAutoplayDuration // stops the autoplay, changes the duration, restarts autoplay changeAutoplayDuration: function(duration) { return this .each(function() { var self = $(this), data = self.data("roundabout"); data.autoplayDuration = duration; if (methods.isAutoplaying.apply(self)) { methods.stopAutoplay.apply(self); setTimeout(function() { methods.startAutoplay.apply(self); }, 10); } }); }, // helpers // ----------------------------------------------------------------------- // normalize // regulates degrees to be >= 0.0 and < 360 normalize: function(degrees) { var inRange = degrees % 360.0; return (inRange < 0) ? 360 + inRange : inRange; }, // normalizeRad // regulates radians to be >= 0 and < Math.PI * 2 normalizeRad: function(radians) { while (radians < 0) { radians += (Math.PI * 2); } while (radians > (Math.PI * 2)) { radians -= (Math.PI * 2); } return radians; }, // isChildBackDegreesBetween // checks that a given child's backDegrees is between two values isChildBackDegreesBetween: function(value1, value2) { var backDegrees = $(this).data("roundabout").backDegrees; if (value1 > value2) { return (backDegrees >= value2 && backDegrees < value1); } else { return (backDegrees < value2 && backDegrees >= value1); } }, // getAnimateToMethod // takes a user-entered option and maps it to an animation method getAnimateToMethod: function(effect) { effect = effect.toLowerCase(); if (effect === "next") { return "animateToNextChild"; } else if (effect === "previous") { return "animateToPreviousChild"; } // default selection return "animateToNearestChild"; }, // relayoutChildren // lays out children again with new contextual information relayoutChildren: function() { return this .each(function() { var self = $(this), settings = $.extend({}, self.data("roundabout")); settings.startingChild = self.data("roundabout").childInFocus; methods.init.apply(self, [settings, null, true]); }); }, // getNearestChild // gets the nearest child from the current bearing getNearestChild: function() { var self = $(this), data = self.data("roundabout"), length = self.children(data.childSelector).length; if (!data.reflect) { return ((length) - (Math.round(data.bearing / data.period) % length)) % length; } else { return (Math.round(data.bearing / data.period) % length); } }, // degToRad // converts degrees to radians degToRad: function(degrees) { return methods.normalize.apply(null, [degrees]) * Math.PI / 180.0; }, // getPlacement // returns the starting degree for a given child getPlacement: function(child) { var data = this.data("roundabout"); return (!data.reflect) ? 360.0 - (data.period * child) : data.period * child; }, // isInFocus // is this roundabout currently in focus? isInFocus: function(degrees) { var diff, self = this, data = self.data("roundabout"), bearing = methods.normalize.apply(null, [data.bearing]); degrees = methods.normalize.apply(null, [degrees]); diff = Math.abs(bearing - degrees); // this calculation gives a bit of room for javascript float rounding // errors, it looks on both 0deg and 360deg ends of the spectrum return (diff <= data.floatComparisonThreshold || diff >= 360 - data.floatComparisonThreshold); }, // getChildInFocus // returns the current child in focus, or false if none are in focus getChildInFocus: function() { var data = $(this).data("roundabout"); return (data.childInFocus > -1) ? data.childInFocus : false; }, // compareVersions // compares a given version string with another compareVersions: function(baseVersion, compareVersion) { var i, base = baseVersion.split(/\./i), compare = compareVersion.split(/\./i), maxVersionSegmentLength = (base.length > compare.length) ? base.length : compare.length; for (i = 0; i <= maxVersionSegmentLength; i++) { if (base && !compare && parseInt(base, 10) !== 0) { // base is higher return 1; } else if (compare && !base && parseInt(compare, 10) !== 0) { // compare is higher return -1; } else if (base === compare) { // these are the same, next continue; } if (base && compare) { if (parseInt(base, 10) > parseInt(compare, 10)) { // base is higher return 1; } else { // compare is higher return -1; } } } // nothing was triggered, versions are the same return 0; } }; // start the plugin $.fn.roundabout = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || $.isFunction(method) || !method) { return methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist for jQuery.roundabout."); } }; })(jQuery);
  22. Aqui está o código: <html> <head> <title>Formulário</title> <script> function verificar (form) { if nome="not null" || senha="not null" && senha>="4" alert("ok!") else alert ("ERROR") } </script> </head> <body> Preencha o formulário abaixo: <br> <form name="teste" action="" method="get"> Nome: <input type="text" name="nome"> <p> Senha:<input type="text" name="senha"> <p> <input type="button" name="button" Value="Verificar" onClick="verificar (this.form)"> </form> </body> </html> Eu sei que é BEM simples, mas é tipo, meu primeiro script... Por algum motivo, não consigo realizar a função "verificar" quando clico no botão. Acho que muitos conseguem me ajudar, por que é algo bem básico, então... Obrigada mesmo assim!
  23. Queria uma ajuda para que quando o usuário selecionasse o erro, o window fechasse o código é o seguinte: reportar.php <div class="relatarErro"> <div class="re-btnFechar">FECHAR</div> <div class="re-titulo"><span>Mãos Armadas Dublado</span> está com erro?</div> <div class="re-texto">Devemos lembrar que este formulário é somente para uma causa real de erro. Verifique as informações do filme antes para constatar a qualidade e o modo de linguagem. Obrigado pela colaboração.</div> <input type="hidden" name="pagina" value="http://www.megafilmesonlinehd.com/assistir-maos-armadas-dublado-online.html" /> <div class="re-form"> <div class="ref-select"> <select name="selectErro" class="re-selectErro" required> <option selected="selected" value="">Selecione o Erro</option> <option value="Video Deletado">Video Deletado</option> <option value="Problemas de Imagem">Problemas de Imagem</option> <option value="Problemas de Som">Problemas de Som</option> <option value="Problemas na Legenda">Problemas na Legenda</option> <option value="Video com Falhas">Video com Falhas</option> <option value="Spam nos Comentários">Spam nos Comentários</option> <option value="Informações Incorretas">Informações Incorretas</option> </select> </div> <button name="btnErro" class="re-btnErro">Relatar Erro</button> </div> </div> <div class="s-mascara"></div> relataerro.php <? if($_POST['btnErro']){ $erroFilme = $_POST["titulo"]; $titulo = $_POST["titulo"]; $pagina = $_POST["pagina"]; } else{ $query = "INSERT INTO report (titulo, pagina, erroFilme) VALUES ('$titulo','$pagina', '$erroFilme')"; $result = mysql_query($query) or die ("Erro ao Inserir"); } ?>e o js.js $(function(){ resizeWindow(); $(window).on("resize", function() { setInterval(resizeWindow(), 10); }); // Relatar Erro $('a.sbr-reportar').click(function(){ $('.s-mascara').css('display','block'); $('.relatarErro').css('display','block'); $('.sbr-btns .sbr-btn.sbrb-luz, ul.sp-itens li').css('z-index', '10'); }); $('.re-btnErro').click(function (){ var erroFilme = $('.re-selectErro').val(); var tituloErro = $('.relatarErro .re-titulo span').html(); var paginaErro = location.pathname; if(erroFilme != undefined && erroFilme != ''){ $.post('relatarerro.php', { erroFilme: erroFilme, titulo: tituloErro, pagina: paginaErro }, function (dados) { alert('Filme reportado com sucesso. Agradecemos a sua ajuda.'); $('.s-mascara').css('display','none'); $('.relatarErro').css('display','none'); $('.sbr-btns .sbr-btn.sbrb-luz, ul.sp-itens li').css('z-index', '99'); }); } else { alert('Selecione o Erro referente ao filme para poder reporta-lo!'); } }); $('.relatarErro .re-btnFechar').click(function () { $('.s-mascara').css('display','none'); $('.relatarErro').css('display','none'); $('.sbr-btns .sbr-btn.sbrb-luz, ul.sp-itens li').css('z-index', '99'); }); }); Creio que o erro deve está no relataerro.php porque quando não seleciona nenhum erro ele da o aviso, mas quando seleciona não da resultado nenhum, alguém pode me ajudar ?
  24. alguém consegue fazer um código com estes dados? O candidatos; Candidato A candidato B candidato C Candidato D. para cada voto em C, A recebe um voto; para cada voto em D, A recebe um voto; para cada voto em A, apenas A RECEBE O VOTO; PARA CADA voto em B, apenas B recebe o voto;
  25. Olá pessoal, boa noite Estou quebrando a cabeça pra achar na internet mas tá dificil ai achei o forum aqui e vi muitos conteudos produtivos... Minha dúvida é a seguinte: Uma textarea onde digita os numeros de um boleto, a partir dele quando clicar no botao gerar boleto, ele vai mostrar o valor dele, a data de vencimento e o banco, porem ele não deu nenhuma dica de como fazer esse bendito programa... já varri a internet atras de algo que possa ajudar mas foi em vão. Se alguém tiver alguma ideia de como fazer essa magica por favor, da uma luz ae kkkk. Obrigado desde já
×
×
  • Criar Novo...