Javascript onclick requires two clicks

I have this box that transforms into a big box when clicked (getting class). But it takes 2 clicks, and not just one, as it was supposed to take.

.clientes {width:170px;height:27px;background-image:url('../imagens/clients.gif');-webkit-transition:1s;}
.clientes-clicked {width:356px !important;height:154px !important;background-image:url('../imagens/clients-big.png') !important;-webkit-transition:1s;}

<script>    
    var clientesclick = function(){
    $('.clientes').on('click', function(e) {
      $('.clientes').toggleClass("clientes-clicked"); //you can list several class names 
      e.preventDefault();
    });
    }
</script>

      

0


source to share


2 answers


You are making it more difficult than it needs to be. You can simply do:

$('.clientes').click(function(){
    $(this).toggleClass('clientes-clicked');
});

      

Fiddle: http://jsfiddle.net/64XQ3/



And as stated above, your jQuery should be wrapped in

$(document).ready(function(){
    // code here
});

      

+1


source


Try this:

<script>   
    $(document).ready(function() {
        $('.clientes').on('click', function(e) {
          $('.clientes').toggleClass("clientes-clicked"); //you can list several class names 
          e.preventDefault();
        });
    });
</script>

      



Not too sure why you are assigning it to a variable, but it will not run immediately, instead it will be executed when you call this method (this is the first click I think) and then your dom elements will have an event (second click).

Using $ (document). Already it will run after all the doms are ready and then when you first click on your elements they should already have an event

+1


source







All Articles