Keep active class on gallery navigation when using pagination - javascript

I have the following navigation on the gallery page of my website that allows users to filter the images by category.
<ul>
<li>All</li>
<li>Our Gym</li>
<li>Our Classes</li>
<li>Our Coaches</li>
</ul>
I've added the following snippet to add the class 'active' the category that is currently being viewed by the user.
<script>
jQuery(function($) {
var path = window.location.href;
$('.gallery_listing_wrapper li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
</script>
This works for the above gallery navigation however once I navigate using the pagination it doesn't work.
The URL for the pagination is slightly different to the gallery and its categories.
For example - instead of /gallery/our-gym/ - page/ and the page number is added to the URL i.e. /gallery/page/2/
Is it possible to adjust the above snippet to keep the active class on All when the pagination is being used?

You could always just add the class to the "All" button if none of the other buttons match the current URL.
<script>
jQuery(function($) {
var path = window.location.href;
let match = $(`.gallery_listing_wrapper li a[href="${path}"]`);
if(match.length >= 1)
match.addClass("active");
else
$(".gallery_listing_wrapper li a[href='/gallery/']").addClass("active");
});
</script>

Related

Add active Menu or Navigation class based on URL

I've added an active class to my menu items. However my current implementation is adding the class to all list menu items as opposed to whatever the current page is.
Please let me know if there is an issue with my current code, and what I can do to achieve the desired outcome.
<ul id="menu_items">
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
$(function(){
var current = location.pathname;
$('#menu_items li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
.active {text-decoration:underline;}
Okay, Try this way, hope it will work
<ul id="menu_items">
<li>Index</li>
<li class="has-sub">STORE</li>
<li>RESEARCH</li>
<li>INFO</li>
</ul>
</html>
<Script>
$("#menu_items li").bind("click", function(e){
$("li").click(function() {
$(this).siblings().find("a").removeClass("active");
$(this).find("a").addClass("active")
})
})
</Script>
Please Check the URLs , All the Links are "/collections"

How to keep the active menu item highlighted when visiting pages in ASP.Net MVC 5 application?

So, I have one ASP.Net MVC 5 application. In that one of page hasfour menu items. When page loads first menu item is selected by default (so it should be highlighted as soon as the page loads). And now as soon as user clicks on any other menu, that other menu should be in highlighted stage, so that user knows which menu he is currently on. Below is my attempt:
My thinking:
a. add a click event on the ul tag.
b. when clicked find "active" class inside ul tag and remove it.
c. now add active class to the source of click event (which means the li tag on which user clicked).
Issue:
The selected/clicked menu gets highlighted for a second, and then
automatically first menu gets highlighted. So as soon as the whole
page corresponding to the newly clicked menu item reloads the first
menu item gets highlighted back.
My Attempt
P.S: This is a partial View, And all redirects will load this partial view afresh.
#if (Request.IsAuthenticated)
{
<ul style="list-style-type:none;">
<li class="active setBtnMargin">
My Resume
</li>
<li class="setBtnMargin">
My Cover Letter
</li>
<li class="setBtnMargin">
My Account
</li>
<li class="setBtnMargin">
Get Rewards
</li>
</ul>
}
<script>
// ATTEMPT 1
$("ul").on("click", "li", function () {
$('ul li').removeAttr('active');
$(this).addClass('active');
});
// ATTEMPT 2
//$("li").click(function () {
// //$("ul li").removeClass("active");
// $(this).addClass("active");
//});
</script>
EDIT 1
So the problem is as the page gets redirected. The active tag again gets appened to the first menu item when entire DOM gets reloaded because all the landing pages use the same partial view.
Everytime you click on a link, it does a page redirect, and it doesn't matter what changes you've made with jQuery, it always fetch this partial view, and in this partial view, you have active class on the first link, that is why it always highlights the first link.
What you have to do is write an HtmlHelper that will add the class "active" to current link on each page load. Create a folder called Helpers under your project and add a custom HtmlHelper class.
using System;
using System.Web.Mvc;
public static class ActiveMenuHelper
{
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string areaName)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
var currentArea = htmlHelper.ViewContext.RouteData.DataTokens["area"];
var builder = new TagBuilder("li")
{
//InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString()
InnerHtml = "" + linkText + ""
};
if (String.Equals(controllerName, currentController, StringComparison.CurrentCultureIgnoreCase) && String.Equals(actionName, currentAction, StringComparison.CurrentCultureIgnoreCase))
builder.AddCssClass("active");
return new MvcHtmlString(builder.ToString());
}
}
and then in your partial view:
#using YourProjectName.Helpers
<ul>
#Html.MenuLink("Resume", "Index", "Resume", "" )
#Html.MenuLink("Cover Letter", "Index", "CoverLetter", "" )
</ul>
You might not need the area, that is why you can leave it blank, i put it in here just in case.
Try adding this to your shared view . normally "_Layout".
#{
string pageUrl = Request.Url.PathAndQuery.ToString();
}
and instead of adding "active" class from the html markups, add conditional statement that will check the pageUrl just like the code below.
#if (Request.IsAuthenticated)
{
<ul style="list-style-type:none;">
<li class="#(pageUrl.ToLower().Contains("/index/Resume") ? "active" : string.Empty) setBtnMargin">
My Resume
</li>
<li class="#(pageUrl.ToLower().Contains("/index/CoverLetter") ? "active" : string.Empty) setBtnMargin">
My Cover Letter
</li>
<li class="#(pageUrl.ToLower().Contains("/index/Home") ? "active" : string.Empty) setBtnMargin">
My Account
</li>
<li class="#(pageUrl.ToLower().Contains("/index/Home") ? "active" : string.Empty) setBtnMargin">
Get Rewards
</li>
</ul>
}
You have to add document ready function.
<script>
$(document).ready(function(){
$("ul").on("click", "li", function () {
$('ul li').removeAttr('active');
$(this).addClass('active');
});
});
</script>
Try this sample one. it works for me. :) :)
<script>
$(document).ready(function(){
$(window).load(function(){
var x = window.location.href;
$('ul a[href="'+x+'"]').each(function() {
if(x == window.location.href){
$('ul li').removeClass('active');
$(this).parent('li').addClass('active');
}
});
});
});
</script>
I took a different approach, leveraging the fact that I use a load script for each partial view to load data into DataTables on that view.
I started by added an "id" to each of the menu items.
<ul class="nav navbar-nav">
<li id="Index"><a asp-page="/Index">Reportables</a></li>
<li id="TaskAssayExclusion"><a asp-page="/TaskAssayExclusion">Task Assay Exclusions</a></li>
<li id="SpecimenSite"><a asp-page="/SpecimenSite">Specimen Site</a></li>
<li id="SnomedCT"><a asp-page="/SnomedCT">Snomed CT</a></li>
<li id="Loinc"><a asp-page="/Loinc">LOINC</a></li>
<li id="Search"><a asp-page="/Search">Search Messages</a></li>
</ul>
At the bottom of each partial view I have a snippet of JavaScript that gets executed when that view loads. An example of the snippet for the Index page is shown below.
<script type="text/javascript">
function partialIndexModelScript() {
$('li#Index').addClass('menu_item_active');
filterLoadComplete = false;
selectLoadComplete = false;
loadReportableResultData();
}
</script>
In my main JavaScript file, near the end of the $(document).ready() function I use 'typeof' to execute the relevant JavaScript snippet.
if (typeof partialIndexModelScript !== "undefined") partialIndexModelScript();
if (typeof partialSpecimenSiteModelScript !== "undefined") partialSpecimenSiteModelScript();
if (typeof partialNormalcyModelScript !== "undefined") partialNormalcyModelScript();
if (typeof partialSnomedCTModelScript !== "undefined") partialSnomedCTModelScript();
if (typeof partialLoincModelScript !== "undefined") partialLoincModelScript();
if (typeof partialTaskAssayExclusionModelScript !== "undefined") partialTaskAssayExclusionModelScript();
if (typeof partialSearchModelScript !== "undefined") partialSearchModelScript();
And finally the CSS which is nearly identical to the :hover CSS except that
I've included the font-weight: bolder !important to really make the selected menu item stand out.
.menu_item_active {
color: #B8B7DA !important;
background-color: #514689 !important;
text-decoration: underline !important;
font-weight: bolder !important;
}
The final result:

Set menu item active based on URL

I've been trying really hard to accomplish what I'm trying to accomplish, but I can't get it to work the way I want. I have a navigation menu with first-level menu items (duh) and second-level menu items. It looks like this:
<ul class="nav" id="side-menu">
<li>
Dashboard
</li>
<li>
Pages
</li>
<li>
Users<span class="fa arrow"></span>
<ul class="nav nav-second-level">
<li>
All users
</li>
<li>
Roles
</li>
</ul>
</li>
</ul>
I'm using the following jQuery function to add the active class to active menu items:
function setActive() {
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')) {
element.addClass('active');
}
// Remove active class from A element if the page isn't the dashboard.
if (location.pathname !== '/admin/' && $('[href="/admin/"]').hasClass('active')) {
$('[href="/admin/"]').removeClass('active');
}
};
This works fine for all first-level menu items and for the second-level menu item All users, but when I go to /admin/users/roles/, it makes All users and Roles active. The same thing happens when I go to /admin/users/roles/add/. I think this happens because the code makes all menu items active which look like the window.location, but I don't know how to only make Roles active when I go to /admin/users/roles/ and /admin/users/roles/add/, etc.
I really hope someone can help me with this. If you can, I'll buy you a beer.
try this..
var loc = window.location.pathname;
$('#side-menu').find('a').each(function() {
$(this).toggleClass('active', $(this).attr('href') == loc);
});
and ue full absolute path in href i.e.http://yourdomain.com//admin/users/roles/

