Javascript onClick for mobile

I am working on a submenu for the navigator, which should be accessible for mobile and tablet devices. I know 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 to switch submenus. If I add this simple Javascript line it works, but the submenu always stays open. How can I get it to close / switch 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;
}

      

+3


source to share


3 answers


You can use an touchstart

event that fires in mobile browsers.

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

      



Other touchscreen events

+3


source


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;
}

      

+2


source


I figured out this question after some research and help. Here's what has been updated in my code to run this correctly on mobile after some update in my CSS:

     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;
    });
  }

      

0


source







All Articles