validation in IF JQuery

2

Good afternoon,

I have several screens that is hidden (fade), when clicked on a button it appears.

<script>
    $(document).ready(function() {
        $("#animate").click(function() {
            $('#content').animate({"left": "100%"}, 1500);
            $('#content2').animate({"right": "100%"},1500);
        });
    });
</script>

I have these IDs: animate, animateServico, animatePortifolio.

I wanted to know how to do a validation, so when I click on any button that has one of the IDs it does the commands.

Example: When I click on the animate, I want the screen to scroll X px, if clicked on the animateServico the screen walk X px.

    
asked by anonymous 02.01.2019 / 16:26

2 answers

1

By the way I understand it, you want to add the EventListener simultaneously to the elements that have the IDs: animate , animateServico , animatePortifolio .

You can do this by simply adding the other IDs with a comma to the selector , like this:

$("#animate, #animateServico, #animatePortifolio").click(function() {
    //ação que você deseja
});

[Edited]

In front of what you said in the comments, contradicting my own statement, you can use the above approach, manipulating with if itself, which screen you want to open.

There are two ways to open a specific screen, according to the element that was clicked:

Form 1

You can get the id of the element clicked, and thus, you construct a block if , like this:

$("#animate, #animateServico, #animatePortifolio").click(function(event) { 
    //o "event" se faz necessário para obter-se o elemento clicado
    let targetId = event.target.id;
    if (targetId == "animate") {
        //ação 1
    } else if (targetId == "animateServico") {
        //ação 2
    } else if (targetId == "animatePortifolio") {
        //ação 3
    }
});

Form 2

You can define a data attribute , and then get its value, and according to it, open the desired screen:

<script> 
    $(document).ready(function() { 
        $("#animate, #animateServico, #animatePortifolio").click(function(event) { 
            $('#content').animate({"left": "100%"}, 1500); 
            $('#' + $(event.target).attr("data-tela")).animate({"right": "100%"},1500); 
         }); 
     }); 
</script>

I hope I have helped!

    
02.01.2019 / 16:59
1

As Gustavo put it in the answer, use .target to know which button triggered the event:

$("#animate, #animateServico, #animatePortifolio").click(function(e){
   
   var id = e.target.id; // pega o id do botão
   
   if(id == "animate"){
      
      console.log("botão animate");
      
   }else if(id == "animateServico"){

      console.log("botão animateServiço");

   }else{

      console.log("botão animatePortifolio");

   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><buttonid="animate">animate</button>
<button id="animateServico">animateServico</button>
<button id="animatePortifolio">animatePortifolio</button>
    
02.01.2019 / 17:23