Add a active link to custom ul in wordpress

I have a custom list(ul) in wordpress sidebar. I want to add active class to list items.
<ul class="sidebar-list">
<li> OWLE</li>
<li>Sink or Swim</li>
<li>Swim and Survive</li>
<li>VWSC</li>
<li>Water Smart</li>
<li>Grey Medallion</li>
<li>Aquatic PD Workshops</li>
<li>Edu From Anywhere</li>
<li>Bronze e-Lifesaving</li>
<li>Water Smart Award</li>
<li>Victorian Water Safety Certificate</li>
<li>Edu From Anywhere Newsletter</li>
<li>Edu Casual Instructor</li>
<li>Grey Medallion</li>
<li>Sink or Swim</li>
<li>Edu Instructor of year Profile</li>
<li>Swim & Survive Licensee of year</li>
</ul>
<li class="active"> OWLE</li>
should look like on 'index.php/owle/'.
Add this to your wordpress them's custom javascript. Lot of themes have that. Check theme customization.
var url = window.location;
// Will only work if string in href matches with location
$('sidebar-list li a[href="'+ url +'"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('sidebar-list li a').filter(function() {
return this.href == url;
}).parent().addClass('active');
if your theme don't have this you have to hardcode this. I recommend you add this to your footer.php
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 '; // your new class
}
return $classes;
}
Try this code, It Works. All you have to do is juss change those class names with the classes you are using.
you no need to do coding for it.
create sidebar with wordpress menu.
wordpress menu have default class for currunt item
current-menu-item
and you can add css to it ..

