animate the current_page_item highlight in wordpress using jquery - javascript

I am creating a website for portfolio and learning purpose and I am new to web programming so sorry if i made some stupid mistake in code :)
I want to single page scrolling website with a simple fixed position menu at the top, with little animation during the page scroll for that i took a reference from http://css-tricks.com/jquery-magicline-navigation/. Here is what i achieved so far http://www.pk-pixels.com
Beside on hover event i want the line to animate to next/prev item when user scroll the page upwards or downwards. So i used jquery waypoints plugin to generate an event
I am successfully able to move the highlight to current item when user scrolls the page but only problem is that it does not animate(some time it does strangely....), here i need your help just make that line animate when page scrolls :), here is my js
$(document).ready(function() {
var $menuline = $("#menuline");
linePosition($menuline);
$('#page1').waypoint(function() {
$("#main-menu ul li").removeClass("current_page_item");
$("#main-menu ul #link1").addClass("current_page_item");
linePosition($menuline);
}, { offset: -10 });
$('#page2').waypoint(function() {
$("#main-menu ul li").removeClass("current_page_item");
$("#main-menu ul #link2").addClass("current_page_item");
linePosition($menuline);
});
});
function linePosition($menuline)
{
$menuline
.width($(".current_page_item").width())
.css("left", $(".current_page_item a").position().left);
var $linewidth = $menuline.width();
var $lineposition = $menuline.position().left;
$menuline.animate({
width: $linewidth,
left: $lineposition
});
}
here is html code for the menu
<nav id="main-menu">
<ul>
<li class="current_page_item" id="link1">Home</li>
<li id="link2">About Us</li>
<li id="link3">Services</li>
<li id="link4">Projects</li>
<li id="link5">Contact Us</li>
<div id="menuline-container">
<div id="menuline"></div>
</div>
</ul>
<!-- <?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?> -->
</nav>
Please help me on this one :)
Thanks

Just some ideas that may help
Firstly create real page links for each menu item not just # as the below code depends on what page link is the current page to work
Secondly you have getton rid of the "$("#example-one").append("");" line of the magicline script and hardcoded the magic line and I am not sure that the animation will work this way

here is some code that relates to the current_page_item class - the animation won't work without something like this
<nav id="main-menu">
<li id="link1" role="navigation" class="page_item <?php if(is_page('home')) echo ' current_page_item'; ?>">Home</li>
<li id="link2" role="navigation" class="page_item <?php if(is_page('about-us')) echo ' current_page_item'; ?>"><a href="about-us" >About Us</a></li>
<li id="link3" role="navigation" class="page_item <?php if(is_page('Services')) echo ' current_page_item'; ?>"><a href="Services" >Services</a></li>
/*this link has multiple pages still highlighting Projects as the current_page_item in the case that you have subpages under one menu link*/
<li id="link4" role="navigation" class="page_item <?php if(is_page('projects')) echo ' current_page_item'; ?><?php if(is_page('project_1')) echo ' current_page_item'; ?><?php if(is_page('project-2')) echo ' current_page_item'; ?><?php if(is_page('project-3')) echo ' current_page_item'; ?>">Projects</li>
<li id="link5" role="navigation" class="page_item <?php if(is_page('contact-us')) echo ' current_page_item'; ?>"><a href="contact-us" >Contact Us</a></li>
</ul>
</nav>

Related

Adding dropdown and collapse functions to mobile menu

