Event.clientX; and Event.clientY do not work in firefox

Asked

Viewed 97 times

0

This function is perfect on Chrome but does not work on firefox. the error is that in firefox it returns me in the console that "Event is not defined" but in chorme ta ok. The variables that are not in the function are global. (I don’t use jquery and I don’t want to use)

Calling on the Onmousedown:

function move_janela_inicia(div_barra_id)
{                                      


    <!--pega o tamanho do body principal que esta na index--> 
    elemento_body = window.parent.document.getElementById('corpo_main');

    <!--pega o retangulo do body--> 
    boxDoElemento = elemento_body.getBoundingClientRect();

    <!--pega a camada que vai se mover efetivamente, a barra filha já veio no parãmetro e assim sei quem é a pai--> 
    elemento_move=document.getElementById(window.parent.document.getElementById(div_barra_id).parentNode.id); 

    maximo_top=elemento_body.offsetHeight-elemento_move.offsetHeight;
    maximo_left=elemento_body.offsetWidth-elemento_move.offsetWidth;


    mover=1;


    document.getElementById(div_barra_id).addEventListener("mouseout", function() {

     move_janela_mouse();

      }, false);

}

Call in the function above

function move_janela_mouse()
{

   if (mover==1)
   {

           <!--pega o quanto rolou--> 
           var rolamentoX = elemento_body.scrollLeft;
           var rolamentoY = elemento_body.scrollTop;



           var xmouse=event.clientX;
           var ymouse=event.clientY;


           var px=((xmouse-boxDoElemento.left + rolamentoX)-(elemento_move.clientWidth/2));
           var py=ymouse-boxDoElemento.top + rolamentoY;


          <!--mantem a janela dentro dos limites-->                                           
          if (py<0) py=0;
          if (py>(maximo_top)) py=maximo_top-50;

          if (px<0) px=0;
          if (px>maximo_left) px=maximo_left;        


          elemento_move.style.left=px;
          elemento_move.style.top=py;

          mover=0;
  }



}       
  • How do you associate the event with that function? The problem is in that part, not in the function code itself. Or at least not only.

  • That is my question, if I put Event as a parameter in the function, what should I pass to this parameter? An event? Which and why?

  • It depends on how you associate the event... There is a way to do it that does not need to pass anything, the passage is automatic. It is the most recommended way, with addEventListener.

  • I put the whole code, it’s in one. js so that I can call with any layer that I want, just pass the div that is in the role of Window Window and works perfect on Chrome, but not firefox.

4 answers

2

Your code is almost there. Two small changes solve.

On the addeventlistener part, pass a reference to the function itself you want to call, instead of using an anonymous function and calling the other from there:

document.getElementById(div_barra_id).addEventListener("mouseout", move_janela_mouse, false);

This type of Listener association will automatically pass an event object as the function’s first argument. So just change the first line of the function to:

