0





147

Advertisement

I'm trying to trigger a click event on a link from within a click handler for the same link. I want to stop the link from navigating until the user has been notified of some action. Once the action is complete the link should navigate as normal.

Please see the test case below.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    </head>
    <body>
        <script language="javascript" type="text/javascript">
            $(function () {
                $("#test").click(function (e) {
                    var lnk = $(this);

                    if (lnk.data("checked") != true) {

                        var notice = $('<a href="#">Continue</a>');
                        $('body').append(notice);

                        notice.click(function (e) {
                            lnk.data("checked", true);
                            lnk.click();

                            return false;
                        });

                        return false;
                    }

                    alert("should navigate now");
                });
            });
        </script>

        <a id="test" href="http://www.google.com">Test</a>

    </body>
</html>

The expected behavior for this example is;

  • Test clicked
  • Continue appears
  • Continue clicked
  • Page navigates to the href of 'Test'

Instead, when continue is clicked, the alert 'should navigate now' is shown but the browser doesn't perform any action.

Question author Alex | Source

Advertisement


0


Try triggering the click using the dom element

   notice.click(function (e) {
       lnk.data("checked", true);
       lnk[0].click();
       // ^^^^
       return false;
   });

DEMO

Answer author Anton