Ir para conteúdo
Fórum Script Brasil
  • 0

1º Desafio - Desafio/Ranking/Códigos


Crystian

Pergunta

Beleza galera! O negócio é o seguinte, estamos (Eu e o Illidan) lançando o primeiro desafio JavaScript/CSS/DHTML.

Vamos começar com um script simples, já que scripts longos geralmente causam repúdio, além do que agente não sabe como anda o conhecimento da galera em JS.

Vamos ao desafio:

- Criar uma página html que contenha:

- um formulário

- um objeto Select (MenuList, Combobox, JumpMenu como vocês quiserem chamar)

Neste Select haverá duas opções:

- Desafio

- Outros

A opção outros deverá estar destacada da forma q vocês quiserem (Negrito, cor de fundo). Mas deve estar destacada.

Quando for selecionado a opção "outros" deverá aparecer uma mensagem pedindo q o usuário informe uma opção para ser inserida no Select. A opção que o usuário escolher deverá ser acrescentada no final do Select (já selecionando essa opção), mostrando assim 3 opções. Se ele selecionar de novo a opção outros, deverá novamente pedir o campo q o usuário deseja inserir no Select e inseri-lo no final(já selecionando essa opção) e assim sucessivamente. É aconselhável que se crie uma função JS para controlar isso.

Este Select deverá estar centralizado na página, sem a ajuda de <br>, somente com CSS.

Lembrando sempre q infelizmente não existe padrão, ou melhor, o padrão não é totalmente seguido pelos principais navegadores(IE) o que torna nossa vida um pouco complicada. Então esse código DEVE funcionar nos dois principais navegadores (IE4+ e NN4+). A intenção é q futuramente vocês possam usar a função e se ela não funcionar em alguns navegadores ou versões ficaria meio complicado.

Viram?! Simples não?!

O objetivo desse desafio é fazer com que se criem novos códigos e se aprenda um pouco mais dessa linguagem tão interessante e criativa q é o JS. Muitas vezes é fácil pegar um código pronto colocar na página e tah tudo beleza, só q quando os problemas acontecem, ficamos a mercê da ajuda alheia.

Quem terminar o código, envie uma PM para mim ou para o Illidan, que assim q agente testar nos dois principais browsers agente atualiza o ranking.

POR FAVOR NÃO POSTEM O CÓDIGO AQUI E NEM EM OUTROS POSTS. SOMENTE POR PM(Mensagem Privada para mim ou o Illidan)

O desafio terminará no dia 25 de novembro, sendo postado o código correto.

Desejamos Boa Sorte a todos.

Abraço

Veja mais:

Equipe de Moderação JS/CSS/DHTML

Editado por OSJunior
Link para o comentário
Compartilhar em outros sites

23 respostass a esta questão

Posts Recomendados

  • 0

De preferência com CSS, é bem simples, procura pelo forum q tu acha. A intenção é variar o conhecimento da galera. Centralizar com tabela ou a tag center é simples. Queremos q todos aprendam novos caminhos q poderão ser úteis num futuro próximo...

Falei bonito....hehehehe....

Quando acabar manda uma PM pra mim q se funcionar atualizo o ranking...

Abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Ranking do 1º Desafio de Javascript/CSS/DHTML

Ao término do desafio, postaremos aqui os códigos de cada usuário.

O ranking está organizado por ordem de entrega do script.

PS: Desculpa Illidan e Renan, mas o felipe tinha me entregue antes o código, e como não pude testar o código dele no Netscape, não tinha atualizado o Ranking. Parabéns felipe

Editado por Crystian
Link para o comentário
Compartilhar em outros sites

  • 0

Pessoal, pra ficar mais organizado, criei um tópico separado pra postar o ranking e os scripts dos usuários (ao término do desafio).

Parabéns ao Error404 e renan_doidera! vocês já estão no ranking...

Abraços!

Link para o comentário
Compartilhar em outros sites

  • 0
Não acho que seja falta de conhecimento, tá mais pra falta de interesse, senão eles estariam postando pedindo ajuda, não acha? ohmy.gif