function move_janela_mouse(event) {
    ...
  • Almost, for some reason in firefox now when I click it goes away, for sure received x or y exaggerated, in Chrome remains perfect.

  • That’s right, in firefox it’s getting almost 300px more, why it will be?

  • Then I no longer know, there are several things in your code that I would do differently. One of them are the global variables you implicitly define in the first function and use in the second. The element box, for example, if it changes with the moment, you would need to recalculate. My response focused on the passage part of the event.

  • Yes, the annoying thing is to work in the chorme and not in the ffox, but ok, thank you partner, already helped a lot,.

0

you can assign the values to the variable this way

var xMouse = event.clientX || event.pageX;
var yMouse = event.clientY || event.pageY;

summarizing, if the first does not rotate, goes with the second value

0

Follow a suggested improvement to your code. this way you create a scope for your variables and avoid unnecessary calls to the event "mouse".

var MoverJanelaInicial = function (div_barra_id) {
    // iniciando variaveis que serão utilizadas no evento.
    this.elemento = document.getElementById(div_barra_id);
    this.elemento_body = window.parent.document.getElementById('corpo_main');
    this.boxDoElemento = this.elemento_body.getBoundingClientRect();
    this.elemento_move = document.getElementById(window.parent.document.getElementById(div_barra_id).parentNode.id); 
    this.maximo_top = this.elemento_body.offsetHeight - this.elemento_move.offsetHeight;
    this.maximo_left = this.elemento_body.offsetWidth - this.elemento_move.offsetWidth;

    // no lugar de temos uma variavel "mover" controlando à chamada do evento "mouseout".
    // que tal apenas remover a associação do evento após executa-lo?
    // para tal é preciso guardar uma referencia ao evento.
    // o ".bind(this)", serve para trocar trocar o objeto de contexto do evento, desta forma o this deixa de ser o elemento DOM e passa a ser à instancia de MoverJanelaInicial
    this.onMouseOut = this.moverJanelaMouse.bind(this);
    this.elemento.addEventListener("mouseout", this.onMouseOut);
}

MoverJanelaInicial.prototype.moverJanelaMouse = function (event) {
    var rolamentoX = this.elemento_body.scrollLeft;
    var rolamentoY = this.elemento_body.scrollTop;

    var xmouse = event.clientX;
    var ymouse = event.clientY;

    var px = ((xmouse - this.boxDoElemento.left + rolamentoX) - (this.elemento_move.clientWidth / 2));
    var py = ymouse - this.boxDoElemento.top + rolamentoY;


    if (py < 0) 
        py = 0;
    if (py > (maximo_top - 50)) 
        py = (maximo_top - 50);

    if (px < 0) 
        px = 0;
    if (px > maximo_left) 
        px = maximo_left;

    this.elemento_move.style.left = px;
    this.elemento_move.style.top = py;

    // removendo evento "mouseout"
    this.elemento.removeEventListener("mouseout", this.onMouseOut);
}

// instanciando o objeto
var moverJanela = new MoverJanelaInicial("meu_id");

0

Thanks a lot for the tips, without them I wouldn’t have made it. Several of them could not be used because I wanted to create a function that could be called from anywhere in my project, just referring to it on ondragstart, without passing any id or worrying about other events. The way below works perfectly on firefox and Chrome. Without further ado, follow the code - just put a div that would be the top bar of the window inside another div that would be the window itself and put the call of the function, type ondragstart='move_janela_start(Event);'

<!--variaveis globais que serão usadas em várias funções-->

 var elemento_move;
 var mover=0;
 var xinicial=0;
 var yinicial=0;



function move_janela_inicia(event)<!--chamar no ondragstart-->  
{

<!--pega a camada que vai se mover efetivamente, a barra filha já veio no parãmetro e assim sei quem é a pai--> 
    elemento_move=document.getElementById(window.parent.document.getElementById(event.target.getAttribute('id')).parentNode.id);                                       

<!--pega a posição x e y do mouse quando clicado-->     
     xinicial=event.clientX; 
     yinicial=event.clientY;


<!--passa um valor, no caso é como se passasse que valor é o id, mas podia ser um número por exemplo. Meio inútil neste exemplo mas sem esta linha não funciona no firefox-->  
     event.dataTransfer.setData("valor", event.target.getAttribute('id') );

<!--Para controlar e ele não ficar movendo sem que eu queira-->      
     mover=1;   

<!--Adiciona o evento oumouseout para que quando o usuário largue o botão chame a função-->      
     document.getElementById(event.target.getAttribute('id')).addEventListener("mouseout", move_janela_mouse, false);

}




<!--chamar no OnMouseout-->                   
function move_janela_mouse(event)
{



    if (mover==1)  <!--Se já iniciou a função move_janela_inicia e não largou o mouse...--> 
    {   


            boxDoElemento = elemento_move.getBoundingClientRect(); <!--pega a dimensão da div principa, que vai se mover--> 

            var px=xinicial-event.clientX; <!--pega aqui o quanto o usuário movimentou o mouse x e y--> 
            var py=yinicial-event.clientY;




            px=elemento_move.offsetLeft-px; <!--Desconta a largura e altura do componente--> 
            py=elemento_move.offsetTop-py;

            if (px<0) px=0; <!--as proximas 4 linhas servem para não permitir que a janela saia dos limites da página--> 
            if (py<0) py=0;

            if (px>window.screen.availWidth-elemento_move.offsetWidth) px=window.screen.availWidth-elemento_move.offsetWidth;
            if (py>(window.screen.availHeight-(elemento_move.offsetHeight*1.28))) py=window.screen.availHeight-(elemento_move.offsetHeight*1.28);  <!--por algum motivo tive que colocar 28% a mais, se puderem ajudar...--> 


            <!--agora move efetivamente a camada-->
            elemento_move.style.left=px;
            elemento_move.style.top=py;




             mover=0;  <!--para de mover as camadas-->
     }  

}       

Browser other questions tagged

You are not signed in. Login or sign up in order to post.