Sidney Sousa
Sidney Sousa

Reputation: 3614

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');  
//alert(origHref);
  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(){
     clicks++;
     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.

Upvotes: 0

Views: 835

Answers (1)

madalinivascu
madalinivascu

Reputation: 32364

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')) {
      e.preventDefault();
      if (!$(this).hasClass('important')) {
        $(this).addClass('important')
          //toggle the menu 
      } else {
        //redirect if second click 
        window.location = $(this).find('a').attr('href');
      }
    }
  }
});

Upvotes: 2

Related Questions