Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make buttons remain 'active' after they're clicked?

I'm currently using the following code for my menu items:

HTML

<li>
<a id="About" class="button" href="About Us.cshtml">About Us</a>
</li>
<li style="margin-left: 30px;">
<a id="Services" class="button" href="Services.cshtml">Services</a>
</li>
<li style="margin-left: 30px;">
<a id="Contact" class="button" href="Contact Us.cshtml">Contact Us</a>
</li>

CSS

#About {background-image: url(../Buttons/About.png); width: 87px;}
#Services {background-image: url(../Buttons/Services.png); width: 112px;}
#Contact {background-image: url(../Buttons/Contact.png); width: 117px;}
a.button {height: 20px; display: inline-block; background-repeat: no-repeat}
a.button:hover {background-position: 0 -20px;}
a.button:active {background-position: 0 -40px;}

I need to get the buttons to remain in the 'active' state after they're clicked and the page loads/refreshes etc.

If the solution requires javascript, please bear in mind that I'm a rank amateur so I'll need any explanations in layman's terms (preferably with examples).

like image 887
OCD Avatar asked Nov 30 '12 17:11

OCD


1 Answers

You need to identify the page you are currently on.

var page = window.location.href;
page = page.substr((page.lastIndexOf('/') + 1));
page = page.split('.');
page = page[0];
//At this point you will have the current page only with no extension or query paramaters
//I.E. "About Us"
page = page.toUpperCase();
//This accounts for upper or lower casing of urls by browsers.
switch(page) {
    case "ABOUT US":
        $('#About').addClass('< name of active button class >');
        break;
    case "SERVICES":
        $('#Services').addClass('< name of active button class >');
        break;
    case "CONTACT US":
        $('#Contact').addClass('< name of active button class >');
        break;
}

If you're not using jQuery replace this line:

$('#< element name >').addClass('< name of active button class >');

with this line:

document.getElementById("< element name >").className += " < name of active button class >";

Hope this helps.

like image 188
War10ck Avatar answered Sep 16 '22 19:09

War10ck