javascript – Open link in new tab without using target="_blank" embedded in HTML

Question:

Scenario

I'm optimizing a page where around 200 Images (very small, no pageing required) of partners are displayed, these images are wrapped in an <a> tag and all partner sites open in a new tab ( target="_blank" ).

Note: I saw related materials on the site but the Javascript used to answer the question (which was not so similar to this one) was too large, which would take away all the savings obtained and would require adaptations to the problem.

Question

How can I suppress target="_blank" and still keep pages opening in a new tab

HTML code

<div id="minor_partners" class="col-md-10 col-md-offset-1">
    <a href="" target="_blank"><img class="link_thumb" src="" title=""></a>
</div>

Answer:

The way I found it was to use a function from the jQuery .click() library so that when the image was clicked, the target property would be assigned the value _blank .

HTML code for testing

<html>
    <head>
    <title>
        Abrindo em nova Aba
    </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
    <body>
        <div id="minor_partners" class="col-md-10 col-md-offset-1">
        <a href="http://pt.stackoverflow.com/"><img class="link_thumb" src="https://clubdopenguinnotice.files.wordpress.com/2010/08/edit-icon.jpg"></a>
        <a href="http://pt.stackoverflow.com/"><img class="link_thumb" src="https://clubdopenguinnotice.files.wordpress.com/2010/08/edit-icon.jpg"></a>
        <a href="http://pt.stackoverflow.com/"><img class="link_thumb" src="https://clubdopenguinnotice.files.wordpress.com/2010/08/edit-icon.jpg"></a>
        </div>
            <a href="http://pt.stackoverflow.com/"><img class="link_thumb" src="https://clubdopenguinnotice.files.wordpress.com/2010/08/edit-icon.jpg"></a>
    </body>
</html>

Javascript code (used on elements that are not generated after page load)

$('#minor_partners a').click(function() {
    $(this).attr('target', '_blank');
});

Javascript code (used in elements that are generated after the page loads)

$('#minor_partners').on('click', 'a',function() {
    $(this).attr('target', '_blank');
});
Scroll to Top