estou fazendo de tudo pra divulgar, mas parece que não está rolando... sad.gif

Pois é mano..

Eu fiquei um tempinho afastado do forum.. das seções em geral..

Ainda não acabei os rolos por aqui..

Quando acabar, vou ver se consigo, com meu pouquíssimo conhecimento de javascript, montar o codigo

O tópico ta pendurado na seção asp tb ...

Mas não sei se o pessoal é bom em js, hehe

T+

Link para o comentário
Compartilhar em outros sites

  • 0
Não acho que seja falta de conhecimento, tá mais pra falta de interesse, senão eles estariam postando pedindo ajuda, não acha? ohmy.gif

estou fazendo de tudo pra divulgar, mas parece que não está rolando... sad.gif

Pois é mano..

Eu fiquei um tempinho afastado do forum.. das seções em geral..

Ainda não acabei os rolos por aqui..

Quando acabar, vou ver se consigo, com meu pouquíssimo conhecimento de javascript, montar o codigo

O tópico ta pendurado na seção asp tb ...

Mas não sei se o pessoal é bom em js, hehe

T+

Gente, valeu mesmo pela ajuda,(seja colocando links, seja divulgando, seja participando) é muito importante pra comunidade essa ajuda q agente tah recebendo aqui, não só nesse desafio.

Agente tah se esforçando pra fazer o pessoal dar uma olhada no JS, tentar aprender e se não aprender pelo menos tentar que é o principal objetivo desse desafio. Mas se o pessoal anda meio sem tempo, temos q tentar entender isso. Mas apesar de tudo vamos continuar a tentar incentivar o pessoal a fazer seus proprios codigos.

Mais uma vez muito obrigado!!!

Abraço

Crystian

Link para o comentário
Compartilhar em outros sites

  • 0

Desafio encerrado, galera! Vou começar a postar os códigos:

Este era o código que eu e o Crystian utilizamos de base para o desafio. Nós utilizamos o mesmo valor para o "value" e o "text" do objeto <option>, pois imaginamos que numa situação real, um usuário comum não saberia diferenciar. Mas aceitamos normalmente os códigos que permitiam definir um valor separado para cada parâmetro.

<html>
<head>
<title>1&ordm; Desafio de Javascript/CSS/DHTML</title>
<script type="text/javascript">

function verify(idSelect) {
    var objSel = getObject(idSelect);
    if (objSel != null) {
        if (objSel.options[objSel.selectedIndex].value == 'outros') {
            var newOpt = prompt('Digite a nova opção', '');
            if (newOpt == "") {
                alert("Você deve preencher os dois campos solicitados");
            } else {
                addOption(idSelect, newOpt);
            }
        }
    }
}

function addOption(idSelect, newOpt) {
    var objSel = getObject(idSelect);
    if (objSel != null) {
        var obj = new Option();
        objSel.options.add(obj);
        obj.text = newOpt;
        obj.value = newOpt;
        obj.selected = true;
    }
}

function getObject(id) {
    var obj = document.getElementById(id);
    if (obj == null || obj == "") {
        return null;
    }
    return obj;
}

</script>
<style type="text/css">
<!--
#sel {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    margin: -10px 0px 0px -100px;
}
-->
</style>
</head>

<body>

<select name="sel" id="sel" onchange="verify(this.id);">
  <option value="</span>">-- Selecione uma opção --</option>
  <option value="1">Opção 1</option>
  <option value="2">Opção 2</option>
  <option value="outros" style="background-color: #ffcccc;">Outros</option>
</select>

</body>
</html>
Error404 http://error404.infinitehost.com.br/challenges/js/
<html onResize='change_pos'>
<head>
<title>JS/CSS/DHTML 1st Challenge ©Error404</title>
<script>
function window_show(e){
	if(e.options[e.selectedIndex].value=="add"){
  document.getElementById('divOption').style.left = document.getElementById('divSelect').offsetLeft+select_offsetLeft-11;
  document.getElementById('divOption').style.top = document.getElementById('divSelect').offsetTop+select_offsetTop-60+180;
  document.getElementById('divOption').style.display = 'block';
  e.style.display = 'none';
  document.formB.optText.focus();
  window.setTimeout("document.getElementById('tableMother').onclick = window_hide",200);
	}
	else{
  window.defaultStatus = "value: "+e.options[e.selectedIndex].value+"    text: "+e.options[e.selectedIndex].text;
	}
}

