Reputation: 5599
I am trying to display menu (#lorem-ipsum-wrapper
) when the div (#content
) is focused, and again hide the menu if neither the div or the menu is clicked.
js:
$(document).ready(function() {
console.log('ready');
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css("display", "block");
event.stopPropagation();
});
$(document).on("click", function() {
$('#lorem-ipsum-wrapper').css("display", "none");
});
});
demo at codepent.io
But the problem is that as soon as the #content
is in focus, the menu displays and then again hides itself. Isn't the stopPropagation()
method used to stop this? What am I doing wrong? Your help will be very much appreciated. Thank you.
Upvotes: 2
Views: 2690
Reputation: 1355
If I didn't misunderstand, you want to hide #lorem-ipsum-wrapper
if #content
is not clicked and show the #lorem-ipsum-wrapper
on click of #content
. Then, your code should be:
$(document).ready(function() {
console.log('ready');
$('#lorem-ipsum-wrapper').css('display','none');
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css('display','block');
});
$('#content').on("blur", function() {
$('#lorem-ipsum-wrapper').css("display", "none");
});
$('#lorem-ipsum-wrapper').on("click",function(){
$(this).css("display","block");
});
Explanation:
The third lines ensures that the lorem-ipsum-wrapper
is not show before executing any code.
The fourth and fifth lines make the #lorem-ipsum-wrapper
visible whenever the focus is on the #content
.
The seventh and eighth lines make the lorem-ipsum-wrapper
hidden whenever the users clicks somewhere else on the page or make the #lorem-ipsum-wrapper
lose focus.
Upvotes: 0
Reputation: 372
Does this help ?
$(document).click(function(e) {
var e = $(e.target), eid = e.attr("id");
if (!e.parents("#lorem-ipsum-wrapper").length && !e.parents("#content-wrapper").length && eid !== "content-wrapper" && eid !== "lorem-ipsum-wrapper") {
$('#lorem-ipsum-wrapper').css("display", "none");
}
});
or you can use blur event :
$('#content').on("focus", function(event) {
$('#lorem-ipsum-wrapper').css("display", "block");
});
$('#content').on("blur", function(event) {
$('#lorem-ipsum-wrapper').css("display", "none");
});
Upvotes: 2