Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Open in new Tab (_blank) [duplicate]

Tags:

jquery

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.

like image 647
user2085752 Avatar asked Feb 19 '13 05:02

user2085752


3 Answers

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")
like image 44
Ravi Gadag Avatar answered Dec 15 '22 12:12

Ravi Gadag


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.
like image 89
kristinalim Avatar answered Dec 15 '22 12:12

kristinalim


Replace this line:

$(this).target = "_blank";

With:

$( this ).attr( 'target', '_blank' );

That will set its HREF to _blank.

like image 25
ncksllvn Avatar answered Dec 15 '22 13:12

ncksllvn