Reputation: 203
I'm using the following JQuery code to control some style elements on mouse hover for a drop down menu solution:
$(window).load(function () {
// On hover show or hide
$("#menu ul li").hover(function(){
$(this).children("ul").show();
$(this).children("ul").css('background-image', 'none');
},
function(){
$(this).children("ul").hide();
})
// On hover show or hide
$("#menu ul ul li, #menu ul ul li a ").hover(function(){
$(this).css('color', '#666');
},
function(){
$(this).css('color', '#FFF');
})
});
See working example:
http://www.youmeusdesign.co.uk/menu_test
I would like to modify this so that I can replace the hover function with a click function. When the client is using a touch interface that does not support the hover functionality. Windows Phone for example. iOS works ok as the device already has some classes to handle hover events.
I've tried modifying my script replacing the .hover with .click but it does not work?
e.g.
$("#menu ul li").click(function(){
Any help would be most appreciated.
Upvotes: 0
Views: 3973
Reputation: 15616
try this one: (tested here: http://jsfiddle.net/d9mPC/)
$("#menu ul li").on("mouseover mouseout tap",function(event){
if($(this).children("ul").is(":hidden") && (event.type == "mouseover" || event.type == "tap")){
$(this).children("ul").show();
$(this).children("ul").css('background-image', 'none');
}else if($(this).children("ul").not(":hidden") && (event.type == "mouseout" || event.type == "tap")){
$(this).children("ul").hide();
}
});
// On hover show or hide
$("#menu ul ul li, #menu ul ul li a ").on("mouseover mouseout tap",function(event){
if(!$.hasData($(this),"hovered") && (event.type=="mouseover" || event.type=="tap")){
$(this).css('color', '#666');
$.data((this),"hovered",true);
}else if($.hasData((this),"hovered") && (event.type=="mouseout" || event.type=="tap")){
$(this).css('color', '#FFF');
$.removeData((this),"hovered");
}
});
Upvotes: 1
Reputation: 206121
I would like to modify this so that I can replace the hover function with a click function.
$("#menu").on('click', 'ul li', function(){
$("#menu li ul").hide().find('li a').css('color', '#FFF');
$("ul", this).show().children('li a').css('color', '#666');
});
Upvotes: 0
Reputation: 942
You can probably do both at the same time.
What I would do is allow a click or hover to show the item (track a click state so that you aren't closing it immediately when hover opens it).
Then you will do achieve a few things
The alternative is to either sniff the device type or conditionally load different javascript files for each device (sniff device on the server side) which could lead to maintenance headaches.
I would recommend just implementing both for every device.
Upvotes: 0