简体   繁体   中英

Javascript onClick for mobile devices

I am working on a submenu for a nav that I need to be accessible for mobile and tablet devices. I am aware that using onClick="return true" will do the trick, however, I also need my list item to close when the user clicks on the list item. Basically I need it to toggle the submenu. If I add this simple line of Javascript, it will work but the submenu will always remain open. How can I get it to close/toggle the submenu?

HTML:
        <nav>
            <ul>
                <li class="active"><a href="#">Menu 1</a></li>
                <li><a href="#">Menu 2</a></li>
                <li><a href="#">Menu 3</a></li>
                <li class="bg"><a class="dropdown" href="#">Menu 4</a>
                    <ul>
                        <li><a href="#">Sub 1</a></li>
                        <li><a href="#">Sub 2</a></li>
                    </ul>
                </li>
            </ul>
        </nav>

Javascript:
$('nav li.bg').on('click', function(){
  return true;
}

You can use touchstart event which fires on mobile browsers.

$('nav li.bg').on('click touchstart', function(){
    return true;
});

More touch based events

A virtual method for p click:

$('p').on("touchstart",p_touch_start);
$('p').on("touchmove",p_touch_move);
$('p').on("touchend",p_touch_end);

function p_touch_start(){
    p_touch_move.cancel_click = false;
}
function p_touch_end(){
    if(p_touch_move.cancel_click) return;
    p_touch_move.cancel_click = true;//avoid somehow repeat call
    //trigger onclick()

}
function p_touch_move(){
    //user is drag page, not click
    p_touch_move.cancel_click = true;
}

I figured out the issue after some researching and help. Here is what was updated in my code to trigger this on mobile devices correctly after some updating of my CSS as well:

     function is_touch_device() {

     return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0));
  }

  if(is_touch_device()) {

    $('.bg').on('click', function(){

      $(this).toggleClass('activate');

      $(this).find('ul').slideToggle();
      return false;
    });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM