Click and dblclick in javascript

Asked

Viewed 657 times

0

I’m new to JS and I’m learning, and I’m doing an old game in which the first click is for the player1 to put the "x", and two clicks for the player2 to put the "o", what’s the best way to do it? because I can’t add an "onclick" or an "ondblclick" to the tag, I was trying to make addeventlistener by taking the class, but I couldn’t make it functional.

I am using a table to create the board: updated js code.

function testejogada(){
alert("funcionou");

}

function testejogada1(){
alert("funcionou1");
}

document.addEventListener('DOMContentLoaded', function(){
var classe = document.querySelector(".espaco");
classe.addEventListener('dblclick', function(){ testejogada()

});

classe.addEventListener('click', function(){ testejogada1()

});
});
<table align="center">
  <tr>
    <td><img class="espaco" src="img/default.png" id="casa1-1" /></td>
    <td><img class="espaco" src="img/default.png" id="casa1-2" /></td>
    <td><img class="espaco" src="img/default.png" id="casa1-3" /></td>
  </tr>

  <tr>
    <td><img class="espaco" src="img/default.png" id="casa2-1" /></td>
    <td><img class="espaco" src="img/default.png" id="casa2-2" /></td>
    <td><img class="espaco" src="img/default.png" id="casa2-3" /></td>
  </tr>

  <tr>
    <td><img class="espaco" src="img/default.png" id="casa3-1" /></td>
    <td><img class="espaco" src="img/default.png" id="casa3-2" /></td>
    <td><img class="espaco" src="img/default.png" id="casa3-3" /></td>
  </tr>

  <tr>
    <td colspan="3" id="ganhador"></td>
  </tr>
</table>

  • Post also code . js please...

  • in this case I was trying to use something like this: /////////// Function testejogada(){ Alert("worked"); } var Elements = Document.querySelectorAll('.espaco'); for (i = 0; i < Elements.length; ++i) { Elements[i]. addeventlistener('click', test played); }

  • Post the code that writes X and O in the boxes.

  • in case my problem is not how to get the X or O and yes to take the 1 click or 2 clicks and be able to do two different operations, I still do not know how to do this and everything I tried is at least flawed.

  • Post your js so that we can analyze it and understand its logic. Then we will help you correct. We will act on the failures only

  • then in the above comment I posted in a way I tried to do; --> code ///// Function testejogada(){ Alert("worked"); } var Elements = Document.querySelectorAll('. espaco'); for (i = 0; i < Elements.length; ++i) { Elements[i]. addeventlistener('click', test played); } /////

  • edited the post with the code in js

  • Is double click a prerogative? Because there are simpler ways to do this

  • yes, you have to use the double click, in case it is for learning, I managed to "fix" my code, but I need to put a "team" to differentiate the two clicks, I will edit there in the post, but tbm do not know how to do this "team".

  • @pdm, you should not use dbclick and click on the same element in these cases. Even if you manage to set the Switch, it will always click. There won’t be time to fire the second event after the first one, you understand? The following ref: https://stackoverflow.com/questions/7897558/listen-to-double-click-not-click

  • truth is pretty bad to use, there would be some other way to do it?

  • @pdm, an alternative is to do as follows: https://codepen.io/valdeir2000/pen/pLqMmM

  • @Valdeirpsr thanks seeing your code I managed to have another view of how to use the js, but this way I was able to do in the case with 1 click.

Show 8 more comments

3 answers

0

Well I guess what you need to do is a little more complex than that, so I used the jquery library that can be downloaded here

What happens you will not be able to put a dbclick and an onclick in the same element whenever a dbclick the onclick will be called so for this I created a function with a timer to be recognized the number of clickes

$(document).ready(function(){
    function testejogada(){
        alert("funcionou");

    }

    function testejogada1(){
        alert("funcionou1");
    }
var classe = $(".espaco");
console.log(classe)

$.each(classe, function(k,v){
var DELAY = 700, clicks = 0, timer = null;



    $(this).on("click", function(e){

        clicks++;  //conta os clicks

        if(clicks === 1) {

            timer = setTimeout(function() {

                testejogada();  //execeuta o click unico action    
                clicks = 0;             //apos executado zera o timer

            }, DELAY);

        } else {

            clearTimeout(timer);    //previne o click unico action
            testejogada1();         //executa  o  dbclick 
            clicks = 0;             //apos fazer a ação reseta o timer
        }

    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancela   o double click default do navegador
    });

});
})