An issue that’s been bugging me for a while is that by default in the mobile menu of my theme, ALL menu items auto expand so it makes it hard to navigate if you have a lot of sub-menu items.
I’m trying to have my sub-menu items collapse with a drop-down arrow. Something that seems fairly simple but there are no options for adjust this in WordPress.
I managed to find some code in Header.php that you will find below
Any ideas how I can modify this code to have my sub-menu items collapse with a dropdown arrow?
Thanks
Christian
You can do it easily by Bootstrap:
Bootstrap Dropdowns
or, You can also hide dropdowns in css:
li ul{
display: none;
}
and show it on arrow click using jQuery:
$("li a").click(function(){
$(this).parent().find("ul").toggle();
});
Demo:
https://codepen.io/seyyedmojtaba72/pen/VOgmdE
Pure js
let arr=[...document.querySelectorAll(".toggle")];
arr.map(a=> a.onclick = e => {
a.nextElementSibling.classList.toggle('hide');
a.innerHTML = a.innerHTML=='→' ? '↓' : '→';
});
.hide { display: none }
.toggle { cursor: pointer}
<nav>
<ul id='menu'>
<li><a class='home' href='/'>Home</a></li>
<li>
<a class='prett' href='#' >SubMenu A</a>
<span class="toggle">→</span>
<ul class='submenus hide'>
<li><a href='#' >Dropdown 1</a></li>
<li><a href='#' >Dropdown 2</a></li>
</ul>
</li>
<li>
<a class='prett' href='#' >SubMenu B</a>
<span class="toggle">→</span>
<ul class='submenus hide'>
<li><a href='#' >Dropdown 3</a></li>
<li><a href='#' >Dropdown 4</a></li>
</ul>
</li>
<li><a class='home' href='/'>Back</a></li>
</ul>
</nav>
Sorry I had a hard time figuring out how to paste code without errors. Here is my code below. Any way to modify this code to have a collapsible drop down menu on mobile devices?
<!– Toggle button for Main Navigation on mobile –>
<button class=”btn btn-primary header__navbar-toggler hidden-lg-up js-sticky-mobile-option” type=”button” data-toggle=”collapse” data-target=”#shaka-main-navigation”><i class=”fa fa-bars hamburger”></i> <span><?php esc_html_e( ‘MENU’ , ‘shaka-pt’ ); ?></span></button>
<!– Main Navigation –>
<nav class=”header__navigation collapse navbar-toggleable-md js-sticky-desktop-option” id=”shaka-main-navigation” aria-label=”<?php esc_html_e( ‘Main Menu’, ‘shaka-pt’ ); ?>”>
<?php
if ( has_nav_menu( ‘main-menu’ ) ) {
wp_nav_menu( array(
‘theme_location’ => ‘main-menu’,
‘container’ => false,
‘menu_class’ => ‘main-navigation js-main-nav js-dropdown’,
‘walker’ => new Aria_Walker_Nav_Menu(),
‘items_wrap’ => ‘<ul id=”%1$s” class=”%2$s” role=”menubar”>%3$s‘,
) );
}
?>
<?php

Uncaught ReferenceError: ChangeSecondNavUlColor() is not defined - Javascript func not working