function window_hide(){
	document.getElementById('divOption').style.display = 'none';
	document.formA.select.style.display = 'inline';
	document.formA.select.options[document.formA.select.options.length-2].selected = true;
	document.getElementById('tableMother').onclick = null;
}

function error_show(e){
	document.getElementById('divError').style.left = document.getElementById('divSelect').offsetLeft;
	document.getElementById('divError').style.top = document.getElementById('divSelect').offsetTop;
	document.getElementById('divError').style.display = 'block';
	document.getElementById('span'+e).style.display = 'inline';
	document.getElementById('btnError').onclick = function temp(){ error_hide(e);};
	document.getElementById('tableMother').onclick = null;
}

function error_hide(e){
	document.getElementById('span'+e).style.display = 'none';
	document.getElementById('divError').style.display = 'none';
	document.getElementById('tableMother').onclick = window_hide;
	field = (e=="Both")? document.formB.optText: eval('document.formB.opt'+e);
	field.focus();
	field.select();
}


function add_opt(text,value){
	if(text.replace(/^\s+|\s+$/g, '')=='</span>' && value.replace(/^\s+|\s+$/g, '')==''){ error_show('Both'); return false;} 
	else if(text.replace(/^\s+|\s+$/g, '')==''){ error_show('Text'); return false;}
	else if(value.replace(/^\s+|\s+$/g, '')==''){ error_show('Value'); return false;}
	document.formA.select.options[document.formA.select.options.length] = new Option('+ adicionar','add');
	document.formA.select.options[document.formA.select.options.length-1].style.color = '#FBF5F5';
	document.formA.select.options[document.formA.select.options.length-1].style.backgroundColor = '#3399CC';
	document.formA.select.options[document.formA.select.options.length-2] = new Option("? "+text,value,false,true);
	document.formB.optText.value = "";
	document.formB.optValue.value = "";
	window.defaultStatus = "value: "+document.formA.select.options[document.formA.select.selectedIndex].value+"    text: "+document.formA.select.options[document.formA.select.selectedIndex].text;
	window_hide();
}

function repositionate(){
	if(document.getElementById('divOption').style.display != 'none'){
  document.getElementById('divOption').style.left = document.getElementById('divSelect').offsetLeft+select_offsetLeft-11;
  document.getElementById('divOption').style.top = document.getElementById('divSelect').offsetTop+select_offsetTop-60+180;
  if(document.getElementById('divError').style.display != 'none'){
   document.getElementById('divError').style.left = document.getElementById('divSelect').offsetLeft;
   document.getElementById('divError').style.top = document.getElementById('divSelect').offsetTop;
  }
	}
}

window.onresize = repositionate;
<<<span style='color:blue'>span style='color:blue'>/script>
</head>
<body bgcolor='#7DA7D9' topmargin='0' bottommargin='0' leftmargin='0' rightmargin='0'>

<table id='tableMother' border='0' cellspacing='0' cellpadding='0' style='position: absolute; z-index: 1; width: 100%; height: 100%; top: 0px; left: 0px;'>
<tr><td style='vertical-align: middle;' align='center'>
  <form name='formA'>
    <div id='divSelect' style='width: 502px; height: 282px;'>
      <table border='0' cellspacing='0' cellpadding='0' style='background-image: url(layout.gif); height: 280px; width: 500px;'>
      <tr><td height='180'></td></tr>
      <tr>
      <td style='text-align: center; vertical-align: top; padding-left: 65px;'>
        <select name='select' style='font-weight: bold; font-family: verdana; font-size: 20px; width: 160px;' onChange='window_show(this); return true;'>
          <option value='challenge' SELECTED>? desafio</option>
          <option value='add' style='color: #FBF5F5; background-color: #3399CC'>+ adicionar</option>
        </select>
      </td></tr>
      </table>
    </div>
  </form>
