Don't know why it's not working, i think the code is fine - could you tell me what is wrong? I need to add some class after some time interval...
$('.main_menu ul li').mouseenter(function(){
setTimeout(function(){
$(this).children('.sub_menu_main').addClass('opened')
},200);
});
$('.main_menu ul li').mouseleave(function(){
$(this).children('.sub_menu_main').removeClass('opened')
});
Don't know why it's not working, i think the code is fine - could you tell me what is wrong? I need to add some class after some time interval...
$('.main_menu ul li').mouseenter(function(){
setTimeout(function(){
$(this).children('.sub_menu_main').addClass('opened')
},200);
});
$('.main_menu ul li').mouseleave(function(){
$(this).children('.sub_menu_main').removeClass('opened')
});
Share
Improve this question
asked Dec 4, 2012 at 15:54
LukasLukas
7,75420 gold badges79 silver badges127 bronze badges
4
- 1 Can you show your html elements too? – Darren Wainwright Commented Dec 4, 2012 at 15:55
- Have you confirmed that your selector statements are returning the correct HTML elements? – adamb Commented Dec 4, 2012 at 15:55
- It would be wise to create a JSFiddle (jsfiddle) that succinctly reproduces the problem. Often you will spot the issue yourself when doing that, but at least you can link your question to a full working example of the issue. – Eric J. Commented Dec 4, 2012 at 15:56
- 1 You need to pass a reference to "this" in your timeout since it executes out-of-context from the event. – Diodeus - James MacFarlane Commented Dec 4, 2012 at 15:56
2 Answers
Reset to default 5$('.main_menu ul li').on({
mouseenter: function(){
var self = this; //in scope
$(self).data('timer', setTimeout(function(){ //new scope
$(self).children('.sub_menu_main').addClass('opened'); //out of scope
},200);
},
mouseleave: function(){
clearTimeout($(this).data('timer'));
$(this).children('.sub_menu_main').removeClass('opened');
}
});
I believe this
isn't referencing what you think it does in that scope. You should try storing a reference to this in your outer scope, and then access the hovered element through that reference instead:
$('.main_menu ul li').mouseenter(function(){
var that = this;
setTimeout(function(){
$(that).children('.sub_menu_main').addClass('opened')
},200);
});