Search code examples
javascriptjqueryanchoreach

Change anchor link in pop-up window based on clicked link in JQuery


I'm currently helping to build a forum and we want to be able to warn users when they click links that will take them to an external site. At the moment, my code opens the pop-up window and will take the user to their designated link as expected.

However, if I were to click a different external link on the page, while the pop-up appears, clicking the redirect button pushes me to the first link I clicked.

How do I get it do that my code picks up the link that was clicked and uses that instead?

Here's the code I'm using so far. It's just a snippet from it.

$(function() {
  $("a").each(function(index, item) {
    $(this).on("click", function(e) {
      if (this.hostname != location.hostname) {
        let URL = $(item).attr("href");
        $(".modal").show();
        $('#redirectButton').click(function() {
          open(URL, '_blank');
        });

Solution

  • Since you don't remove the previous click handler it opens the previous link. Just remove the previous click handler first with .off('click'):

    $(function() {
      $("a").each(function(index, item) {
        $(this).on("click", function(e) {
          if (this.hostname != location.hostname) {
            let URL = $(item).attr("href");
            $(".modal").show();
            $('#redirectButton').off('click').click(function() {
              open(URL, '_blank');
            });