I am using jQuery to show and hide a div by adding/removing a class to it.
$('input').focus(function(){
$(this).parents('.row').addClass("linksdiv");
}).blur(function(){
$(this).parents('.row').removeClass("linksdiv");
});
It works quite well when focusing on inputs, but if I click a link in linksdiv
it loses focus and the div disappears. Would it be better to use show() and hide() for the linksdiv
than to depend on css?
Would that allow the div to be clickable when 开发者_JS百科inputs are focused? Or is there a simple work around to keep linksdiv from losing focus when clicked but still have it disappear on blur?
Thanks again in advance! You folks are fantastic!
I am sorry I couldn't describe very well what i was trying to do this is it http://jsfiddle.net/Zw5c2/5/ Thanks Patrick for the resource!
@Nick is right, there won't be a clean solution.
One possibility is to delay the code in your blur so that your link's click handler has a chance to send the focus back to the input.
http://jsfiddle.net/Zw5c2/
var lastInput;
var timeout;
$('input').focus(function() {
var $th = $(this);
lastInput = $th;
clearTimeout(timeout);
$th.parents('.row').addClass("linksdiv");
}).blur(function() {
var $th = $(this);
timeout = setTimeout(function() {
lastInput = null;
$th.parents('.row').removeClass("linksdiv");
}, 150);
});
$('.link').click(function() {
lastInput.focus();
// run your code for the link
});
Another solution may be to make it so that the link is actually an input. Just style it to make it look like a link, and prevent any change to the text.
http://jsfiddle.net/Zw5c2/1/
Neither solution is perfect.
A change to implementation may be better.
I would not have a blur event attached to the inputs. Blur happens for many reasons and which can be undesired.
If your goal is to simply highlight the input row for the currently active field, then I would just add logic within focus that ensures that only one div.row
can have a linksdiv
class at a time. In your case:
$('input').focus(function() {
var containing_div = $(this).parents('.row');
var current_div = $('div.row.linksdiv');
if (current_div && current_div != containing_div) {
current_div.removeClass("linksdiv");
}
else {
containing_div.addClass("linksdiv");
}
});
精彩评论