</td></tr>
</table>

<div id='divOption' style='position: absolute; z-index: 2; width: 180px; height: 152px; display: none;'>
	<table border='0' cellspacing='0' cellpadding='0' style='background-image: url(window.gif); height: 152px; width: 180px;'>
	<tr><td style='height: 45px;' colspan='5'><img src='spacer.gif' style='height: 45px;'></td></tr>
	<form name='formB'>
	<tr>
  <td width='8' style='height: 24px;'></td>
  <td style='height: 24px; width: 55px; font-size: 9pt; font-family: verdana; font-weight: bold; text-align: center; vertical-align: middle;'>text:</td>
  <td style='height: 24px; width: 109px; text-align: left; vertical-align: middle;' colspan='2'><input type='text' name='optText' style='height: 20px; width: 100px; font-size: 9pt; font-family: verdana; font-weight: bold;' maxlength='15'></td>
  <td width='8' style='height: 24px;'></td>
	</tr>
	<tr><td style='height: 4px;' colspan='5'><img src='spacer.gif' style='height: 4px;'></td></tr>
	<tr>
  <td width='8' style='height: 24px;'></td>
  <td style='height: 24px; width: 55px; font-size: 9pt; font-family: verdana; font-weight: bold; text-align: center; vertical-align: middle;'>value:</td>
  <td style='height: 24px; width: 109px; text-align: left; vertical-align: middle;' colspan='2'><input type='text' name='optValue' style='height: 20px; width: 100px; font-size: 9pt; font-family: verdana; font-weight: bold;' maxlength='15'></td>
  <td width='8' style='height: 24px;'></td>
	</tr>
	<tr><td style='height: 19px;' colspan='5'><img src='spacer.gif' style='height: 19px;'></td></tr>
	<tr>
  <td width='8' style='height: 24px;'></td>
  <td valign='top' style='height: 24px; width: 82px;' align='left' colspan='2'><img src='btn_make_up.gif' onMouseDown='this.src="btn_make_down.gif";' onMouseUp='this.src="btn_make_up.gif";' onClick='add_opt(document.formB.optText.value,document.formB.optValue.value)'; border='0' style='height: 24px; width: 79px; cursor: pointer;'></td>
  <td valign='top' style='height: 24px; width: 82px;' align='right'><img src='btn_cancel_up.gif' onMouseDown='this.src="btn_cancel_down.gif";' onMouseUp='this.src="btn_cancel_up.gif";' onClick='window_hide();' border='0'style='height: 24px; width: 79px; cursor: pointer;'></td>
  <td width='8' style='height: 24px;'></td>
	</tr>
	<tr>
  <td width='8' style='height: 12px;'></td>
  <td width='55' style='height: 12px;'><img src='spacer.gif' style='height: 12px;'></td>
  <td width='27' style='height: 12px;'></td>
  <td width='82' style='height: 12px;'></td>
  <td width='8' style='height: 12px;'></td>
	</tr>
	</form>
	</table>
</div>

