Paul
Paul

Reputation: 3368

How to detect a page and modify a class based on it

I am creating a bar with 4 pieces to it. Each piece will lead to and be a different page. What I am wanting to do is if the user is on page A for example, I want the background for that service-specificBar-tab to be a certain color. For example sake, red. Then if the user is on B for the background of that service-specificBar-tab to be another different color, ie: purple.

So basically, how would I go about detecting which page the user is on and making the service-specificBar-tab be a certain color? OR is there a different way to do this without detecting a page?

#gray {
	background: #f9f9f9;
	width: 100%;
	height: 700px;
	position: relative;
}
#service-specificBar-container {
	position: relative;
	top: 300px;
	width: 100%;
	padding: 25px 0;
}
#service-specificBar {
	width: 100%;
	height: 100px;
	border: 1px solid black;
}
.service-specificBar-tab {
	width: 25%;
	height: 100%;
	display: inline-block;
	margin: 0;
	padding: 0px;
}
.service-specificBar-tab:nth-child(2) {
	background: blue;
}
.service-specificBar-tab:nth-child(4) {
	background: green;
}
<div id="gray">
		<div id="service-specificBar-container">
			<div id="service-specificBar"><div class="service-specificBar-tab">A
				</div><div class="service-specificBar-tab">B
				</div><div class="service-specificBar-tab">C
				</div><div class="service-specificBar-tab">D
				</div>
			</div>
		</div>
	</div>

Upvotes: 0

Views: 27

Answers (1)

Mark E
Mark E

Reputation: 3483

You can find the actual url with window.location.href, so then you just make a switch to change the color of a certain div. I would also recommend, although it's not necessary, to add an id to each service-specificBar-tab.

Example:

switch( window.location.href ){
    case "http://example.com/myFirstPage":
        $("#firstItemId").addClass("active");
        break;

    case "http://example.com/mySecondPage":
        $("#secondItemId").addClass("active");
        break;
}

And if you want it to be a different color for each active tab define it in your css

#firstItemId.active {
    background-color: red;
    /* active css */
}

If there is the possibility of arriving there with a hash on the url, you can remove it like this:

var url = window.location.href.split("#")[0];

Upvotes: 1

Related Questions