I have a unordered list over a text, like:
<a href="">
<ul>
<li>OK</li>
</ul>
</a>
The unorder list is positioned absolute above the text using css
a {
position:relative;
}
ul {
position: absolute;
top:0;
left:0;
}
Then I use jQuery's .on function to make li respond to click:
$(document).on("click", "li", function() {
alert('hello');
});
However, when I click on li, the link in a is also clicked and makes me go to google.
How can I prevent the link in a when I click on li?
The demo can be found at: /
I have a unordered list over a text, like:
<a href="http://google.">
<ul>
<li>OK</li>
</ul>
</a>
The unorder list is positioned absolute above the text using css
a {
position:relative;
}
ul {
position: absolute;
top:0;
left:0;
}
Then I use jQuery's .on function to make li respond to click:
$(document).on("click", "li", function() {
alert('hello');
});
However, when I click on li, the link in a is also clicked and makes me go to google..
How can I prevent the link in a when I click on li?
The demo can be found at: http://jsfiddle/jfq8L/
Share Improve this question asked Sep 4, 2013 at 10:32 Zhengming YingZhengming Ying 4574 silver badges7 bronze badges 4- The mouse action does not pass through in chrome... – astex Commented Sep 4, 2013 at 10:36
-
1
So what is the point of wrapping an
ul
element with ana
nchor? – Ram Commented Sep 4, 2013 at 10:37 - Are you looking for this? jsfiddle/jfq8L/5 - @ZhengmingYing – Nitesh Commented Sep 4, 2013 at 10:38
- I need a block element at the top-left of an inline element. So the layout needs to be unchanged. – Zhengming Ying Commented Sep 4, 2013 at 14:48
5 Answers
Reset to default 5What you need to do is to stop the event from bubbling up the tree. You can do that with stopPropagation()
And your can bind the event directly to the li, you only need to delegate it if it isn't there on pageload.
$('li').on("click", function(e) {
e.stopPropagation();
alert('hello');
});
You have a wrong markup, a
is an inline element and ul
is a block level element. You cannot nest inline elements in block level elements
$(document).on("click", "li", function(e) {
e.preventDefault();
alert('hello');
});
What you are trying to do is to detect a click on the li element but stop the event going through to the a.
You are going to want to separate out the event listener for the li and use
$('li').on("click", function(e) {
e.stopPropagation();
}
here is an edit of your fiddle: http://jsfiddle/epwec/1/
Clicking on the a directly fires its event listener but clicking on the li only fires the li's event listener.
Try this
$('a ul li').click(function() {
alert('hello');
});
or
$('ul li').click(function() {
alert('hello');
});
or
$('li').click(function() {
alert('hello');
});
or
$(document).on("click", "li", function(event) {
event.preventDefault();
alert('hello');
});