So I have this hover code:
function shortHover(elem){
$('body').delegate(elem, 'hover',
function() {
$(this).css("background-color", "#f0c723;")
},
function(){
$(this).css("background-color", "#00ed00;")
}
)
}
shortHover("#for_width_my_added");
shortHover("#for_width_my_published");
shortHover("#for_width_my_unpublished");
And than, on clicking on one of these elements:
$("#for_width_my_added").css("background-color", "#00ed00");
$("#for_width_my_published").css("background-color", "#00ed00");
$("#for_width_my_unpublished").css("background-color", "#00ed00");
$("#for_width_<%= @output[0] %>").css("background-color", "#f0c723");
So on clicking over elements assigned to green color, and currently clicked - to color of hover, so one element can have these color permanentely.
The problem is that after clicks over elements stop react on hover. Even though I used delegate. Why?
Your problem is that jQuery's hover
isn't a real JavaScript event, but merely a jQuery event or shorthand for $(selector).mouseenter(handlerIn).mouseleave(handlerOut);
. You can use this instead:
function shortHover(elem) {
$('body').delegate(elem, 'mouseover mouseout',
function (e) {
if (e.type == 'mouseover') {
$(this).css("background-color", "#f0c723");
} else if (e.type == 'mouseout') {
$(this).css("background-color", "#00ed00");
}
});
}
shortHover("#for_width_my_added");
shortHover("#for_width_my_published");
shortHover("#for_width_my_unpublished");
$("#for_width_my_added").css("background-color", "#00ed00");
$("#for_width_my_published").css("background-color", "#00ed00");
$("#for_width_my_unpublished").css("background-color", "#00ed00");
$("#for_width_<%= @output[0] %>").css("background-color", "#f0c723");
And here's a jsFiddle
Unless you are using an older version of jQuery, you shouldn't use .delegate()
but use .on()
instead as it has superseded .delegate()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.