Creating a WordPress website.
Have a function ChangeSecondNavUlColor() that is called in the header.php to change the color of the .menu-secondary-menu-links li a (Navigation anchor tags color to white) IF user is not the front-page.php
In the php code, I have an if statement to check if is on front page, if so I AM changing the background color of nav using echo $blackBg; but for the navigation a tag color (since it is nested), i've decided to grab the DOM using javascript.
But getting the following error:
Uncaught ReferenceError: ChangeSecondNavUlColor is not defined
<header class="main-header">
<div id="sidebar-btn">
<span></span>
<span></span>
<span></span>
</div>
<div id="sidebar-nav">
<div class="logo-nav-one-wrap">
<nav class="nav-one">
<li id="primary-headline" class="logo-icon"><img src="#"><?php bloginfo('name'); ?></li>
<ul>
<?php
$args = array(
'theme_location' => 'primary'
);
wp_nav_menu($args);
?>
</ul>
</nav>
</div>
<nav class="nav-two home-nav">
<!-- CHANGE THE BACKGROUND COLOR OF NAV TO BLACK IF NOT HOMEPAGE -->
<?php if(!is_front_page()) {
$blackBg = "background-black-nav"; ?>
<script type="text/javascript"> ChangeSecondNavUlColor(); </script>
<?php } ?>
<div class="nav-two-wrap <?php echo $blackBg;?>">
<?php
$walker = new Nav_Walker_Nav_Menu;
$args = array(
'theme_location' => 'secondary',
'walker' => $walker
);
wp_nav_menu($args);
?>
</div>
</nav>
</div>
JavaScript
function ChangeSecondNavUlColor() {
jQuery(".menu-secondary-menu-links li a").css("color","white !important");
alert("Aasd");
}
Ideas why I'm getting this error and how to fix the issue?
UPDATE 1 - ADDING THE FUNCTIONS.PHP
function ipe_resources() {
// Add stylesheet
wp_enqueue_style('style', get_template_directory_uri().'/css/default.css');
// Add javascript
wp_enqueue_script('script_js', get_template_directory_uri().'/js/ipe_script.js', array('jquery'), '2017', true );
}
add_action('wp_enqueue_scripts', 'ipe_resources');
UPDATE 2: ADDING THE HTML STRUCTURE - I THINK I AM NOT SELECTING THE A TAGS CORRECTLY??
<div class="menu-secondary-menu-links-container">
<ul id="menu-secondary-menu-links" class="menu">
<li id="menu-item-161" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-161"><a title="Our Programs" href="http://localhost/wordpress/courses/">Courses</a></li>
<li id="menu-item-160" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-160"><a title="Event Schedule " href="http://localhost/wordpress/events/">Event Calendar</a></li>
<li id="menu-item-159" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-159"><a title="Registration Open" href="http://localhost/wordpress/book-a-seminar/">Book A Seminar</a></li>
<li id="menu-item-158" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-158"><a title="Registration Open" href="http://localhost/wordpress/book-a-workshop/">Book A Workshop</a></li>
<li id="menu-item-293" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-293">Gallery</li>
</ul>
</div>
You need this line of code:
wp_enqueue_script('script_js', get_template_directory_uri().'/js/ipe_script.js', array('jquery'), '2017', true );
to
wp_enqueue_script('script_js', get_template_directory_uri().'/js/ipe_script.js', array('jquery'), '2017', false);
Changing true to false allows the script to be injected in the header instead of the footer.
For reference: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Another Solution would be to try this:
<script type="text/javascript">
window.onload = function() {
ChangeSecondNavUlColor();
}
</script>
And for your script try this:
function ChangeSecondNavUlColor() {
jQuery("#menu-secondary-menu-links li a").css({"color": "white"});
alert("Aasd");
}

How to add active class to nav ul li a element when it has some sub pages with it?

