Reputation: 557
I have a div, I want the div to to go to a link when clicked on. However, within the div, I also have a link that I simply want it to add a product to cart (via ajax), but NOT go to the link.
PARENT ELEMENT JS FOR LINK
$(document).on("click", '.product_result', function(){
url = $('h3 a',this).attr('href');
window.location = url;
});
CHILD ELEMENT FOR ADD TO CART
$('.product_add').click(function(e){
e.preventDefault();
var pid = $(this).siblings('.product_pid').val();
var quantity = $(this).siblings('.product_cart input').val();
var product_name = $(this).siblings('.product_name_add').val();
add_cart(pid,quantity);
cart_status(quantity,product_name);
});
HTML
<div class="product_result_wrapper">
<div class="product_result">
<div class="result_image"><img height="100" width="150" alt="Product NAme" src="image.jpg"/></div>
<div class="product_info">
<h3><a href="link" title="image">Product Name</a></h3>
<p class="product_info_desc">CONTENT</p>
<div class="product_price"><span>Price:</span>£495.00</div>
<div class="product_more_info"><a href="link">More Info</a></div>
<div class="clr"></div>
</div>
<div class="clr"></div>
<div class="product_order">
<div class="product_cart">
<input type="text" value="1"/>
<input class="product_pid" type="hidden" value="44"/>
<input class="product_name_add" type="hidden" value="product_id"/>
<input class="product_add" type="button" value="Add to Cart"/>
</div>
</div>
</div>
</div>
So the issue is the .product_add element, within the .product_result element. I hacked it by creating an extra parent element, .product_result_wrapper, and placed the add_cart element in there (not shown in this code) and simply changed the position of the element to appear within the .product_result element.
I also tried it with CSS, making it a higher z-index, with relative positions, but this did not work either.
So how do I prevent the default of a js event? So that I can include a different element withe the same event within this element, but to do a different action?
Upvotes: 0
Views: 30
Reputation: 2824
Change e.preventDefault();
in the $('.product_add').click(function(e){})
function to e.stopImmediatePropagation();
That must prevent the .product-result click listener from being triggered
Upvotes: 1
Reputation: 4676
It sounds like you're looking for e.stopPropagation()
, not e.preventDefault()
. It is, however, always messy to use either one of these. The cleanest fix, if possible, would be to be more specific on what should trigger the 'parent element link', e.g. instead of
$(document).on("click", '.product_result', function(){
...
something like
$(document).on("click", '.product_result h3 a', function(){
var url = $(this).attr('href');
...
Again, I don't know if this is possible for you, but here's a JSFiddle you can play around with.
Upvotes: 0