Reputation: 475
I have a dropdown
menu which works fine, but when I am adding a link inside the dropdown
menu then the link doesn't work.
Check the fiddle here and try to click on the link2 and the google
link;
It's the google
link that doesn't work.
HTML
<div class="menu">
<div class="link">
<a href="#">Link 1</a>
<div class="dropdown">
Content for dropdown 1
</div>
</div>
<div class="link">
<a href="#">Link 2</a>
<div class="dropdown">
<a href="http://google.com">Google</a>
</div>
</div>
</div>
JQUERY
$('.link a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
$(document).mouseup(function (e)
{
var container = $(".dropdown");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
CSS
.link {
display: inline-block;
position: relative;
float: right;
}
.link a {
padding: 10px;
}
.link .dropdown {
display: none;
position: absolute;
top: 20px;
right: 0px;
color: white;
background: #999;
height: 200px;
width: 200px;
padding: 20px;
border: 1px solid red;
}
http://jsfiddle.net/abLku7e1/2
Any idea how to solve this?
Thanks in advance
Upvotes: 1
Views: 3730
Reputation: 1
I had a very similar problem. My CSS menu had something like:
<ul>
<li><a href="#internal link"> Working </a></li>
<li><a href="http://external link"> Not working </a></li>
</ul>
Like you, my javascript used e.preventDefault();
to close the menu once clicked and for the external link it would close the menu without actually going to that external link.
I solved it by adding a span:
<ul>
<li><a href="#internal link"> Working </a></li>
<li> <span> <a href="http://external link"> </span> Now its working </a></li>
</ul>
Upvotes: 0
Reputation: 52
Try this:
$('.link > a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
You only want to target direct descendants of .link.
Upvotes: 0
Reputation: 2367
Change the JS code to only act on the first link not all sub links like below
$('.link>a').on("click", function(e){
e.preventDefault();
$(this).parent('.link').siblings().children('.dropdown').fadeOut();
$(this).siblings('.dropdown').fadeToggle();
});
$(document).mouseup(function (e)
{
var container = $(".dropdown");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});
note link>a mean only first level
Upvotes: -1
Reputation: 3064
e.preventDefault();
is the problem, it's on .link a
which is ALL a
decendents of .link
. Use .link > a
for the parent level links.
>
means direct child.
Upvotes: 4