Активный пункт меню
Активный пункт меню — весьма востребованное свойство для любого сайта. И в этой статье мы рассмотрим, как можно силами CSS и небольшого кода JavaScript сделать такое весьма значимое решение на Вашем сайте.
Уверен, Вы не раз сталкивались с подобного рода визуальными эффектами на сайтах и хотели бы реализовать данную возможность у Вас на сайте. Нет проблем, эта статья поможет воплотить Вашу мечту в реальность.
Когда-то давным давно я сам задавался этой проблемой, пока не пришел к выводу, что бесполезно искать какие-то сторонние решения и решил создать свой скрипт, который легок для понимания любому мало-мальски подготовленному программисту в JavaScript, легко встраивается в любой шаблон, дизайн, в любую систему управления сайтом, хоть Joomla, хоть WordPress или иные. Итак, представляю Вашему вниманию активный пункт меню CSS и JavaScript.
Для начала подключаем между тегами
и JQuery библиотеку, вот код.Чтобы более наглядно продемонстрировать Вам всю возможность и порядок действий для начала создайте любое меню между тегами , например, вот такое.
Как мы видим из примера это у нас обычное меню, которому мы присвоили класс menu — учтите, Вы можете присваивать такой класс, который Вы считаете нужным, чтобы у Вас не было проблем с одинаковыми классами меню, настоятельно рекомендую использовать уникальные названия классов.
И вот, мы установили такое меню. Теперь наша задача сделать так, можно сказать, представить в голове, а потом кодом, как нам нужно, чтобы выглядел активный пункт меню при нахождении на соответствующей странице. Для этого мы будем использовать CSS и давайте придумаем класс для нашего активного пункта меню и назовем его active. Учтите, Вы можете назвать его как Вашей душе угодно. Вот примерный код.
Заметьте, все, что Вы пишите в CSS, должно относится к нашему пункту меню, который мы хотим сделать активным. Теперь же нам необходимо сделать маленький скрипт, который бы определял, на какой мы находимся странице, а затем при условии, что эта страница равна нашей запрошенной — присваивал нужному нам пункту меню свой класс active. И наш пункт меню бы окрасился в нужным нам цвет, поменял бы шрифт, или сменил background. Ниже код, не забудьте, вставляем его между тегами
Учтите, что у Вас могут возникнуть вопросы — Вы всегда сможете оставить свои комментарии под этой статьей. Удачи в написании отличных менюшек.
CSS Create active menu point in navigation
The following tutorial shows you how to use CSS to do «CSS Create active menu point in navigation».
CSS Style
The CSS style to do «CSS Create active menu point in navigation» is
.active < background-color:orange; >
HTML Body
body> div> ul id="Category" >"row list-inline"> li> a href="/products/Category/Cars"> Cars li> a href="/products/Category/Cars%20Racer"> Cars MVC li> a href="/products/Category/Bikes" >"active"> Bikes li> a href="/products/Category/Rollers"> Rollers li> a href="/products/Category/Scooters"> Scooters
The following iframe shows the result. You can view the full source code and open it in another tab.
html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> .active !-- w w w . d em o 2 s . co m--> background-color: orange; > body> div> ul id="Category" >"row list-inline"> li> a href="/products/Category/Cars"> Cars li> a href="/products/Category/Cars%20Racer"> Cars MVC li> a href="/products/Category/Bikes" >"active"> Bikes li> a href="/products/Category/Rollers"> Rollers li> a href="/products/Category/Scooters"> Scooters
Related
- CSS Containing background color to individual cells in a navigation menu (Demo 2)
- CSS Containing background color to individual cells in a navigation menu (Demo 3)
- CSS Containing background color to individual cells in a navigation menu (Demo 4)
- CSS Create active menu point in navigation
- CSS Creating a three-column navigation menu. Having trouble with valid structuring that allows independent scrolling
- CSS creating navigational menus in html css javascript jquery
- CSS DIV navigation menu to replace old TABLE menu, element size issue
demo2s.com | Email: | Demo Source and Support. All rights reserved.
CSS menu:active
The following tutorial shows you how to use CSS to do «CSS menu:active».
CSS Style
The CSS style to do «CSS menu:active» is
#menu2 !-- w w w. d e m o 2 s . c o m --> background:black; float:left; list-style:none; margin:0; padding:0; width:220px; > #menu2 li < margin:0; padding:0; > #menu2 a < background:black; border-bottom:1px solid #393939; color:#ccc; display:block; margin:0; padding:9px 16px; text-decoration:none; > #menu2 a:hover < background:black url("../images/select.png") left center no-repeat; color:#fff; padding:9px 16px; > #menu2 a:active < background:red url("../images/select.png") left center no-repeat; color:#fff; padding:9px 16px; >
HTML Body
body> ul id="menu2"> li> a href="index.php?id=home">Home li> a href="index.php?id=about">About us li> a href="index.php?id=contacts">Contacts
The following iframe shows the result. You can view the full source code and open it in another tab.
html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> #menu2 !-- w ww . d e m o 2 s . c o m --> background: black; float: left; list-style: none; margin: 0; padding: 0; width: 220px; > #menu2 li < margin: 0; padding: 0; > #menu2 a < background: black; border-bottom: 1px solid #393939; color: #ccc; display: block; margin: 0; padding: 9px 16px; text-decoration: none; > #menu2 a:hover < background: black url("../images/select.png") left center no-repeat; color: #fff; padding: 9px 16px; > #menu2 a:active < background: red url("../images/select.png") left center no-repeat; color: #fff; padding: 9px 16px; > body> ul id="menu2"> li> a href="index.php?id=home">Home li> a href="index.php?id=about">About us li> a href="index.php?id=contacts">Contacts
Related
demo2s.com | Email: | Demo Source and Support. All rights reserved.
How to Add Active Class to a Navigation Menu Based on URL
When we’re creating a navigation menu for a website, it’s always good to make it so the visitors or user on the website knows on which page or part of the site he is on. This can be accomplished by adding an “active class” or “current class” to the menu item that links to the page on which the visitor or user is.
To do this, we’ll create a css navigation menu. With a few links in it just for demonstration. Of course you can add as many as you want.
Then we add some style to it to make it look like an actual navigation menu.
#nav < margin:200px auto; width:430px; >#nav ul < list-style:none; background-color:#64abfb; >#nav ul li < display:inline-block; line-height:44px; >#nav ul li a < margin:10px; color:#FFF; padding:4px; font-size:20px; text-decoration:none; >#nav ul li a:hover < border-bottom:3px #FFF solid; >#nav ul li .active
After we are done we should have something like this:
Now, you see a class named #nav ul li .active this is not yet added to any of the navigation items. To add it, we need to add some jQuery to our project, that will check the page URL that the user or visitor is viewing, and compares with the one on the menu item. If they mach, it’ll add the .active class to that menu item.
If you don’t have the jQuery library added to your project yet, this won’t work. So to include the library to your project, simply add the following line right before the end of your html tag ( )
And after you are all done with this, your navigation should work properly.
Or, if u want to do it by plain javascript, you can do that too. Here’s how.
First you got to add a #nav ID to your element. Then, use this code to add the active class to the li a element.
function setActive() < aObj = document.getElementById('nav').getElementsByTagName('a'); for(i=0;i=0) < aObj[i].className='active'; >> > window.onload = setActive;
Active Class for WordPress
Incase your WordPress Theme doesn’t support it yet, you can add the following script to your functions.php and use the .active CSS Class to style the current navigation item.
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2); function special_nav_class($classes, $item) < if( in_array('current-menu-item', $classes) )< $classes[] = 'active '; >return $classes; >
If you have any questions or you know an other way to do this or just want to say hi, feel free to leave a comment down below