Trigger event when clicking on anchor element
I have a list like this:
<ul class="titles clearfix">
<li class="opened">Billing Address</li>
<li class="">Shipping Address</li>
<li class="">Review Order</li>
</ul>
And the button:
<a href="#">Next</a>
How it works:
The first item in the list is opened by default (it has an "open" class), and if I click on "Shipping address" (only if I click), the "open" class will apply to the "shipping address".
What I want to do is when I click next to open "Shipping Address" and if I click again to open "View Order".
Basically, I need to do when "next" is clicked to click on "Shipping address" for example.
How can i do this?
source to share
You can use addClass()
both removeClass()
to set the class as needed and next()
to get the next item li
. Try the following:
$('a').click(function(e) {
e.preventDefault();
$('li.opened').removeClass('opened').next().addClass('opened');
});
If necessary, you will need to implement some logic to prevent the user from going through the third item li
.
source to share
var i = 2 ;
var len = $("ul li").length;
$('a').on('click', function(){
$("ul li.opened").removeClass('opened');
$("ul li:nth-child("+ i +")").addClass('opened');
console.log(i, len);
if (i == len) {
i = 1;
}else{
i++;
}
});
.opened{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<ul class="titles clearfix">
<li class="opened">Billing Address</li>
<li class="">Shipping Address</li>
<li class="">Review Order</li>
</ul>
<a href="#">Next</a>
source to share