Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically click follows href and add some code

I would like to dynamically add an href element (to open a jnlp file), then continue the caller's workflow, for example just doing a console.log.

So far, my code is this:

$('<a id="tmplink" />')
  .attr('href', '/open_my.jnlp')
  .text('LINK')
  .appendTo('body')
  .get(0)
  .click(function(e) {
      console.log('aaaa'); // <-- this is never reached
});

The jnlp file is opening, but the browser's console, at least in Firefox is refreshed/cleaned and the console.log is never reached.

like image 324
leonardorame Avatar asked Oct 30 '22 15:10

leonardorame


1 Answers

Your code will work fine after adjusting this two points :

  1. No need to use .get(0) since it will return the element HTML like :

    <a id="tmplink" href="/open_my.jnlp">LINK</a>
    

So you cant attach click event to (html) instead you could attach the event click() directly.

  1. You should prevent the redirect using .preventDefault() to see the console log :

    $('<a id="tmplink" />')
       .attr('href', '/open_my.jnlp')
       .text('LINK')
       .appendTo('body')
       .click(function(e) {
          e.preventDefault();
          console.log('anchor clicked');
    });
    

Hope this helps.

$('<a id="tmplink" />')
.attr('href', '/open_my.jnlp')
.text('LINK')
.appendTo('body')
.click(function(e) {
  e.preventDefault();
  console.log('anchor clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 98
Zakaria Acharki Avatar answered Nov 15 '22 05:11

Zakaria Acharki