Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change ondblclick to onclick event when using IOS/Android etc

How can I change the ondblclick event to onclick event when page detects that its on IOS/Android etc. What makes it difficult is I cannot just call the ID of the element since it carry data from database to Javascript function.

Check it out.

Server-side:

<?php         
echo '<table>';
while($row=mysql_fetch_array($query)){
    echo '<tr><td ondblclick="sampFunc("'.$row[0].'","'.$row[1].'")">';
        echo $row[0];
    echo '</td></tr>'; 
}
echo '</table>';
?>

Client-side:

<script>
$(document).ready(function(){
    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
        /* ?????????????????? */
    }
});
function sampFunc(data1,data2){
    //-- Something
}
</script>
like image 567
Markipe Avatar asked Nov 12 '22 03:11

Markipe


1 Answers

I think you should re-write some of you code to make it easier to achieve what you want.

Trying to sniff the user agent isn't a great idea. Devices can change, new OS's can be launched and it requires more maintenance on your end. Feature detection is a much better approach as it covers devices now and in the future as well as minimising false positives.

The updated PHP now uses the HTML5 data-* attribute and removes the inline event:

<?php         
echo '<table class="myclass">';
while($row=mysql_fetch_array($query)){
    echo '<tr><td data-a="'.$row[0].'" data-b="'.$row[1].'">';
        echo $row[0];
    echo '</td></tr>'; 
}
echo '</table>';
?>

The new JS checks whether it's a touchscreen device and defines a variable touchDevice as true or false depending on which it is. This var is then used to define the event. If it's true (device is touch capable) then click is the event, otherwise it's dblclick.

The event handler now uses .on() instead of being defined inline and it makes use of the .data() function.

<script>
var touchDevice = !!('ontouchstart' in window) || !!('onmsgesturechange' in window);

$(document).ready(function(){
    var dblevent = touchDevice ? 'click' : 'dblclick';
    $('.myclass td').on(dblevent, function(){
        var data1 = $(this).data('a'), data2 = $(this).data('b');
         //-- Something
    });   
});
</script>

or simply use the updated PHP and the doubletap event:

$('.myclass td').on('dblclick doubletap', function(){
      var data1 = $(this).data('a'), data2 = $(this).data('b');
      //-- Something 
});
like image 103
Joe Avatar answered Nov 14 '22 22:11

Joe