javascript - jQuery: Add class depending on URL in the best way -
i have html progress meter:
<div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> login </div> </div> </div> <div class="col-md-3 progress-pos-container"> <div class="progress-pos" id="progess-2"> <div class="progress-pos-inner"> scan items </div> </div> </div> <div class="col-md-3 progress-pos-container"> <div class="progress-pos" id="progess-3"> <div class="progress-pos-inner"> confirm address </div> </div> </div> <div class="col-md-3 progress-pos-container"> <div class="progress-pos" id="progess-4"> <div class="progress-pos-inner"> finished </div> </div> </div>
i use following jquery add/remove classes depending on url.
$( document ).ready(function() { if(location.search == "?route=account/login&ssl"){ $("#progess-1").addclass("active"); } if(location.search == "?route=checkout/cart"){ $("#progess-2").addclass("active"); $("#progess-1").addclass("inactive"); } if(location.search == "?route=checkout/checkout"){ $("#progess-3").addclass("active"); $("#progess-1").addclass("inactive"); $("#progess-2").addclass("inactive"); } if(location.search == "?route=checkout/success"){ $("#progess-4").addclass("active"); $("#progess-1").addclass("inactive"); $("#progess-2").addclass("inactive"); $("#progess-3").addclass("inactive"); } });
i know isn't best way acomplish (even though code work), have repeat same thing on , over. have tried prev()
didn't seem work.
what best way go it?
edit: clear, not elements apart 1 active
class should given class of active
, ones prior.
edit 2:
current activity:
user on page ?route=account/login&ssl
, #progress-1
give class of .active
.
user progresses ?route=checkout/cart
sucessfully, , #progress-1
given class of .inactive
, #progress-2
.active
user progresses ?route=checkout/checkout
sucessfully, , #progress-1
& #progress-2
given class of .inactive
, #progress-3
.active
, on.
$( document ).ready(function() { // re-set on entry $("#progess-1, #progess-2, #progess-3, #progress-4").removeclass("inactive active"); // check correct 1 make active if(location.search == "?route=account/login&ssl") $("#progess-1").addclass("active"); else if(location.search == "?route=checkout/cart") { $("#progess-2").addclass("active"); $("#progess-1").addclass("inactive"); } else if(location.search == "?route=checkout/checkout") { $("#progess-3").addclass("active"); $("#progess-1,#progess-2").addclass("inactive"); } else if(location.search == "?route=checkout/success") { $("#progess-4").addclass("active"); $("#progess-1,#progess-2,#progess-3").addclass("inactive"); } });
this can achieved replacing if statement switch.
Comments
Post a Comment