Html menu link active

Активный пункт меню

Активный пункт меню — весьма востребованное свойство для любого сайта. И в этой статье мы рассмотрим, как можно силами CSS и небольшого кода JavaScript сделать такое весьма значимое решение на Вашем сайте.

Уверен, Вы не раз сталкивались с подобного рода визуальными эффектами на сайтах и хотели бы реализовать данную возможность у Вас на сайте. Нет проблем, эта статья поможет воплотить Вашу мечту в реальность.

Когда-то давным давно я сам задавался этой проблемой, пока не пришел к выводу, что бесполезно искать какие-то сторонние решения и решил создать свой скрипт, который легок для понимания любому мало-мальски подготовленному программисту в JavaScript, легко встраивается в любой шаблон, дизайн, в любую систему управления сайтом, хоть Joomla, хоть WordPress или иные. Итак, представляю Вашему вниманию активный пункт меню CSS и JavaScript.

Для начала подключаем между тегами и JQuery библиотеку, вот код.

Чтобы более наглядно продемонстрировать Вам всю возможность и порядок действий для начала создайте любое меню между тегами , например, вот такое.

Как мы видим из примера это у нас обычное меню, которому мы присвоили класс menu — учтите, Вы можете присваивать такой класс, который Вы считаете нужным, чтобы у Вас не было проблем с одинаковыми классами меню, настоятельно рекомендую использовать уникальные названия классов.

И вот, мы установили такое меню. Теперь наша задача сделать так, можно сказать, представить в голове, а потом кодом, как нам нужно, чтобы выглядел активный пункт меню при нахождении на соответствующей странице. Для этого мы будем использовать CSS и давайте придумаем класс для нашего активного пункта меню и назовем его active. Учтите, Вы можете назвать его как Вашей душе угодно. Вот примерный код.

Читайте также:  Opencart system startup php

Заметьте, все, что Вы пишите в CSS, должно относится к нашему пункту меню, который мы хотим сделать активным. Теперь же нам необходимо сделать маленький скрипт, который бы определял, на какой мы находимся странице, а затем при условии, что эта страница равна нашей запрошенной — присваивал нужному нам пункту меню свой класс active. И наш пункт меню бы окрасился в нужным нам цвет, поменял бы шрифт, или сменил background. Ниже код, не забудьте, вставляем его между тегами

Учтите, что у Вас могут возникнуть вопросы — Вы всегда сможете оставить свои комментарии под этой статьей. Удачи в написании отличных менюшек.

Источник

Активный пункт меню на JavaScript?

Хотел себе разработать: адаптивное меню с активным пунктом меню при её посещении.

— Главная
— Книги
— Истории
— Профиль

При нахождении на главной странице сайта, нужно чтобы подсвечивалась — главная (она же с SVG) у пользователя при посещении главной страницы с телефона.

Решил поступить таким путем.

 

Первое время думал, можно реализовать только используя HTML & CSS, но похоже это не так.

Но ничего не выходит. Изначально (как я думал) он должен был захватить тег (a) вместе с (svg) и (div). Тем самым покрасив — главную и SVG в один цвет, благодаря классу active. Но ничего не вышло. Только удалось окрасить (svg) иконку, точней, только он и окрашивается, на текст — главная, плевать хотел JS.

Не могу понять в чем моя проблема.

Также, хотел бы у вас узнать, как можно этот скрипт JS подключить грамотно внутри тега (head), чтобы он работал и моментально отображался, вовсе не пока прогрузится страница. Пробовал подключать, он просто не работает, как и Owl-carousel, только перед (body).

Если говорить в целом, то, просто хотел реализовать меню навигации как у ivi.ru под мобильные устройства и планшеты (320-1024px) и также как у неё активный пункт меню.

61cb24e0975f8231129513.png

p.s буду очень рад, вашей помощи.

Источник

I am using some jquery code to highlight the current active page on my site. It is working great for the page. but when I am linking the menu to any div id it is not highlighting. how can I make it work for id as well. Here is my code:

can you post a fiddle with the problem? I don’t understand what you mean by «linking the menu to any div id»

say I have a div which id is #contact . I have a menu named contact, I have linked this div to that contact menu. when I click on the contact link it is scrolling to that #contact div but It is not highlighting as active section.

4 Answers 4

 var url = window.location; var element = $('ul.nav a').filter(function() < return this.href == url || url.href.indexOf(this.href) == 0; >).addClass('active').parent().parent().addClass('in').parent(); if (element.is('li'))

Oops, nevermind. I was thinking folders «example.com/content» & «example.com/content1». Anyway, he’s using anchors.

For this reason he said that when link to anchors the menu link lost the highlight.. well in this way don’t lost it.

Based on the comments, I assume that you are trying to highlight the div as well the menu clicked.

You can use the below code. It will scroll the div as well as highlight the target div as well as the menu linked clicked.

$(function() < // this will get the full URL at the address bar var url = window.location.href; $(".menu_holder a").on('click',function(event) < event.preventDefault(); var selectedDiv = $(this).attr('href'); $('html, body').animate(< scrollTop: $(selectedDiv).offset().top - 20 >, 'slow'); $(selectedDiv).addClass("active"); $(this).addClass("active"); >); >); 
        
Home contact
contact section

Suppose you have this html:

 
Div 1 Div 2
content 1
content 2

if you want to highligth the anchor after the click you can use this code that merges yours and adds what you are looking for:

var url = window.location.href;

$(".Menu a").each(function(e) < if (url == (this.href)) < $(this).addClass("Active"); >>).on("click", function(e) < var a = this; setTimeout(function() < if (window.location.href == a.href) $(a).addClass("Active"); >, 0); >); 

I used setTimeout (. 0) to make the browser process the click and change the location.

That is because window.location.href gives you the actual, absolute URL of the page — for example, http://stackoverflow.com/questions/38541730/highlight-active-link-on-menu#contact . But, most probably your link has an href that is relative — basically, this.href is probably just #contact .

I think a better solution would be to use a regular expression like this to get the relative url:

window.location.href.match(/#.*/) //gives you $contact" 

EDIT: Thanks to Mottie, here’s an even better solution:

window.location.hash //gives you "#contact" 

Источник

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.

Active Class to a Navigation Menu Based on URL

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:

active1

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.

active2

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

Источник

Оцените статью