Search code examples
jqueryonclickonclicklistenerontouch

onclick event don´t works in mobile devices


I use this simple code for when click in div, check input checked, and also change color when i do click over div

My code :

  <div class="container_item" onclick="$('.check_<?php echo $pd;?>').attr('checked','checked');$('.drop_container_item').removeClass('drop_click');$(this).addClass('drop_click');">Test Click</div>

The problem it´s in all browsers works, but in mobile device don´t works, for example when i use un mobile devices, change the color of div, but don´t works the check

You can test here :

https://jsfiddle.net/aqnz3vc9/

I try other posibilities but i haven´t luck about this ways, thank´s in advanced for the help, regards


Solution

  • Firstly you shouldn't use inline event handler as they are very outdated and no longer best practice.

    As you're using jQuery attach your event handlers unobtrusively. If you use on() you can hook to both the click and touch events which will then work for desktop and mobile devices. Try this:

    <div class="drop_container_item">Click Now</div>
    <input type="radio" class="check" name="veritas" value="yes">
    
    jQuery(function($) {
      $('.drop_container_item').on('click touch', function() {
        $('.check').prop('checked', true);
        $('.drop_container_item').removeClass('drop_click');
        $(this).addClass('drop_click')
      });
    });