Wosley Alarico Wosley Alarico - 3 months ago 13
Javascript Question

jquery single click not working properly

I managed to remove the attribute element of a list item but I am struggling to do the following: When I click on a list item,it should add a class called important,otherwise, the class must not exist.

I tried this using jQuery:

$(document).ready(function (){
var origHref = $('ul#primary-menu > li.menu-item-has-children > a').attr('href');
var clicks = 0;
$('ul#primary-menu > li.menu-item-has-children > a').removeAttr("href").data("origHref",origHref);
$('ul#primary-menu > li.menu-item-has-children').click(function(){
if(clicks === 1){
$('ul#primary-menu > li.menu-item-has-children').addClass('important');
else if(clicks > 1){
alert("you clicked twice");

Problem: When I inspect the element and click on the list for the first time,nothing happens.Only when I click for the second time that the class is added.

NOTE: I wanna do that for mobile devices only,so no need to worry about screens wider than 800 pixels.

Please help.


Do a if based on the class not a global variable, prevent the default click event :

  $('ul#primary-menu > li.menu-item-has-children').click(function(e) {
  if ($(window).width() < 800) {
    if (!$(e.target).closest('ul').is('.sub-menu')) {
      if (!$(this).hasClass('important')) {
          //toggle the menu 
      } else {
        //redirect if second click 
        window.location = $(this).find('a').attr('href');