Simulate click with jQuery after inserting link via jQuery

Asked

Viewed 4,160 times

8

I have to open another tab with a link that is returned to from PHP to jQuery. I used window.open but he asks to release the popup and the client doesn’t like it at all. So I thought I’d do, when jQuery gets the link, it changes a <a href="javascript:void(0);" target="_blank"></a> for <a href="http://www.LinkQueRetornou.com.br" target="_blank"></a> and runs a function to simulate a click to open in another tab. The problem is that I made the code below and it is not working because it does not open the page in another tab, now I do not know if it is because the link was added later in a jQuery action (DOM).

HTML + jQuery

<button class="button" type="button" id="teste">Click</button>
<a href="javascript:void(0);" id="linkredirect" target="_blank"></a>

<script>
    $(document).ready(function(){

        $("#teste").click(function(){

            $("a#linkredirect").prop('href', 'http://www.google.com');
            $("a#linkredirect").trigger("click");
        })
    })
    </script>
  • Like you were using with window.open? Here for me (in Chrome) your code opened normal in another tab with window.open and _blank. See on fiddle.

  • Yes, mine also worked. But the client asked to allow popup. I think his was Safari

1 answer

7


Instead of using the function $(seletor).trigger("click"); use $(seletor)[0].click();.

Good, but because?

According to @The Alpha’s response to this question, what happens is that in the case of the function trigger() execution will not trigger a click event itself, but rather execute an event handler, if declared, for example:

$(selector).click(function() {
    // some code...
});

Okay, but why use the [0] before the .click(); ?

If it is necessary to use 0 between brackets, why function click() is native to javascript, so it does not belong to a jQuery object. If you are not using [0] to take only the HTML element from the function click() will have the same functionality as the trigger().

That way your code will work.

$(document).ready(function(){
    $("#teste").click(function(){
        $("a#linkredirect").prop('href', 'http://www.google.com');
        $("a#linkredirect")[0].click();
    });
});

See also working on jsfiddle

  • Thank you, your code worked here!!

  • 1

    @Alissonacioli I will add the answer to why this.

  • All right ;).. Thank you very much indeed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.