I am working on Drupal 8 website. In that i having a problem in assigning a active class to nav list elements.
I used the following code to set the active class, it is working for the same url.
The code look like this
<nav id="getnav">
<ul>
<li>
<a class="" data-drupal-link-system-path="user" href="/drupal/todo">Todo</a>
</li>
<li>
<a class="" data-drupal-link-system-path="user" href="/drupal/files">Files</a>
</li>
<li>
<a class="" data-drupal-link-system-path="user" href="/drupal/photos">Photos</a>
</li>
</ul>
</nav>
I used jquery function to set the active class based on the url. Using the following code.
function setActive() {
var myurl =window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$("#getnav ul li a").each(function(){
if($(this).attr("href") == '/drupal/'+myurl )
$(this).addClass("active");
});
}
window.onload = setActive();
The real problem is whenever accessing the subpages like todo/page2 the active class is gone.
http://localhost/drupal/todo :::is working fine but after accessing subpage like
http://loclahost/drupal/todo/add
The class is gone.
Please give me suggestions regarding this problem.
I want to Set The Active class to all of the subpages too.after todo/*
You can do this using pure CSS. You need to add class/id to your body element and your nav li elements, and then you can define combinations of them in your css to be highlighted. For example, suppose this is your html:
< body id="todo_body">
<nav id="getnav">
<ul>
<li class="todo_dropdown">
<a class="" data-drupal-link-system-path="user" href="/drupal/todo">Todo</a>
</li>
<li class="files_dropdown">
<a class="" data-drupal-link-system-path="user" href="/drupal/files">Files</a>
</li>
<li class="photos_dropdown">
</body>
<a class="" data-drupal-link-system-path="user" href="/drupal/photos">Photos</a>
</li>
</ul>
</nav>
</body>
Now, you can use css like given below to apply highlighting styles to your 'should be active' li element:
#todo_body .todo_dropdown,
#files_body .files_dropdown,
#photos_body .photos_dropdown
{
background-color: red;
color: white;
/*Your css styles for active nav item will come here */
}
You can also add any styles to any elements contained in the should be active li element.
<ul class="nav">
<?php
$page_name = basename($_SERVER['PHP_SELF']);
?>
<!-- Main menu -->
<li class="<?php echo ($page_name=='dashboard.php')?'current':'';?>"><i class="glyphicon glyphicon-home"></i> Dashboard</li>
<li class="submenu <?php echo ($page_name=='welcome_note.php' || $page_name=='corporate_profile.php' || $page_name=='introduction_of_the_township.php' || $page_name=='location_map.php')?'current open':'';?>">
<a href="#">
<i class="glyphicon glyphicon-list"></i> Masters
<span class="caret pull-right"></span>
</a>
<!-- Sub menu -->
<ul>
<li class="<?php echo ($page_name=='welcome_note.php')?'current':'';?>">Welcome Note</li>
<li class="<?php echo ($page_name=='corporate_profile.php')?'current':'';?>">Corporate Profile</li>
<li class="<?php echo ($page_name=='introduction_of_the_township.php')?'current':'';?>">The Township</li>
<li class="<?php echo ($page_name=='location_map.php')?'current':'';?>">Location Map</li>
</ul>
</li>
</ul>

Bootstrap Nav Tabs - Fire Javascript

