Steve Jobs Steve Jobs - 1 year ago 59
Javascript Question

Change href onclick with multiple variables

I know very little about js so please be gentle.

I'm using the below code which was originally used to swap classes. I thought it would be as simple as changing

but I was wrong.

My problem is that it works once and then stops.

$('#click').click(function () {
var classes = ['/1','/2','/3','/4'];
this.href = classes[($.inArray(this.href, classes)+1)%classes.length];

Here is the html I'm using:

<a id="url" href="/0">hello</a>

My goal is to switch /0 with /1 then /2 and so on with each onclick.

Answer Source

You can use .attr(), set a varible to -1. At click event handler increment variable utilize remainder operator, classes.length

$(document).ready(function() {
  var classes = ['/1','/2','/3','/4'];
  var i = -1;
  var url = $("#url");
  $('#click').click(function () {
    url.attr("href", classes[++i % classes.length]);
<script src="">
<button id="click">click</button>
<a id="url" href="/0">hello</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download