I've setup some Jquery based off other StackOverflow questions/answers. The purpose of this script is that it makes an entire div a link based on any a href tag that is inside that div.
This works fine however I need to set it to _blank to open in a new tab. I've tried the below with no luck.
$(document).ready(function() {
$(".product-item").click(function() {
$(this).target = "_blank";
window.location = $(this).find("a").attr("href");
return false;
});
});
EDIT
Thanks for the help but none of these answers actually work. If anyone can paste the full code that actually works, rather than little snippets without testing if it works. Thanks.
EDIT 2
Thanks to kristinalim, for providing a complete working solution.
you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.
$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")
Setting links on the page woud require a combination of @Ravi and @ncksllvn's answers:
// Find link in $(".product-item") and set "target" attribute to "_blank".
$(this).find("a").attr("target", "_blank");
For opening the page in another window, see this question: jQuery click _blank And see this reference for window.open
options for customization.
Update:
You would need something along:
$(document).ready(function() {
$(".product-item").click(function() {
var productLink = $(this).find("a");
productLink.attr("target", "_blank");
window.open(productLink.attr("href"));
return false;
});
});
Note the usage of .attr()
:
$element.attr("attribute_name") // Get value of attribute.
$element.attr("attribute_name", attribute_value) // Set value of attribute.
Replace this line:
$(this).target = "_blank";
With:
$( this ).attr( 'target', '_blank' );
That will set its HREF to _blank.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With