JScript

Programação & Desenvolvimento


Você não está conectado. Conecte-se ou registre-se

Avatar no ChatBox nativo! 

3 participantes

Ir para baixo  Mensagem [Página 1 de 1]

1Avatar no ChatBox nativo!  Empty Avatar no ChatBox nativo!  Ter 03 Dez 2013, 10:55 pm

JScript

JScript
Administradores
Administradores

Avatar no /ChatBox nativo!


- Introdução:

Eu tenho visto muitos pedidos de adicionar o avatar no /chatbox nativo e dos códigos que já vi por ai, nenhum consegue mostrar de forma eficiente, rápida e sem erros incluindo o de Request Limit!

Este link jscript.forumeiros.com/t311-avatar-no-chatbox-personalizado me fez pensar no problema e como eu sempre gostei de desafios e fico bastante inquieto enquanto não consigo resolver um, bom, é claro que nem sempre eu resolvo pois ainda sou novato na linguagem de scripts para web...

Assim como meus códigos não são 100% livres de erros, como também não são perfeitos, lógico, mas venho-vos mostrar que consegui ter um efeito semelhante ao que temos em nosso ShoutBox aqui que usa HTML+JavaScript para ter o avatar, dando um efeito bem real!

Porém, esse artifício faz uso essencialmente de JavaScript, mas eu tentei ao máximo deixá-lo bem otimizado, ainda está um pouco desorganizado, mas já é funcional.


- Adicionando JavaScript

Adicione na gestão de JavaScript com investimento no índice o código abaixo:
Código:

/*
 * Avatar in /chatbox - Fast and Rá!!!
 * Version: 1.11.2013 - Kheops
 * Made and Optimizations by JScript - 2013/11/01
 * View more in: http://jscript.forumeiros.com/forum
 * Copyright (c) 2013 JScript <jscriptbrasil at live dot com>
 * This work is free. You can redistribute it and/or modify it
 * under the terms of the WTFPL, Version 2
 */
$(document).ready(function(){
    var sHtml = '<iframe onload="setOptions()" src="/chatbox/index.forum?archives=1" id="frame_chatbox" scrolling="yes" width="100%" height="100%" type="text/html" style="border: 0px;" />';
    $('#frame_chatbox').replaceWith(sHtml);
});

var old = '',
    oChat= null,
    connected = 1,
    chatbox_updated = 0,
    chatbox_last_update = 1,
    template_color = '#333333',
    chatbox_messages = 'null',
    chatbox_messages_old = '',
    number_of_refresh = 0,
    refresh_interval = 0,
    ncheckData = 0;