I'm using a basic Bootstrap tab structure, where I wish to fire a Javascript event once the tab is clicked. I can't figure out how to do this. This is the code I have come up with so far:
<ul class="nav nav-tabs nav-justified">
<li class="active"><a data-toggle="tab" href="#tab1"> tab(<?php echo $count ?>) </a></li>
<li><a data-toggle="tab" href="#menu2"> tab(<?php echo $count3 ?>) </a></li>
<li><a data-toggle="tab" href="#menu1"> tab(<?php echo $count2 ?>) </a></li>
</ul>
and the Javascript:
$("#menu2").click(function() {
alert('yes, the click actually happened');
});
$('.nav-tabs a[href="#menu2"]').click(function() {
You have to do:
$('[href=#menu2]').on('shown.bs.tab', function (e) {
alert('Your Code')
});
This event fires on tab show after a tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
http://getbootstrap.com/javascript/

Is there a more efficient way to toggle multiple classes on click than this?

What is a better way to implement this toggle class using JS?
What this is doing is simply this:
When you click either "Services", "Gallery", or "Customer", it removes the class "hidden" in the div below, and adds the class "hidden" to all other lists within the same div.
A live demo of what is happening can be seen here: http://www.cyberbytesdesign.com/WIP2 (it's the main header navigation).
Here is the code that I am using (definitely not an efficient way as this is less than half of all the code, but gets the point across).
<nav>
<ul class="menu-option-set">
<li>
<a href="javascript:;" onmouseup="
document.getElementById('services').classList.toggle('hidden');
document.getElementById('gallery').classList.add('hidden');
document.getElementById('customer').classList.add('hidden');
">Services</a>
</li>
<li>
<a href="javascript:;" onmouseup="
document.getElementById('gallery').classList.toggle('hidden');
document.getElementById('services').classList.add('hidden');
document.getElementById('customer').classList.add('hidden'); ">Gallery</a>
</li>
<li>
<a href="javascript:;" onmouseup="
document.getElementById('gallery').classList.toggle('hidden');
document.getElementById('services').classList.add('hidden');
document.getElementById('customer').classList.add('hidden'); ">Customer</a>
</li>
</ul>
</nav>
<div id="header-subnav">
<nav>
<ul id="services" class="hidden">
<li <?php echo $bathroom ?>>Bathroom</li>
<li <?php echo $kitchen ?>>Kitchen</li>
<li <?php echo $accessibility ?>>Accessibility</li>
</ul>
<ul id="gallery" class="hidden">
<li <?php echo $photo ?>>Photo Gallery</li>
<li <?php echo $project ?>>Project Gallery</li>
</ul>
<ul id="customer" class="hidden">
<li <?php echo $coupons ?>>Coupons</li>
<li <?php echo $testimonials ?>>Testimonials</li>
</ul>
<nav>
</div>
I'm assuming that you have to do something similar to using this somehow, but modified:
$('.menu-option-set a').click(function()
{
// if clicked item is selected then deselect it
if ($('#header-subnav').hasClass('hidden'))
{
$('#header-subnav').removeClass('hidden');
}
// otherwise deselect all and select just this one
else
{
$('.menu-option-set a').removeClass('hidden');
$('#header-subnav').addClass('hidden');
}
});
Any ideas?
Less modification version:
Add data attribute to main menu and set its value to sub menu's id.
<nav>
<ul class="menu-option-set">
<li>
Services
</li>
<li>
Gallery
</li>
<li>
Customer
</li>
</ul>
</nav>
Then attach event handler to main menu. It hides all sub menus, and shows proper sub menu. (Also you don't need 'hidden' class.)
$(function() {
$("#header-subnav ul").hide();
$('.menu-option-set a').on('click', function() {
var $s = $("#" + $(this).attr('data-subid'));
if($s.is(':hidden')) {
$("#header-subnav ul").hide();
$s.show();
} else {
$s.hide();
}
});
});
​
That's all! Here's example: http://jsfiddle.net/dT225/1/
...But I suggest this style personally:
Put sub menus next to each main menu.
<nav id="menu">
<ul>
<li>
Services
<ul>
<li <?php echo $bathroom ?>>Bathroom</li>
<li <?php echo $kitchen ?>>Kitchen</li>
<li <?php echo $accessibility ?>>Accessibility</li>
</ul>
</li>
<li>
Gallery
<ul>
<li <?php echo $photo ?>>Photo Gallery</li>
<li <?php echo $project ?>>Project Gallery</li>
</ul>
</li>
<li>
Customer
<ul>
<li <?php echo $coupons ?>>Coupons</li>
<li <?php echo $testimonials ?>>Testimonials</li>
</ul>
</li>
</ul>
</nav>​​​​​​​​​​​​​
When main menu clicked, event handler will show just next element of source element.
$(function() {
$('#menu li ul').hide();
$('#menu a').on('click', function() {
var $s = $(this).next();
if($s.is(':hidden')) {
$('#menu li ul').hide();
$s.show();
} else {
$s.hide();
}
});
});
​It's more simple, maintainable, and semantic I think. http://jsfiddle.net/dKtVK/1/
First of all thumbs up for trying to do this with plain javascript. Note however, that using things like classList is not supported in every browser - your code will fail in IE.
To your question: You almost answered your question by yourself. It is strongly advised to NOT use those event attributes an the elements. Instead put it into (a separated) js (file). This makes your code clean and maintainable.
So write this instead:
<a class="services" href="javascript:;">Services</a>
and then add an eventhandler in your <script> Tag or separate JS-File:
var gallery = document.getElementById('gallery');
var services = document.getElementById('services');
var customer = document.getElementById('customer');
document.querySelector(".services").addEventListener(function(){
/* Do your stuff here */
gallery.classList.toggle('hidden');
/*...and so on...*/
});
I used querySelector here, because it is quite similar to jQuery, thus familiar to lot of people, and supported in IE >=8. But feel free to use whatever suits you (and is needed for browser-support).
Using jQuery (the second codesnippet you posted) makes this quite a lot easier and is working fine in all browsers, so feel free to use it and save you some work.

Categories

Resources