I'm trying to edit a shopify theme and the last part I'm stuck on is getting these navigation menus to open on hovering instead of clicking. The css I have for the menus is:
.site-nav {
position: relative;
padding: 0;
text-align: center;
margin: 25px 0;
a {
padding: 3px 10px;
}
li {
display: inline-block;
}
}
.site-nav--centered {
padding-bottom: $gutter-site-mobile;
}
/*================ Site Nav Links ================*/
.site-nav__link {
display: block;
white-space: nowrap;
.site-nav--centered & {
padding-top: 0;
}
.icon-chevron-down {
width: 8px;
height: 8px;
margin-left: 2px;
.site-nav--active-dropdown & {
transform: rotateZ(-180deg);
}
}
&.site-nav--active-dropdown {
border: 1px solid $color-border;
border-bottom: 1px solid transparent;
z-index: 2;
}
}
/*================ Dropdowns ================*/
.site-nav--has-dropdown {
position: relative;
}
.site-nav--has-centered-dropdown {
position: static;
}
.site-nav__dropdown {
display: none;
position: absolute;
left: 0;
padding: $dropdown-padding;
margin: 0;
z-index: $z-index-dropdown;
text-align: left;
border: 1px solid $color-border;
background: $color-bg;
left: -1px;
top: 41px;
.site-nav__link {
padding: 4px 30px 4px 0;
}
.site-nav--active-dropdown & {
display: block;
}
li {
display: block;
}
}
// Centered dropdown
.site-nav__dropdown--centered {
width: 100%;
border: 0;
background: none;
padding: 0;
text-align: center;
}
The HTML and Liquid for the header is:
{% if section.settings.align_logo == 'left' %}
<nav class="grid__item medium-up--one-half small--hide" id="AccessibleNav" role="navigation">
{% include 'site-nav' %}
</nav>
{% endif %}
And the relevant menu Javascript:
/* ================ MODULES ================ */
window.theme = window.theme || {};
theme.Header = (function() {
var selectors = {
body: 'body',
navigation: '#AccessibleNav',
siteNavHasDropdown: '.site-nav--has-dropdown',
siteNavChildLinks: '.site-nav__child-link',
siteNavActiveDropdown: '.site-nav--active-dropdown',
siteNavLinkMain: '.site-nav__link--main',
siteNavChildLink: '.site-nav__link--last'
};
var config = {
activeClass: 'site-nav--active-dropdown',
childLinkClass: 'site-nav__child-link'
};
var cache = {};
function init() {
cacheSelectors();
cache.$parents.on('click.siteNav', function(evt) {
var $el = $(this);
if (!$el.hasClass(config.activeClass)) {
// force stop the click from happening
evt.preventDefault();
evt.stopImmediatePropagation();
}
showDropdown($el);
});
// check when we're leaving a dropdown and close the active dropdown
$(selectors.siteNavChildLink).on('focusout.siteNav', function() {
setTimeout(function() {
if ($(document.activeElement).hasClass(config.childLinkClass) || !cache.$activeDropdown.length) {
return;
}
hideDropdown(cache.$activeDropdown);
});
});
// close dropdowns when on top level nav
cache.$topLevel.on('focus.siteNav', function() {
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
});
cache.$subMenuLinks.on('click.siteNav', function(evt) {
// Prevent click on body from firing instead of link
evt.stopImmediatePropagation();
});
}
function cacheSelectors() {
cache = {
$nav: $(selectors.navigation),
$topLevel: $(selectors.siteNavLinkMain),
$parents: $(selectors.navigation).find(selectors.siteNavHasDropdown),
$subMenuLinks: $(selectors.siteNavChildLinks),
$activeDropdown: $(selectors.siteNavActiveDropdown)
};
}
function showDropdown($el) {
$el.addClass(config.activeClass);
// close open dropdowns
if (cache.$activeDropdown.length) {
hideDropdown(cache.$activeDropdown);
}
cache.$activeDropdown = $el;
// set expanded on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'true');
setTimeout(function() {
$(window).on('keyup.siteNav', function(evt) {
if (evt.keyCode === 27) {
hideDropdown($el);
}
});
$(selectors.body).on('click.siteNav', function() {
hideDropdown($el);
});
}, 250);
}
function hideDropdown($el) {
// remove aria on open dropdown
$el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'false');
$el.removeClass(config.activeClass);
// reset active dropdown
cache.$activeDropdown = $(selectors.siteNavActiveDropdown);
$(selectors.body).off('click.siteNav');
$(window).off('keyup.siteNav');
}
function unload() {
$(window).off('.siteNav');
cache.$parents.off('.siteNav');
cache.$subMenuLinks.off('.siteNav');
cache.$topLevel.off('.siteNav');
$(selectors.siteNavChildLink).off('.siteNav');
$(selectors.body).off('.siteNav');
}
return {
init: init,
unload: unload
};
})();
Any help would be greatly appreciated. I feel so silly asking a simple question like this. I just can't figure out where to put :hover in the code. It seems pretty strait forward but I can't get it. You can see the site here: AlexandIvy.myShopify.com and the password to view it is staysk. I'm just talking about the top navigation menus.
This is the code from the console:
<nav class="grid__item medium-up--one-half small--hide" id="AccessibleNav" role="navigation">
<ul class="site-nav list--inline " id="SiteNav">
<li class="site-nav--has-dropdown">
<a href="/collections/bedding" class="site-nav__link site-nav__link--main" aria-has-popup="true" aria-expanded="false" aria-controls="SiteNavLabel-bedding">
Bedding
<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon--wide icon-chevron-down" viewBox="0 0 498.98 284.49"><defs><style>.cls-1{fill:#231f20}</style></defs><path class="cls-1" d="M80.93 271.76A35 35 0 0 1 140.68 247l189.74 189.75L520.16 247a35 35 0 1 1 49.5 49.5L355.17 511a35 35 0 0 1-49.5 0L91.18 296.5a34.89 34.89 0 0 1-10.25-24.74z" transform="translate(-80.93 -236.76)"></path></svg>
<span class="visually-hidden">expand</span>
</a>
<div class="site-nav__dropdown" id="SiteNavLabel-bedding">
<ul>
<li>
Sheet Sets
</li>
</ul>
</div>
</li>
Since you're using JS to hide/show the dropdowns, I suggest you do this if you're comfortable with JQuery.
$('.site-nav--has-dropdown').hover(function() {
if ($(this).hasClass('activated')){
$(this).removeClass('activated');
$(this).children('.site-nav__dropdown').css('display', 'none');
}
else{
$(this).addClass('activated');
$(this).children('.site-nav__dropdown').css('display', 'block');
}
});
The idea behind this is that the child closest to .site-nav--has-dropdown which has a class name .site-nav__dropdown can be activated on hover. You can use pol's code too which provides a different (and shorter) approach.
You should use mouseover/mouseout methods in jquery.
$('.site-nav--has-dropdown').mouseover(function() {
$(this).children('.site-nav__dropdown').show();
});
$('.site-nav--has-dropdown').mouseout(function() {
$(this).children('.site-nav__dropdown').hide();
});
Or just use css :hover,
to better support touch devices you should add :focus too.
.site-nav--has-dropdown:hover .site-nav__dropdown,
.site-nav--has-dropdown:focus .site-nav__dropdown {
display: block;
}
jsfiddle demo: sfiddle.net/8p33qh9h
Related
I have a click event handler for an anchor that grabs the selector's ID as a variable, has an if parameter and runs 2 functions with return false; at the end to prevent the window from refreshing:
function ItemNumberHistory(ItemNumber) {
var state = {ItemNumberHistory: ItemNumber};
var title = null;
var path = '/Inventory/' + ItemNumber;
history.pushState(state, title, path); // Add item number to URL/history
}
$(document).on('click', '.StoneLink', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
return false;
});
For some reason though this still refreshes the window [although return false; is expected to prevent that], but when I comment out ItemNumberHistory(ItemNumber); (line 23) the return false; doesn't refresh the window.
return false; doesn't work when I delete the contents of ItemNumberHistory(ItemNumber); either. It seems that i'm having the issue simply because the function is inside the click event handler.
How do I run my click event handler without the window refreshing on click?!
CODE SNIPPET
var ItemNumberHistory = '';
function loadItem(ItemNumber) {
ItemNumberHistory = ItemNumber;
$('#pageRoot').css('overflow-y', 'hidden');
$('.LoadItem, #StonePage').show(); // Show modal and loader
$.ajax({
url: 'vendors/pages/Inventory/LandingPage/Item.php?number=' + ItemNumber,
method: 'POST',
data: {ItemNumber: ItemNumber},
async: true,
cache: false,
error:
function(jqXHR, strError) {
if(strError == 'timeout') {
// Do something. Try again perhaps?
alert('Seems like there was an error loading this stones information.');
}
},
success:
function(data) {
$('#StoneDetails').html(data);
},
timeout: 3000
});
}
function ItemNumberHistory(ItemNumber) {
var state = {ItemNumberHistory: ItemNumber};
var title = null;
var path = '/Inventory/' + ItemNumber;
history.replaceState(state, title, path); // Add item number to URL/history
}
$(document).on('click', '.StoneLink', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
return false;
});
function closeModal() {
if($('#StonePage').is(':visible')) {
$('#StonePage').hide();
$('#pageRoot').css('overflow-y', 'auto');
history.replaceState(null, null, '/Inventory'); // Remove ItemNumber from URL path
}
}
// Hide modal when close button
$(document).on('click', '#CloseModal', function() {
closeModal();
});
// Hide modal on click away
$(document).on('click', '.head, #StonePage', function(event) {
// If clicked anywhere [on #StonePage] outside of .modal
if(!$('.modal').is(event.target) && $('.modal').has(event.target).length === 0) {
closeModal();
}
});
// Hide modal on esc key press
$(document).on('keydown', function(event) {
// keyCode 27 is esc key
if(event.keyCode == 27) {
closeModal();
}
});
.modalContainer {
display: none;
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
padding: 0;
margin: 130px 0 0 0;
overflow: auto;
z-index: 2;
cursor: pointer;
outline: none;
background-color: rgba(0, 0, 0, .25);
}
.modal {
width: 700px;
height: 375px;
padding: 0;
margin: 20px auto;
box-shadow: 0 0 10px #000;
-webkit-box-shadow: 0 0 10px #000;
-moz-box-shadow: 0 0 10px #000;
-o-box-shadow: 0 0 10px #000;
-ms-box-shadow: 0 0 10px #000;
cursor: default;
background-color: #fff;
}
.StoneDetails {
}
/* .CloseModal height and width are 36px */
.CloseModal {
position: relative;
float: right;
color: #ff0000;
text-align: right;
cursor: pointer;
user-select: none; /* Standard syntax */
-webkit-user-select: none; /* Safari 3.1+ */
-moz-user-select: none; /* Firefox 2+ */
-ms-user-select: none; /* IE 10+ */
z-index: 9;
background-color: transparent;
}
.CloseModal:hover {
text-shadow: 1px 1px 10px rgba(150, 150, 150, 1);
}
.CloseModal:active {
color: #000;
}
/* Load Item */
.LoadItem {
display: none;
position: absolute;
width: 700px;
height: 375px;
margin: auto;
padding-top: 164px;
user-select: none; /* Standard syntax */
-webkit-user-select: none; /* Safari 3.1+ */
-moz-user-select: none; /* Firefox 2+ */
-ms-user-select: none; /* IE 10+ */
overflow: hidden;
z-index: 4;
border: 0px solid red;
background-color: #fff;
}
.noScroll {
position: fixed;
overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Inventory">
<div id="StonePage" class="modalContainer" tabindex="0">
<div class="modal">
<div id="CloseModal" class="CloseModal" title="Close">
<span class="mdi mdi-36px mdi-close"></span>
</div>
<div id="StoneDetails" class="StoneDetails">
<!-- Content appends here -->
</div>
</div>
</div>
<div class="InventoryContent">
<!-- Stone listings -->
<div id="StoneContainer">
<div class="Stone" id="StoneIteration" data-listing="1" data-totalrows="1">
<!-- Stone's landing page -->
<a href="<?php $_SERVER['DOCUMENT_ROOT'] ?>/Inventory/Item Number" class="StoneLink" id="Item Number">
<!-- Image -->
<div class="StoneData StoneIMG">
<img src="image.jpg">
</div>
<!-- Weight -->
<div class="StoneData">
Weight
</div>
<!-- Type -->
<div class="StoneData">
Type
</div>
<!-- Enhancement -->
<div class="StoneData">
Enhancement
</div>
<!-- Dimensions -->
<div class="StoneData">
Dimensions
</div>
<!-- Item Number -->
<div class="StoneData">
#Item Number
</div>
</a>
</div>
</div>
</div>
</div>
I'm not sure if this is what you want.
'a href' is suspected.
change your tag
<a href="javascript:void(0);" class="StoneLink" id="<?php echo $row['number']; ?>">
(or <a href="#" class="StoneLink" id="<?php echo $row['number']; ?>">)
and change your event function
$('.StoneLink').on('click', function(event) {
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
location.href = '/Inventory/'+ItemNumber; // '<a href="">' instead
return false;
});
I went through the code you posted and there are a bunch of small, semantic issues (not the culprit here though). I was able to run most of it successfully on my local machine. A couple things:
Make sure you're stopping propagation correctly i.e. event.preventDefault(), not event.preventDefault.
navContent isn't defined (at least within the snippet provided).
Do you need ItemNumberHistory both as a variable and function definition? It's confusing.
I think if you add this you'll be fine:
$('.StoneLink').on('click', function(event) {
event.preventDefault();
var ItemNumber = $(this).attr('id'); // Get item number from ID;
// Toggle nav on mobile
if($(navContent).is(':visible')) {
$(navContent).addClass('navHide'); // Hide nav on mobile
$('#navToggleIcon').toggleClass('mdi-close mdi-menu'); // Toggle nav menu icon
}
ItemNumberHistory(ItemNumber);
loadItem(ItemNumber);
location.href = '/Inventory/'+ItemNumber; // '<a href="">' instead
return false;
});
I am trying to show a description when hovering over an option in a select list, however, I am having trouble getting the code to recognize when hovering.
Relevant code:
Select chunk of form:
<select name="optionList" id="optionList" onclick="rankFeatures(false)" size="5"></select>
<select name="ranks" id="ranks" size="5"></select>
Manipulating selects (arrays defined earlier):
function rankFeatures(create) {
var $optionList = $("#optionList");
var $ranks = $("#ranks");
if(create == true) {
for(i=0; i<5; i++){
$optionList.append(features[i]);
};
}
else {
var index = $optionList.val();
$('#optionList option:selected').remove();
$ranks.append(features[index]);
};
}
This all works. It all falls apart when I try to deal with hovering over options:
$(document).ready(
function (event) {
$('select').hover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
I found that code while searching through Stack Exchange, yet I am having no luck getting it to work. The alert occurs when I click on an option. If I don't move the mouse and close the alert by hitting enter, it goes away. If I close out with the mouse a second alert window pops up. Just moving the mouse around the select occasionally results in an alert box popping up.
I have tried targeting the options directly, but have had little success with that. How do I get the alert to pop up if I hover over an option?
You can use the mouseenter event.
And you do not have to use all this code to check if the element is an option.
Just use the .on() syntax to delegate to the select element.
$(document).ready(function(event) {
$('select').on('mouseenter','option',function(e) {
alert('yeah');
// this refers to the option so you can do this.value if you need..
});
});
Demo at http://jsfiddle.net/AjfE8/
try with mouseover. Its working for me. Hover also working only when the focus comes out from the optionlist(like mouseout).
function (event) {
$('select').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
})
})
You don't need to rap in in a function, I could never get it to work this way. When taking it out works perfect. Also used mouseover because hover is ran when leaving the target.
$('option').mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
console.log('yeah!');
};
})
Fiddle to see it working. Changed it to console so you don't get spammed with alerts. http://jsfiddle.net/HMDqb/
That you want is to detect hover event on option element, not on select:
$(document).ready(
function (event) {
$('#optionList option').hover(function(e) {
console.log(e.target);
});
})
I have the same issue, but none of the solutions are working.
$("select").on('mouseenter','option',function(e) {
$("#show-me").show();
});
$("select").on('mouseleave','option',function(e) {
$("#show-me").hide();
});
$("option").mouseover(function(e) {
var $target = $(e.target);
if($target.is('option')) {
alert('yeah!');
};
});
Here my jsfiddle https://jsfiddle.net/ajg99wsm/
I would recommend to go for a customized variant if you like to ease
capture hover events
change hover color
same behavior for "drop down" and "all items" view
plus you can have
resizeable list
individual switching between single selection and multiple selection mode
more individual css-ing
multiple lines for option items
Just have a look to the sample attached.
$(document).ready(function() {
$('.custopt').addClass('liunsel');
$(".custopt, .custcont").on("mouseover", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "block")
} else {
$(this).addClass("lihover");
}
})
$(".custopt, .custcont").on("mouseout", function(e) {
if ($(this).attr("id") == "crnk") {
$("#ranks").css("display", "none")
} else {
$(this).removeClass("lihover");
}
})
$(".custopt").on("click", function(e) {
$(".custopt").removeClass("lihover");
if ($("#btsm").val() == "ssm") {
//single select mode
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
$(this).removeClass("liunsel");
$(this).addClass("lisel");
} else if ($("#btsm").val() == "msm") {
//multiple select mode
if ($(this).is(".lisel")) {
$(this).addClass("liunsel");
$(this).removeClass("lisel");
} else {
$(this).addClass("lisel");
$(this).removeClass("liunsel");
}
}
updCustHead();
});
$(".custbtn").on("click", function() {
if ($(this).val() == "ssm") {
$(this).val("msm");
$(this).text("switch to single-select mode")
} else {
$(this).val("ssm");
$(this).text("switch to multi-select mode")
$(".custopt").removeClass("lisel");
$(".custopt").addClass("liunsel");
}
updCustHead();
});
function updCustHead() {
if ($("#btsm").val() == "ssm") {
if ($(".lisel").length <= 0) {
$("#hrnk").text("current selected option");
} else {
$("#hrnk").text($(".lisel").text());
}
} else {
var numopt = +$(".lisel").length,
allopt = $(".custopt").length;
$("#hrnk").text(numopt + " of " + allopt + " selected option" + (allopt > 1 || numopt === 0 ? 's' : ''));
}
}
});
body {
text-align: center;
}
.lisel {
background-color: yellow;
}
.liunsel {
background-color: lightgray;
}
.lihover {
background-color: coral;
}
.custopt {
margin: .2em 0 .2em 0;
padding: .1em .3em .1em .3em;
text-align: left;
font-size: .7em;
border-radius: .4em;
}
.custlist,
.custhead {
width: 100%;
text-align: left;
padding: .1em;
border: LightSeaGreen solid .2em;
border-radius: .4em;
height: 4em;
overflow-y: auto;
resize: vertical;
user-select: none;
}
.custlist {
display: none;
cursor: pointer;
}
.custhead {
resize: none;
height: 2.2em;
font-size: .7em;
padding: .1em .4em .1em .4em;
margin-bottom: -.2em;
width: 95%;
}
.custcont {
width: 7em;
padding: .5em 1em .6em .5em;
/* border: blue solid .2em; */
margin: 1em auto 1em auto;
}
.custbtn {
font-size: .7em;
width: 105%;
}
h3 {
margin: 1em 0 .5em .3em;
font-weight: bold;
font-size: 1em;
}
ul {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
customized selectable, hoverable resizeable dropdown with multi-line, single-selection and multiple-selection support
</h3>
<div id="crnk" class="custcont">
<div>
<button id="btsm" class="custbtn" value="ssm">switch to multi-select mode</button>
</div>
<div id="hrnk" class="custhead">
current selected option
</div>
<ul id="ranks" class="custlist">
<li class="custopt">option one</li>
<li class="custopt">option two</li>
<li class="custopt">another third long option</li>
<li class="custopt">another fourth long option</li>
</ul>
</div>
I'm writing a single page website. It has 3 'slides' like About/Music/Contact. The access to these slides is created with a dropdown menu. When you click the link in menu, the current page wrapper go visibility: hidden and through animation the following becomes visible. This works quite well, but everything happens on the root page, without changing the URL, which isn't user-friendly as if you want to share the link to the page you will always be redirected to the root.
So the question is: "How to make the url change without reloading the page (maybe through hash or smth) on the click?". Thanks in advance.
P.S. No code needed, just give me your way to make this, and I will add it into the code.
Just check with this and take it if you want this
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
// click-to-scroll behavior
$("a").click(function (e) {
e.preventDefault();
var section = this.href;
var sectionClean = section.substring(section.indexOf("#"));
$("html, body").animate({
scrollTop: $(sectionClean).offset().top
}, 1000, function () {
window.location.hash = sectionClean;
});
});
// listen for the scroll event
$(document).on("scroll", function() {
//console.log("onscroll event fired...");
// check if the anchor elements are visible
$(".common").each(function (idx, el) {
if ( isElementInViewport(el) ) {
// update the URL hash
if (window.history.pushState) {
var urlHash = "#" + $(el).attr("id");
window.history.pushState(null, null, urlHash);
}
}
});
});
body {
float: left;
width: 100%;
padding-bottom: 0px;
}
.common {
width: 100%;
float: left;
height: 100vh;
display: table;
}
.allbody {
float: left;
width: 100%;
}
a {
display: inline-block;
padding: 15px;
}
header {
float: left;
width: 100%;
position: fixed;
top: 0;
left: 0;
background: #fff;
}
.common h2 {
font-size: 30px;
color: #fff;
text-align: center;
padding-top: 10%;
display: table-cell;
vertical-align: middle;
}
#firstDestination {
background: #000;
}
#secondDestination {
background: #999;
}
#thirdDestination {
background: #ccc;
}
#fourthDestination {
background: #c1c1c1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<header>
first page
<a href="#secondDestination" >second page</a>
third page
fourth page
</header>
<div class="allbody">
<div class="common" id="firstDestination" ><h2>First Page</h2></div>
<div class="common" id="secondDestination"><h2>Second Page</h2></div>
<div class="common" id="thirdDestination" ><h2>Third Page</h2></div>
<div class="common" id="fourthDestination" ><h2>Fourth Page</h2></div>
</div>
I'm looking to learn how to do this left menu :
http://js.devexpress.com/New/15_2/#HTML_5_JS_Core
When you scroll down the page, the "active" menu item change.
p.s.
Is there a name for this type of menu?
regards,
yaniv
Scroll Navigation
That is how we call these type of navigation bars. Basically you have to listen to the scroll event and calculate which element is in the viewport at the moment than you add a class to your navigation that marks the current menu element.
There is a nice demo built in jQuery but because jQuery is a thing of the past, I built one in Vanilla JS. See comments for explanations.
There are different ways to define which is the current element. In my Example it is the last one whose top line just passed the top line of the browser.
Working demo
window.onscroll = onScroll;
function onScroll() {
var removeActiveClass = function (elements) {
for (var i = 0; i < elements.length; ++i) {
elements[i].classList.remove('active');
}
}
var anchors = document.querySelectorAll('#menu-center a');
var previousRefElement = null;
for (var i = 0; i < anchors.length; ++i) {
// Get the current element by the id from the anchor's href.
var currentRefElement = document.getElementById(anchors[i].getAttribute('href').substring(1));
var currentRefElementTop = currentRefElement.getBoundingClientRect().top;
// Searching for the element whose top haven't left the top of the browser.
if (currentRefElementTop <= 0) {
//The browser's top line haven't reached the current element, so the previous element is the one we currently look at.
previousRefElement = anchors[i];
// Edge case for last element.
if (i == anchors.length - 1) {
removeActiveClass(anchors);
anchors[i].classList.add("active");
}
} else {
removeActiveClass(anchors);
previousRefElement.classList.add("active");
break;
}
}
}
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.menu {
width: 100%;
height: 75px;
position: fixed;
background-color:rgba(4, 180, 49, 0.6);
}
#menu-center {
width: 980px;
height: 75px;
margin: 0 auto;
}
#menu-center ul {
margin: 15px 0 0 0;
}
#menu-center ul li {
list-style: none;
margin: 0 30px 0 0;
display: inline;
}
.active {
font-size: 14px;
color: #fff;
text-decoration: none;
line-height: 50px;
}
a {
font-size: 14px;
color: black;
text-decoration: none;
line-height: 50px;
}
.content {
height: 100%;
width: 100%;
}
#portfolio {background-color: grey;}
#about {background-color: blue;}
#contact {background-color: red;}
<div class="menu">
<div id="menu-center">
<ul>
<li><a class="active" href="#home">Home</a></li>
<li>Portfolio</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="home" class="content"></div>
<div id="portfolio" class="content"></div>
<div id="about" class="content"></div>
<div id="contact" class="content"></div>
This is not exactly menu type, it is the way how you can position objects by html.
You can use position:Abosule property to achieve this effect:
http://www.w3schools.com/css/tryit.asp?filename=trycss_position_fixed
By this given divs are "flying" above the res of the page. In your case it could be a menu.
EDIT:
To sync this you need to detect when given anchor is currently seen.
It can be done by jQuery, this is sample draft of code, should explain clue of solution:
// list of header on page
var positions = [
$("#anchor1").offset().top,
$("#anchor2").offset().top,
$("#anchor3").offset().top,
];
var menu_objects= [
"#menu1",
"#menu2",
"#menu3"
];
var $w = $(window).scroll(function(){
// clear old
for(var v in menu_objects)
$(v).css({"color","white"});
for(var i=positions.length-1;i>=0;i--)
{
if(positions[i]>=$w.scrollTop())
{
$(menu_objects[i]).css({"color","red"});
break;
}
}
});
I'm trying to have a bgcolor change for an element on mouseover, mouseout, and onclick. The problem is Javascript overwrites my onclick with mouseout, so I can't have both. So is there any way to have mouseover reset after mouseout?
function init() {
document.getElementById('default').onmouseover = function() {
tabHoverOn('default', 'grey')
};
document.getElementById('default').onmouseout = function() {
tabHoverOff('default', 'yellow')
};
document.getElementById('section2').onmouseover = function() {
tabHoverOn('section2', 'grey')
};
document.getElementById('section2').onmouseout = function() {
tabHoverOff('section2', 'yellow')
};
document.getElementById('section3').onmouseover = function() {
tabHoverOn('section3', 'grey')
};
document.getElementById('section3').onmouseout = function() {
tabHoverOff('section3', 'yellow')
};
}
function tabHoverOn(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
function tabHoverOff(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
var current = document.getElementById('default');
function tab1Highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab1highlight";
current = id;
}
function tab2highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab2highlight";
current = id;
}
function tab3highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab3highlight";
current = id;
}
window.onload = init();
body {
width: 900px;
margin: 10px auto;
}
nav {
display: block;
width: 80%;
margin: 0 auto;
}
nav > ul {
list-style: none;
}
nav > ul > li {
display: inline-block;
margin: 0 3px;
width: 150px;
}
nav > ul > li > a {
width: 100%;
background-color: #ffff66;
border: 1px solid #9b9b9b;
border-radius: 12px 8px 0 0;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
font-family: arial, sans-serif;
}
main {
display: block;
width: 80%;
margin: 0 auto;
border: 1px solid #9b9b9b;
padding: 10px;
}
main > h1 {
font-size: 1.5em;
}
.tab1highlight {
background-color: #339966;
color: white;
}
.tab2highlight {
background-color: #ff6666;
color: white;
}
.tab3highlight {
background-color: #6600ff;
color: white;
}
main img {
border: 5px solid #eeefff;
width: 80%;
margin-top: 20px;
}
<body>
<nav>
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</nav>
<main>
<h1>Exercise: Navigation Tab #5</h1>
<ul>
<li>
Combine the navigation tab exercises #1, #3, and #4 in one file, including <br>
<ul>
<li>temporarily change the background color of a tab when the cursor is hovering on it.</li>
<li>set the foreground and background color of the tab being clicked.</li>
<li>change the background color of the main element based on the selected tab.</li>
</ul>
<p>
To test, click on a tab and then move your mouse around. For example, the third tab is clicked, the tab background color is switched to blue. Then hover the mouse over the third tab, the background color of the tab should be switch to light green and then back to blue after the mouse moves out.
</p>
<img src="menu_tab5.jpg">
</li>
</ul>
</main>
It's generally a good idea to keep CSS out of JavaScript completely if you can help it. A better strategy for solving the hover problem is to use the CSS pseudo selector :hover rather than coding the color changes in JavaScript. If you give all your tabs the same class, you only have to write the CSS once:
.tab {
background-color: yellow;
}
.tab:hover {
background-color: grey;
}
Once you've done that, you can also relegate the click styling to CSS by creating an event handler that adds and removes a special class each time a tab is clicked.
In the CSS file:
.tab.clicked {
background-color: blue;
}
And then in JavaScript, something like:
var tabs = document.getElementsByClassName('tab');
for (i = 0; i < tabs.length; i ++) {
tabs[i].onclick = function (ev) {
for (i = 0; i < tabs.length; i ++) {
tabs[i].classList.remove('clicked');
}
ev.currentTarget.classList.add('clicked');
};
}
I've created a JSFiddle to illustrate.
Try updating a Boolean variable.
var Ele = document.getElementById('default');
var clicked = false;
Ele.onclick = function(){
clicked = true;
// add additional functionality here
}
Ele.onmouseover = function(){
clicked = false;
// add additional functionality here
}
Ele.onmouseout = function(){
if(!clicked){
// add additional functionality here
}
}