william44isme
william44isme

Reputation: 877

Toggle window.location in jQuery/javascript

What I am trying to achieve is that whenever you click an image, it changes the window.location url, toggling it between '#' and '#footer'. Right now, all I have is this:

<script>
function clickarrow(){

    var rd=Math.floor(Math.random()*11)

    if (rd > 5){
        window.location="#footer";      
        }

    else{
        window.location="#";
    }
}
</script>

As you can see, this makes a 50:50 chance of either change being made. It works as a temparary fix, but sometimes you have to click up to 6 times for it to take effect.

Is there a way of doing this that properly toggles the window.location?

I am using jQuery 1.9.

Upvotes: 3

Views: 1883

Answers (2)

nandin
nandin

Reputation: 2575

you can use data attribute to tell what is next step:

$('#arrow').click(function() {
    if ($(this).data('footer'))
    {
        window.location="#footer"; 
        $(this).data('footer', 'false');
        alert('b');
    }
    else
    {
        window.location="#";
        $(this).data('footer', 'true');
        alert('a');
    }
});

Upvotes: 1

Platinum Azure
Platinum Azure

Reputation: 46193

If you're trying to reliably toggle the hash, rather than using a random chance, try something like this:

function clickarrow(){
    var showFooter = true;

    return function () {
        if (showFooter) {
            window.location.hash = "footer";
        } else {
            window.location.hash = "";
        }

        showFooter = !showFooter;
    }
}

jQuery(function () {
    jQuery('#myToggleLink').click(clickarrow());
});

Note: Normally when binding events, a function reference must be passed in. Here, I'm invoking clickarrow() since it returns a function by design. The returned function encapsulates the toggle variable via closure.

Upvotes: 3

Related Questions