Add Active Class for any URL match to first segment?

My Javascript is adding the active class to all links with one segment that match my path variable, but not ones with two on my nav.
I want it regardless to check the first segment of any URL that is currently in the window.location.pathname and if the first segment matches then add the active class to the nav item.
It works for home, products and gallery. But when I console.log(linkPath) it's showing for the url products/samples the text sample and not products. Thus there is no math and it will not add the active class to the current item.
How Can I get it to add the active class no matter what based off the first segment matching within any url with more than one segment?
HTML
<nav class="navbar" role="navigation">
<h2 class="markup">Main Navigation</h2>
<div class="collapse navbar-collapse main-nav-list navbar-link-background">
<ul class="nav navbar-nav">
<li>Home
</li>
<li>Products
</li>
<li>Gallery
</li>
<li>Promotions
</li>
<li>Samples
</li>
</ul>
</div>
</nav>
Javascript
var url = window.location.pathname.split( '/' ),
path = url[1];
/* Get URL For Setting Active Nav List Item */
$(".navbar-nav").children("li").each(function() {
var link = $(this).children("a").attr("href"),
linkPathIndex = link.lastIndexOf("/")+1,
linkPath = link.substring(linkPathIndex);
if (linkPath == path) {
$(this).addClass("active");
}
});
Why dont you check for the pathname directly in the link href? something like this:
$(".navbar-nav").children("li").each(function() {
var link = $(this).children("a").attr("href");
if(link.indexOf(path) > -1){
$(this).addClass("active");
return;
}
});
This is what I use:
this.win.on(events.load, function() {
var anchors = self.list.prev().find(cache.anchor),
url = document.URL;
$.each(anchors, function() {
var anchor = $(this),
href = anchor.prop('href');
if (url.indexOf(href) !== -1) {
anchor.addClass(classes.active);
}
});
});

Categories

Resources