<div id='divError' style='position: absolute; z-index: 3; width: 500px; height: 280px; display: none;'>
	<table border='0' cellspacing='0' cellpadding='0' style='height: 280px; width: 500px;'>
	<tr><td height='140'></td></tr>
	<tr>
  <td style='text-align: left; vertical-align: top; padding-left: 95px;'>
   <table border='0' cellspacing='0' cellpadding='0' style='background-image: url(error.gif); width: 370px; height: 110px;'>
   <tr><td style='height: 42px;'><img src='spacer.gif' style='height: 42px;'></td></tr>
   <tr>
    <td style='height: 18px; font-size: 9pt; font-family: verdana; font-weight: bold; text-align: center; vertical-align: top;'>
     <span id='spanText' style='display: none;'>O campo "text" foi preenchido incorretamente...</span>
     <span id='spanValue' style='display: none;'>O campo "value" foi preenchido incorretamente...</span>
     <span id='spanBoth' style='display: none;'>Os 2 campos foram preenchidos incorretamente...</span>
    </td>
   </tr>
   <tr><td style='height: 13px;'><img src='spacer.gif' style='height: 13px;'></td></tr>
   <tr>
    <td style='height: 24px; width: 370px; text-align: center'><img id='btnError' src='btn_ok_up.gif' onMouseDown='this.src="btn_ok_down.gif";' onMouseUp='this.src="btn_ok_up.gif";' border='0' style='height: 24px; width: 79px; cursor: pointer;'></td>
   </tr>
   <tr><td style='height: 13px;'><img src='spacer.gif' style='height: 13px;'></td></tr>
   </table>
  </td>
	<tr><td height='30'></td></tr>
	</tr>
	</table>
</div>

<table id='tableCopyright' border='0' cellspacing='0' cellpadding='0' style='height: 100%; width: 100%;'>
	<tr>
  <td style='text-align: center; vertical-align: bottom; height: 100%; width: 100%;'>
  <img src='copyright.gif'>
  </td>
	</tr>
</table>
</body>
</html>
<script>
var select_offsetLeft = document.formA.select.offsetLeft;
var select_offsetTop = document.formA.select.offsetTop;

window.defaultStatus = "value: "+document.formA.select.options[document.formA.select.selectedIndex].value+"    text: "+document.formA.select.options[document.formA.select.selectedIndex].text;
</script>
felipefrancesco
<html>
<head>
 <style type="text/css">
  #centro {
          position      : absolute;
          top           : 50%;
          left          : 50%;
          margin-top    : -50px;
          margin-left   : -50px;
  }
  .negrito {
          color         : #FF0000;
          font-size     : 20px;
  }
 </style>
 <script language="JavaScript">
  function atualiza(p_indice, p_combo) {
   if(p_indice == 1) {
    var strOpcao = prompt('Digite a opção a ser inserida','');
    if(strOpcao == '') {
     alert('Digite um valor para a opção');
     p_combo.options[0].selected = true;
    } else {
     var intTamanho = p_combo.length;
     p_combo.length = intTamanho + 1;
     p_combo.options[intTamanho].text = strOpcao;
     p_combo.options[intTamanho].value = intTamanho;
     p_combo.options[intTamanho].selected = true;
    }
   }
  }
 </script>
</head>
<body>
 <div id="centro">
  <select name="cbo_desafio" onChange="atualiza(this.selectedIndex, this);">
   <option value="0">Desafio</option>
   <option class="negrito" value="1">>> Outros</option>
  </select>
 </div>
</body>
</html>
renan_doidera
<html>
<head>
<title> 1º Desafio JAVASCRIPT/DHTML/CSS - Script Brasil</title>
<style type="text/css">
.nada {
  text-align     : center; 
  vertical-align : middle; 
  width          : auto ;
  height         : auto ;
  padding        :  25% ;
   } 
</style>
</head>

<body>

<form name="renan">


   <div id="insere_campo" class="nada">
   <select size="1" name="Select_1" onchange="javascript:condicao()" >
<option> O Desafio !! </option>
<option style="font-weight: bold; background-color: #99CCFF" value="insere">
Inserir &quot;Option&quot;</option> 
</select>
</div>



<script language="javascript">

 a = "\<select size=\"1\" name=\"Select_1\" style=\"text-align: center; line-height: 100%\" onchange=\"javascript:condicao()\">"
 b = "\n\<option\> O Desafio !! \</option\>\n\<option style=\"font-weight: bold; background-color: #99CCFF\" value=\"insere\"\>Inserir \"Option\"\</option\>"
 c = "\</select\>"


       function insere2() 
 {
 b += "\n<option value=\""+nome+"\">"+nome+"</option>"
    document.getElementById('insere_campo').innerHTML = a+b+c;
    document.renan.Select_1.value = nome;                      
 }

 function insere() 
 {
 nome = prompt("Insira o Nome do Option a Ser inserido:","Opt Padrão");

  if ( nome == "insere" )
     { alert("Você não pode usar esse nome.");
       javascript:insere()                  }
  else { javascript:insere2() }
 }      
  function condicao() 
 {
  if (document.renan.Select_1.value == "insere")
      { javascript:insere() }               
 }        


