Steve Jobs Steve Jobs - 2 months ago 13
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

.className
to
.href
but I was wrong.

My problem is that it works once and then stops.

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


EDIT:
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

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]);
    console.log(url.attr("href"))
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button id="click">click</button>
<a id="url" href="/0">hello</a>