dev_levity
dev_levity

Reputation: 31

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

Upvotes: 3

Views: 8552

Answers (3)

pgmsoul
pgmsoul

Reputation: 61

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

Upvotes: 2

dev_levity
dev_levity

Reputation: 31

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

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can use touchstart event which fires on mobile browsers.

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

More touch based events

Upvotes: 3

Related Questions