</script>


<address>
Por Renan Manola
</address>
<address>
Renan_doidera@hotmail.com
</address>

</form>
</body>
</html>
rEd nEcK * http://redneck.zapto.org:2/desafios/js.sb.1.html
<!--

@desafio:  Js / DHTML / CSS - ScriptBrasil;
@tentivas: 3;
@criador:  RedNeck;
@creditos: Error404 && John Doe && Fabyo;

-->

<html>
<head>

<title>Desafio ScriptBrasil // by redneck</title>

<script language="JavaScript">

var n=0;

function adiciona(v){
   if(v == "Outros"){
      var texto = window.prompt("Por Favor Informe o Texto da Opção que deseja.","");
      var valor = window.prompt("Por Favor Informe o Valor da Opção que deseja.","");

   if(texto == null && valor == null){
    return false;
   }else{
       document.form.menu.options[document.form.menu.options.length] = new Option(texto,valor,false,true);
      }
   }else{
      return false;
   }

}

</script>

</head>

</form>

<style type="text/css">

.c1 {
width: 240px;
border: 1px solid #c0c0c0;
padding: 0; 
}

.c2 {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #ffffff;
padding:2px 5px;
font-weight: bold;
letter-spacing: 5px;
text-align: center;
background-color: #999999;
border: 1px solid #c0c0c0;
}


</style>

<body style="text-align: center;">

<script language="JavaScript">

if(screen.width == 800){
   document.write('<div id="l_center" style="position: absolute; left: 114px; top: 163px; margin-left: 150px; z-index: 1;">');
}else if(screen.width == 1024){
   document.write('<div id="l_center" style="position: absolute; left: 225px; top: 250px; margin-left: 150px; z-index: 1;">');
}

</script>

<fieldset class="c1">

<legend class="c2">Desafio JS</legend>
<form name="form">

<select name="menu" onChange="adiciona(this.options[this.selectedIndex].value);">
<option value="Desafio">Desafio</option>
<option value="Outros" style="color: #ff0000;">Outros</option>
</select>

</form>
</fieldset>

</div>

</body>
</html>
mello
<html>
<head>
<title>Challenge</title>
<style>
body
{
background: #0099ff;
font-family: Arial;
font-size: 10pt;
text-align: center;
}

.combo
{
width: 150pt;
background: #ffffff;
}
</style>
</head>

<script>
/*
*********************
* Moises Mello *
* 21/11/04 *
*********************
*/
function add_option(){
var n_options = document.form.set_option.options.length;
var selected_index = document.form.set_option.selectedIndex;
var new_option;

n_options = parseInt(n_options) - 1;

if(selected_index == 1){
new_option = prompt('Digite a nova opção:','');

if(new_option == null) new_option = '';

var n_length = parseInt(n_options) + 2;

document.form.set_option.options.length = n_length;
n_length = parseInt(n_length) - 1;
document.form.set_option.options[n_length].text = new_option;
document.form.set_option.options[n_length].style.color = 'red';


for(i=0;i<=n_length;i++){
if(document.form.set_option.options[i].index == n_length){
document.form.set_option.options[i].selected = true;
}
}
}
}

</script>
<body>
<div style="text-align: center; font-family: Verdana; font-size: 14pt; ">CHALLENGE</div>

<form name="form" action="" method="post">
<select name="set_option" onChange="add_option();" class=combo>
<option value="">Desafio</option>
<option value="" style="color: #666600;">Outros</option>
</select>
</form>
</body>
</html>

É isso aí, pessoal... valeu pela participação de todos!

Um abraço e até o próximo desafio! rolleyes.gif

Editado por Crystian
Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.


  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...