harley_woop February 2016

jQuery: Add class depending on URL in the best way

I have this HTML for a 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 the following jQuery to add/remove classes depending on the 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 that this isn't the best way to acomplish this (Even though the code does work), as I have to repeat the same thing over and over. I have tried prev() but it didn't seem to work.

What is the best way to go about it?

<

Answers


Jordan Lowe February 2016

$( document ).ready(function() {

    // Re-set all on entry
    $("#progess-1, #progess-2, #progess-3, #progress-4").removeClass("inactive active");

    // Then check for the correct one to 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 also be achieved by replacing the if statement with a switch.

Post Status

Asked in February 2016
Viewed 2,915 times
Voted 12
Answered 1 times

Search




Leave an answer