function setOptions() {
    oChat = $('#frame_chatbox').contents();
    oChat.find('#chatbox_footer form').attr('onsubmit', "parent.submitmsg2('?archives=1');parent.refresh_chatbox2('?archives=1');return false;");
    oChat.find('#chatbox_main_options li:eq(0) a').attr('onclick', "parent.ajax_refresh_chatbox2('?archives=1', 1);");
    oChat.find('#chatbox_main_options li:eq(3)').attr('onclick', "parent.refresh_chatbox2('?archives=1');");
    oChat.find('#chatbox_main_options li:eq(4) a').attr('onclick', "parent.CB_disconnect2();");

    connected = document.getElementById('frame_chatbox').contentWindow['connected'];
    chatbox_updated = document.getElementById('frame_chatbox').contentWindow['chatbox_updated'];
    chatbox_last_update = document.getElementById('frame_chatbox').contentWindow['chatbox_last_update'];
    number_of_refresh = document.getElementById('frame_chatbox').contentWindow['number_of_refresh'];
    //refresh_interval = document.getElementById('frame_chatbox').contentWindow['refresh_interval'];

    ncheckData = setInterval("checkData()", 10);
}
function checkData() {
    if (oChat.find('#chatbox span.user').length) {
        clearInterval(ncheckData);
        try {
            connected = document.getElementById('frame_chatbox').contentWindow['connected'];
            document.getElementById('frame_chatbox').contentWindow.clearInterval(document.getElementById('frame_chatbox').contentWindow['refresh_interval']);
            chatAvatar();
            refresh_interval = setInterval("refresh_chatbox2('?archives=1')", 5000);
            oChat[0].getElementById('chatbox').scrollTop = 999999;
        } catch (err) {}
    }
}
function chatAvatar() {
    var target = oChat.find('#chatbox span.user a'), chk = {};
    target.each(function(index) {
        var oThis = $(this);
        var USER_URL = oThis.attr('href');

        if (!chk[USER_URL]) {
            chk[USER_URL] = true;        
            //if ( !oThis.parent().find('.KheopsUserPhoto.KheopsUserPhoto_icon').length ) {
            /* Gets the avatar saved in local storage */
            var oStor = sessionStorage.getItem('chat' + USER_URL);
        
            if (oStor !== null) {
                oChat.find("#chatbox span.user a[href='" + USER_URL + "']").parent().prepend('<img alt="" class="KheopsUserPhoto KheopsUserPhoto_icon" src="' + oStor + '">');
                //oThis.parent().prepend('<img alt="" class="KheopsUserPhoto KheopsUserPhoto_icon" src="' + oStor + '">');
            } else {
                //jQuery.ajaxSetup({async:false});
                $.get(USER_URL, function (data) {
                    var AVATAR = $('#profile-advanced-right img', data).attr('src');
                    if (!AVATAR) AVATAR = $('#profile_tabs p img', data).attr('src');

                    oChat.find("#chatbox span.user a[href='" + USER_URL + "']").parent().prepend('<img alt="" class="KheopsUserPhoto KheopsUserPhoto_icon" src="' + AVATAR + '">');
                    /* Saves the member avatar in local storage */
                    sessionStorage.setItem('chat' + USER_URL, AVATAR);
                });
                //jQuery.ajaxSetup({async:true});
            }
            //}
        }
    });
    if (oChat.find("#punbb_jscript").length) {
        $('#punbb_jscript').attr('href', 'http://jscript.forumeiros.com').text('(c) http://jscript.forumeiros.com').show();
    } else {
        oChat.find('#chatbox_main_options').prepend('<li><a id="punbb_jscript" title="JScript at live dot com" href="http://jscript.forumeiros.com" target="_top" style="float: right; margin-left: 10px;">(c) http://jscript.forumeiros.com</a></li>');
    }
}
function CB_disconnect2() {
   if (connected) {
        document.getElementById('frame_chatbox').contentWindow.ajax_connect('?archives=1', 'disconnect');
      clearInterval(refresh_interval);
        clearInterval(ncheckData);
        connected = 0;
   } else {
        document.getElementById('frame_chatbox').contentWindow.ajax_connect('?archives=1', 'connect');
        clearInterval(refresh_interval);
        document.getElementById('frame_chatbox').contentWindow.clearInterval(document.getElementById('frame_chatbox').contentWindow['refresh_interval']);
        connected = 1;
        number_of_refresh = 0;
        if (!ncheckData) ncheckData = setInterval("checkData()", 10);
      /*try {
            chatAvatar();
         refresh_interval = setInterval("refresh_chatbox2('?archives=1')", 5000);
      } catch (err) {}*/
   }
}
function submitmsg2(params) {
   oChat[0].post.sent.value = oChat[0].post.message.value;
   oChat[0].post.message.value = '';
   oChat[0].post.message.focus();
   ajax_submit_chatbox2(params);
   return false
}
function refresh_chatbox2(params) {
   if (params == '' || params == undefined) {
      params = '?achives=0'
   }
   if (oChat[0].getElementById('refresh_auto').checked == true) {
      ajax_refresh_chatbox2(params)
   }
    $.post('/chatbox/chatbox_actions.forum?archives=1', 'mode=send&sent=');
}
function ajax_refresh_chatbox2(params, force) {
   if (params == '' || params == undefined) {
      params = '?achives=0'
   }
   if (window.XMLHttpRequest) {
      var http_request = new XMLHttpRequest()
   } else if (window.ActiveXObject) {
      var http_request = new ActiveXObject("Microsoft.XMLHTTP")
   }
   http_request.onreadystatechange = function () {
      if (http_request.readyState == 4 && http_request.status == 200) {
         var parsed_text = http_request.responseText;
         eval(parsed_text);
         if (chatbox_last_update > chatbox_updated || force) {
            if (oChat[0].getElementById('chatbox').innerHTML != null) {
               if (chatbox_messages_old != chatbox_messages) {
                  oChat[0].getElementById('chatbox').innerHTML = chatbox_messages;
                  chatbox_messages_old = chatbox_messages;
                        chatAvatar()
                  oChat[0].getElementById('chatbox').scrollTop = oChat[0].getElementById('chatbox').scrollHeight + oChat[0].getElementById('chatbox').offsetHeight;
                  oChat[0].getElementById('chatbox').scrollTop = 999999;
               }
            }
            if (oChat[0].getElementById('chatbox_members').innerHTML != null) oChat[0].getElementById('chatbox_members').innerHTML = chatbox_memberlist;
            chatbox_updated = chatbox_last_update
         }
      }
   };
   http_request.open('GET', '/chatbox/chatbox_actions.forum' + params + '&mode=refresh', true);
   http_request.send(null)
}
function ajax_submit_chatbox2(params) {
   number_of_refresh = 0;
   var msg_sent = oChat[0].post.sent.value;
   if (params == '' || params == undefined) {
      params = '?achives=0'
   }
   var data = '&mode=send';
   data += '&sent=' + encodeURIComponent(msg_sent);
   data += '&sbold=' + oChat[0].post.sbold.value;
   data += '&sitalic=' + oChat[0].post.sitalic.value;
   data += '&sunderline=' + oChat[0].post.sunderline.value;
   data += '&sstrike=' + oChat[0].post.sstrike.value;
   data += '&scolor=' + oChat[0].post.scolor.value;
   if ((msg_sent.indexOf('/away') == 0) || (msg_sent.indexOf('/abs') == 0)) {
      oChat[0].getElementById('refresh_auto').checked = false
   }
   if (oChat[0].post.sent.value == '/banlist') {
      window.open('/chatbox/chatbox_banlist.forum' + params, 'banlist', 'toolbar=no,menubar=no,personalbar=no,width=450,height=300,scrollbars=yes,resizable=yes');
      return false
   }
   if (window.XMLHttpRequest) {
      var http_request = new XMLHttpRequest()
   } else if (window.ActiveXObject) {
      var http_request = new ActiveXObject("Microsoft.XMLHTTP")
   }
   http_request.onreadystatechange = function () {
      if (http_request.readyState == 4 && http_request.status == 200) {
         var parsed_text = http_request.responseText;
         eval(parsed_text);
         if (chatbox_last_update > chatbox_updated) {
            oChat[0].getElementById('chatbox').innerHTML = chatbox_messages;
            oChat[0].getElementById('chatbox_members').innerHTML = chatbox_memberlist;
            chatbox_updated = chatbox_last_update;
                chatAvatar()
            oChat[0].getElementById('chatbox').scrollTop = 999999;
         }
      }
   };
   http_request.open('POST', '/chatbox/chatbox_actions.forum' + params, true);
   http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
   http_request.send((data))
}