You can see the example working here

  • thank you very much, really it was =D

0


You can do this by alternating the attributes onclick and ondblclick as the players play.

I created a class jogado to disable clicks on the houses that have already been marked (I put a red background for example).

Example:

var jogador1 = true;
var jogador2 = false;
var jogador_vez = 1;

function alteraJogador(){

   var casas = document.body.querySelectorAll(".espaco");
   
   for(var x=0; x<casas.length; x++){

      casas[x].setAttribute("onclick", jogador1 ? "joga(this)" : "");
      casas[x].setAttribute("ondblclick", jogador1 ? "": "joga(this)");
      
      // aqui eu removo os atributos onde tem classe "jogado"
      // para não aceitar mais cliques
      if(casas[x].classList.contains("jogado")){
         casas[x].removeAttribute("onclick");
         casas[x].removeAttribute("ondblclick");
      }
   }
   
}

function joga(casa){
   jogador1 = !jogador1;
   jogador2 = !jogador2;

   casa.classList.add("jogado");
   
   alteraJogador();

   if(jogador_vez == 1){
      // faz algo quando o jogador 1 jogar
      console.log("Jogador 1 jogou.");
   }else{
      // faz algo quando o jogador 2 jogar
      console.log("Jogador 2 jogou.");
   }

   jogador_vez = jogador1 ? 1 : 2;
   
   console.log("Vez do jogador "+jogador_vez+" jogar");
}

document.addEventListener("DOMContentLoaded", alteraJogador );
.jogado{
   background: red;
}
<table align="center">
<tr>
   <td><img class="espaco" src="img/default.png"  id="casa1-1"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa1-2"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa1-3"/></td>
</tr>

<tr>
   <td><img class="espaco" src="img/default.png"  id="casa2-1"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa2-2"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa2-3"/></td>
</tr>

<tr>
   <td><img class="espaco" src="img/default.png"  id="casa3-1"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa3-2"/></td>
   <td><img class="espaco" src="img/default.png"  id="casa3-3"/></td>
</tr>

<tr >
   <td colspan="3" id="ganhador"></td>
</tr>		
</table>

  • perfect! thanks so much for the help! that’s just what I was needing, I wasn’t aware about setAttribute and the remove, it helped a lot in my learning =)

0

My suggestion is that you use only the event click, and make the change between cruz and circulo.

var game = [ 
  [null, null, null], 
  [null, null, null], 
  [null, null, null], 
]

var squares = document.querySelectorAll(".square");
var onSquareCircle = function (event) {
  var hasCircle = this.classList.contains("circle");
  this.classList.toggle("circle", !hasCircle)
  this.classList.toggle("cross", hasCircle)
  
  var x = parseInt(this.dataset.x)
  var y = parseInt(this.dataset.y)
  game[x][y] = hasCircle ? 1 : 0
};

[].forEach.call(squares, function (square) {
  square.addEventListener("click", onSquareCircle);
})
.square {
  height: 64px;
  width: 64px;
  border: 1px solid black;
  border-radius: 5px;
  background-size: calc(100% - 5px);
  background-position: center;
  background-repeat: no-repeat;
}

.cross {
  background-image: url('https://image.flaticon.com/icons/svg/128/128397.svg')
}

.circle {
  background-image: url('https://image.flaticon.com/icons/svg/64/64299.svg')
}
<table>
  <tbody>
    <tr>
      <td data-x="0" data-y="0" class="square"></td>
      <td data-x="0" data-y="1" class="square"></td>
      <td data-x="0" data-y="2" class="square"></td>
    </tr>
    <tr>
      <td data-x="1" data-y="0" class="square"></td>
      <td data-x="1" data-y="1" class="square"></td>
      <td data-x="1" data-y="2" class="square"></td>
    </tr>
    <tr>
      <td data-x="2" data-y="0" class="square"></td>
      <td data-x="2" data-y="1" class="square"></td>
      <td data-x="2" data-y="2" class="square"></td>
    </tr>
  </tbody>
</table>

Browser other questions tagged

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