I have jQuery that changes the href attribute of an <a>
tag, but it only runs once
This is what I have:
JS:
$('.swatch span').click(function(e) {
e.preventDefault();
var link = $(this).parents().attr("href");
if($(this).data("image").indexOf("no-image") == -1) {
$(this).parents('.thumbnail').find('img').attr('src', $(this).data("image"));
$(this).parents('.thumbnail').find('img').attr('srcset', $(this).data("image"));
}
$(this).parents('.thumbnail').find('a').attr('href', link);
});
I found this answer and tried below:
$('.swatch span').on('click', function(e) {
e.preventDefault();
var link = $(this).parents().attr("href");
if($(this).data("image").indexOf("no-image") == -1) {
$(this).parents('.thumbnail').find('img').attr('src', $(this).data("image"));
$(this).parents('.thumbnail').find('img').attr('srcset', $(this).data("image"));
}
$(this).parents('.thumbnail').find('a').attr('href', link);
});
HTML/Markup:
<div class="one-third column alpha thumbnail even" itemprop="itemListElement" itemscope="" itemtype="http://schema.org/Product">
<!-- the link below needs to change -->
<a href="/collections/polarized/products/product" itemprop="url">
<div class="relative product--product collection--443303820 product_image">
<img src="//cdn.shopify.com/s/files/1/2321/4605/products/013_a-_g__72_380x@2x.jpg?v=1504208271" class="transition-in lazyloaded">
<div class="collection_swatches">
<a href="/collections/polarized/products/product?variant=44459262348" class="swatch">
<span data-image="//cdn.shopify.com/s/files/7/2221/2305/products/store_013_a-_g__72_480x.jpg?v=1504208271" style="background-color: ; background-image: url(//cdn.shopify.com/s/files/7/2221/2305/products/store_013_a-_g__72_480x.jpg?v=1504208271); background-position: center; background-size: contain"></span>
</a>
<a href="/collections/polarized/products/product?variant=44459262476" class="swatch">
<span data-image="//cdn.shopify.com/s/files/7/2221/2305/products/store_013_a-_b__72_480x.jpg?v=1504208271" style="background-color: ; background-image: url(//cdn.shopify.com/s/files/7/2221/2305/products/store_013_a-_b__72_480x.jpg?v=1504208271); background-position: center; background-size: contain"></span>
</a>
<a href="/collections/polarized/products/product?variant=44459262668" class="swatch">
<span data-image="//cdn.shopify.com/s/files/7/2221/2305/products/_a-_g__72_480x.jpg?v=1504208271" style="background-color: ; background-image: url(//cdn.shopify.com/s/files/7/2221/2305/products/store_003_a-_g__72_480x.jpg?v=1504208271); background-position: center; background-size: contain"></span>
</a>
</div>
Doesn't work.
putting in console.log('clicked')
returns clicked
on every click.
- why is my click event firing only once in both instances?
- Does it have to do with the
.attr()
behavior? I checked documentation but don't see anything that suggests that it only fires once.