- Adicionando CSS
Código:

/*
 * Avatar in /chatbox - Fast and Rá!!!
 * Version: 1.11.2013 - Kheops
 * Made and Optimizations by JScript - 2013/11/01
 * View more in: http://jscript.forumeiros.com/forum
 * Copyright (c) 2013 JScript - jscriptbrasil at live dot com
 * This work is free. You can redistribute it and/or modify it
 * under the terms of the WTFPL, Version 2
 */
 /* 1- Parte: Essa parte é necessária! */
.KheopsUserPhoto {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #D5D5D5;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
    float: left;
    margin-right: 8px;
    padding: 1px;
}
.KheopsUserPhoto_icon {
float: left !important;
  height: 16px;
  width: 16px;
}
.KheopsUserPhoto:hover {
    border-color: #7D7D7D;
}
.KheopsUserPhoto img {
    height: 50px;
    width: 50px;
}
img, .input_check, .input_radio {
  vertical-align: middle;
}
/* 2- Parte: Apenas pra dar uma característica de IPBoard */
#chatbox span[title] {
  float: right !important;
}
#chatbox .user > span {
  float: left !important;
}
#chatbox .user:not(a) {
  display: inline-block !important;
  max-width: 150px !important;
  min-width: 14% !important;
  text-align: right !important;
}
#chatbox .user a {
  float: left !important;
  font-weight: 700;
  max-width: 150px !important;
  min-width: 50px !important;
}
Nota: A primeira parte deste CSS é necessária, o restante é apenas pra deixar as mensagens um pouco mais elegantes, mas se não gostar, basta não usar a 2ª parte!



