Search code examples
javascripthtmlhttp-redirectcookieshref

Redirect when all links have been clicked?


I have a page with three hashtag urls:

<a href="#Link1">Some Text 1</a>
<a href="#Link2">Some Text 2</a>
<a href="#Link3">Some Text 3</a>

Once the user has clicked all three I need to redirect them to another URL.

Does anyone have an example, or know a way I can do this?


Solution

  • Try with this:

    window.onload = function () {
        var anchors, clicked_count, clicked, i, cur_anchor, my_anchor_id;
    
        anchors = document.getElementsByTagName("a");
        clicked_count = 0;
        clicked = {};
    
        for (i = 0; i < anchors.length; i++) {
            cur_anchor = anchors[i];
            cur_anchor.setAttribute("data-anchor-id", i);
            cur_anchor.onclick = function (e) {
                e = e || window.event;
                e.preventDefault();
    
                my_anchor_id = this.getAttribute("data-anchor-id");
                if (!(my_anchor_id in clicked)) {
                    clicked[my_anchor_id] = null;
                    if (++clicked_count === anchors.length) {
                        console.log("WOULD BE REDIRECTING");
                        //window.location.href = "NEW URL";
                    }
                }
            };
        }
    };
    

    DEMO: http://jsfiddle.net/hCRtD/1/

    To prove the demo works, click on some anchors several times before clicking on the last one needed. It won't just complete after 3 clicks total (my original solution was flawed that way), but will wait until each are clicked at least once.

    It sets a special attribute on all <a> tags, uniquely identifying them. Obviously, an id could be used, but you didn't include it and it's easy enough to do this way.

    Then, when an anchor is clicked (only its first time), its unique identifier is added to a collection (clicked).

    When a counter (clicked_count), which is incremented every time an anchor is clicked for the first time, reaches the total number of anchors found in the first place, then everything has completed.