- Resultado

PUNBB
Avatar no ChatBox nativo!  Punbb10

Outras versões de fórum:
Spoiler:






PunBB Forumeiros


Se tiver alguma dúvida relacionada com este tópico crie um tópico com o seguinte título:
Avatar no chatbox nativo!

http://autoitbrasil.com

2Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Ter 03 Dez 2013, 11:00 pm

JScript

JScript
Administradores
Administradores

Olá!

Este tutorial está liberado para todos, comente, dê sua sugestão e crítica...

JS

http://autoitbrasil.com

3Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qua 04 Dez 2013, 5:56 am

waghcwb

waghcwb
Desenvolvedores
Desenvolvedores

Muito bacana mesmo. Pude ver o efeito quando você deixou o efeito disponível para a galera aqui mesmo...
Apesar que prefiro o chatbox IPB xD

http://wagneraugusto.com.br/

4Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qua 04 Dez 2013, 9:15 pm

Convidado

avatar
Convidado

Aqui não funcionou na PhpBB3.. Só o outro código, que e privado para alguns fóruns.

5Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qua 04 Dez 2013, 9:39 pm

JScript

JScript
Administradores
Administradores

Cʀɑzy escreveu:Aqui não funcionou na PhpBB3.. Só o outro código, que e privado para alguns fóruns.
Interessante pois a única coisa que eu fiz foi remover o bloqueio, o código é o mesmo...

JS

http://autoitbrasil.com

6Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qui 05 Dez 2013, 9:15 am

Convidado

avatar
Convidado

Entendo, já que só aquele funciona aqui, poderia desbloquea-lo para este fórum?
-> http://destruction.narutorpg.org/forum

7Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qui 05 Dez 2013, 7:11 pm

JScript

JScript
Administradores
Administradores

@Crazy

Não há mais o que desbloquear pois eu apenas removi o bloqueio que nada tem à ver com o restante do código, tanto é que não tenho mais essa parte do código...
Reveja algumas funções no fórum que possam estar em conflito com meu código! Mas lhe garanto que é o mesmo código amigo.

Se você desejar e confiar em mim, me passe a sua conta pra que eu possa ver o chatbox do seu fórum, ou crie uma nova conta e me passe os dados por MP ok, pois não posso ficar me registrando em todos os fóruns para resolver problemas...

Abraços,

JS

http://autoitbrasil.com

8Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Qui 05 Dez 2013, 7:58 pm

Convidado

avatar
Convidado

@JScript

Olá, boa noite!

Já resolvi a situação, desde que cheguei da escola, optei por utilizar o ShoutBox. Dei uma personalizada, e ficou muito elegante no meu fórum.
Confio em você, quem sabe na próxima você não me ajude sem precisar se registrar..

9Avatar no ChatBox nativo!  Empty Re: Avatar no ChatBox nativo!  Sex 20 Mar 2015, 10:56 am

DiogoR.

DiogoR.
Membro
Membro

Visto que a Forumeiros deixou isso padrão acho melhor arquivar este tópico.

Antigamente eu cheguei a usar esse código.

Conteúdo patrocinado



Ir para o topo  Mensagem [Página 1 de 1]

Permissões neste sub-fórum
Não podes responder a tópicos