Vertically Stretch List Items - javascript

I am building a phonegap application. I have the following:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Three <br>a Half</li>
</ul>
How can I make the <li> elements stretch vertically and fill the whole height of the page given that this needs to be dynamic so that it adapts to other viewports. The text inside the <li> elements needs to be vertically centred and supports multiple lines.
Is there any clean way of doing this?

I suggest using the display: table family of CSS3 rules. They'll be dynamic and maintain full height spacing if done correctly:
body, html {
height: 100%;
margin: 0;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
display: table;
width: 100%;
height: 100%;
}
ul li {
display: table-row;
}
ul li a { /* assuming an anchor child. Can be anything */
display: table-cell;
vertical-align: middle;
padding: 1em 3em;
}
Demo: http://jsfiddle.net/6z3q35x0/1/

There are two parts to your question: the first is to force the <ul> element to stretch to fill the viewport, and the second is to vertically and horizontally center the <li> content. However, the centering requires modifications to your markup. We can wrap all the content in <li> using <div> elements.
For centering, we can use CSS3 flexbox for that. This would be a JS-free solution, although it enjoys less cross-browser support. For viewport size, we can use the vw and vh units respectively.
ul {
display: flex;
flex-direction: column;
list-style: none;
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
}
li {
display: flex;
align-items: center;
justify-content: center;
flex-grow: 1;
}
li div {
}
/* For stylistics only */
li:nth-child(odd) {
background-color: #ddd;
}
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet"/>
<ul>
<li><div>One</div></li>
<li><div>Two</div></li>
<li><div>Three</div></li>
<li><div>Three <br>a Half</div></li>
</ul>
However, there might be situations where using CSS flexbox and viewport units are not ideal — iOS7, for example, has a well-documented rendering bug that does not calculate vh properly. In this case, we might have to rely on JS instead. The height of each <li> is simply divided by the number of <li>s present in the container.
var calcHeight = function() {
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var li = document.querySelectorAll("ul li");
for(var i=0; i<li.length; i++) {
li[i].style.height = (h/li.length)+'px';
}
}
calcHeight();
window.onresize = calcHeight();
ul {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
height: 100vh;
}
li {
display: block;
width: 100%;
position: relative;
}
li div {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
li:nth-child(odd) {
background-color: #ddd;
}
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet"/>
<ul>
<li><div>One</div></li>
<li><div>Two</div></li>
<li><div>Three</div></li>
<li><div>Three <br>a Half</div></li>
</ul>

Here is a JavaScript solution, which will give the heights according to the viewport's height.
Forcing ul to take the entire viewport's height:
Demo on Fiddle
var li = document.getElementsByTagName('li');
function doMath() {
for (i = 0; i < li.length; i++) {
li[i].style.height = window.innerHeight / li.length + 'px';
}
}
doMath();
window.onresize = doMath;
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
background: rosybrown;
}
span {
display: block;
position: relative;
top: 50%;
text-align: center;
transform: translateY(-50%);
}
li:nth-of-type(2n) {
background: plum;
}
body {
margin: 0;
}
<ul>
<li><span>One</span></li>
<li><span>Two</span></li>
<li><span>Three</span></li>
<li><span>Three<br />a Half</span></li>
<li><span>Four</span></li>
<li><span>Five<br />a Half</span></li>
<li><span>Six</span></li>
</ul>
Forcing lis to take the entire viewport's height:
Demo on Fiddle
var li = document.getElementsByTagName('li');
function doMath() {
for (i = 0; i < li.length; i++) {
li[i].style.height = window.innerHeight + 'px';
}
}
doMath();
window.onresize = doMath;
ul {
padding: 0;
margin: 0;
list-style: none;
}
li {
background: rosybrown;
}
span {
display: block;
position: relative;
top: 50%;
text-align: center;
transform: translateY(-50%);
}
li:nth-of-type(2n) {
background: plum;
}
body {
margin: 0;
}
<ul>
<li><span>One</span></li>
<li><span>Two</span></li>
<li><span>Three</span></li>
<li><span>Three<br />a Half</span></li>
<li><span>Four</span></li>
<li><span>Five<br />a Half</span></li>
<li><span>Six</span></li>
</ul>

You need to add height 100% to body and html, try this
<style>
body, html {
height: 100%;
}
ul {
height: 100%;
display: table;
}
li {
height: 25%;
display: table-row;
}
li div{
height: 25%;
display: table-cell;
vertical-align: middle;
}
</style>
Jsfiddle link: http://jsfiddle.net/d80xw55e/1/

Since you're allowing Javscript, this is pretty easy, I'm just having trouble getting the bullet point right. Hopefully you won't be using that though?
function liH(){
var lis = document.getElementsByTagName("li");
var spans = document.getElementsByTagName("span");
var liHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0) / lis.length;
for(var i = 0; i < lis.length; ++i){
var spanH = spans[i].getBoundingClientRect().height;
lis[i].style.paddingTop = ((liHeight - spanH) / 2) + "px";
lis[i].style.paddingBottom = lis[i].style.paddingTop;
//spans[i].style.top = -(spanH / 4) + "px"
}
}
liH();
window.onresize = liH;
li {background:#eee;margin-bottom:5px;}
span {position:relative;}
<ul>
<li><span>elem1</span></li>
<li><span>elem2</span></li>
<li><span>elem<br />3</span></li>
</ul>
The reason the view is not exact is because of the padding on the top that won't remove, and because of the 5px margin which I put to distinguish the elements.

Related

How to make a div scroll without the page itself scrolling?

I came across this site and thought the effect was really amazing. I wish to replicate this effect in some capacity. I am aware it will involve both css and javascript. Getting the divs rendered and centered on screen is very easy. What I am having issues with is getting each individual to scroll off screen instead of the screen itself scrolling. What effect or strategy can be used to achieve this??
EDIT: I do not wish for a javascript or external library approach. Thank you
No matter what, you will need a little bit of JavaScript to accomplish the effect shown in the link you provided.
Here is an example that more-or-less shows how the effect works:
var active = 0;
var divs = document.querySelectorAll('.wrap > div')
function onScroll(){
var winHeight = window.innerHeight
var scrollAmt = document.body.scrollTop;
var newActive = Math.floor( scrollAmt / winHeight )
if( active != newActive ){
active = newActive;
divs.forEach(function(el, indx){
if( indx <= active )
el.classList.add('released')
else
el.classList.remove('released')
})
}
}
window.addEventListener('scroll', onScroll)
html, body {
padding: 0;
margin: 0;
}
.wrap {
min-height: 400vh;
}
.wrap > div {
height: 100vh;
width: 100%;
position: fixed;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
}
.wrap > div > div {
width: 50%;
height: 50%;
}
.wrap > div.first { z-index: 3; }
.wrap > div.second { z-index: 2; }
.wrap > div.third { z-index: 1; }
.wrap > div.first > div {
background: blue;
height: 60%;
}
.wrap > div.second > div {
background: yellow;
width: 55%;
height: 55%;
}
.wrap > div.third > div{
background: green;
width: 60%;
}
.wrap > div.released {
position: relative;
}
<div class="wrap">
<div class="first released"><div></div></div>
<div class="second"><div></div></div>
<div class="third"><div></div></div>
</div>
You can use overflow: auto; or overflow: scroll; in the css for the div.
.container {
height: 100px;
overflow: auto; /*you can also use overflow: scroll; option */
}
<div class ='container'>
1<br>
2<br>
3<br>
4<br>
5<br>
6<br>
7<br>
8<br>
9<br>
10<br>
</div>

Translating jQuery to Vanilla JS issue

I was watching a tutorial that used jQuery and wanted to turn it into JS, but my code is broken - was hoping someone could help me with this:
Tutorial JS:
$(function() {
var btn = $('button');
var progressBar = $('.progressbar');
btn.click(function() {
progressBar.find('li.active').next().addClass('active');
})
})
Taken from URL:http://www.kodhus.com/kodity/codify/kod/mGXAtb
Here is my failed attempt at rewriting the jQuery using JavaScript DOM:
var btn1 = document.getElementsByTagName('BUTTON');
var progBar = document.getElementsByClassName('progressbar');
function clickMe1() {
var elm = progBar.querySelectorAll("li");
var emlClass = elm.querySelector(".active");
return emlClass.nextElementSibling.addClass('active');
}
btn1.addEventListener("click", clickMe1, false);
where did I go wrong?
Working fiddle.
Your code will work after several changes check the notes below :
You've missed addClass() there it's a jQuery function, for vanilla JS use .classList.add() instead:
return emlClass.nextElementSibling.classList.add("active");
querySelectorAll(); will return a list of nodes you have to loop through them and add class, use :
var emlClass = progBar.querySelectorAll("li.active");
Instead of :
var elm = progBar.querySelectorAll("li");
var emlClass = elm.querySelector(".active");
Then loop and add active class:
for(var i=0;i<emlClass.length;i++){
emlClass[i].nextElementSibling.classList.add("active");
}
getElementsByTagName() and getElementsByClassName() will also returns a list of nodes with given name, you have to specify which one you want to pick (selecting the first in my example) :
var btn1 = document.getElementsByTagName('BUTTON')[0];
var progBar = document.getElementsByClassName('progressbar')[0];
Hope this helps.
var btn1 = document.getElementsByTagName('BUTTON')[0];
var progBar = document.getElementsByClassName('progressbar')[0];
function clickMe1() {
var emlClass = progBar.querySelectorAll("li.active");
for(var i=0;i<emlClass.length;i++){
emlClass[i].nextElementSibling.classList.add("active");
}
}
btn1.addEventListener("click", clickMe1, false);
.container {
width: 100%;
}
.progressbar {
counter-reset: step;
margin: 0;
margin-top: 50px;
padding: 0;
}
.progressbar li {
list-style-type: none;
float: left;
width: 33.33%;
position: relative;
text-align: center;
}
.progressbar li:before {
content: counter(step);
counter-increment: step;
width: 30px;
height: 30px;
line-height: 30px;
border: 2px solid #ddd;
display: block;
text-align: center;
margin: 0 auto 10px auto;
border-radius: 50%;
background-color: white;
}
.progressbar li:after {
content: '';
position: absolute;
width: 100%;
height: 2px;
background-color: #ddd;
top: 15px;
left: -50%;
z-index: -1;
}
.progressbar li:first-child:after {
content: none;
}
.progressbar li.active {
color: green;
}
.progressbar li.active:before {
border-color: green;
}
.progressbar li.active + li:after {
background-color: green;
}
button {
position: relative;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 2px;
left: 50%;
margin-top: 30px;
transform: translate(-50%);
cursor: pointer;
outline: none;
}
button:hover {
opacity: 0.8;
}
<div class="container">
<ul class="progressbar">
<li class="active">Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ul>
</div>
<button>Next step</button>
.querySelectorAll("li") will return an array (or an array-like object) with one or more <li> tags. So you need to either:
loop through every <li> in that list and do the rest,
or just take the first item from that list if you don't want to worry about there being more than one li in the page,
or use .querySelector (not .querySelectorAll) to just take the first <li> for you.
MDN

Hold ul visible when parent loses hover (pure css if possible)

I'm quite new with css. I want hold the ul visible when hovering from parent to ul. I don't know how do it.
HTML Markup
<drop-down class="dropdown">
<span>Dropdown menu<i class="fa fa-cog"></i></span>
<ul>
<li>
Github<i class="fa fa-github"></i>
</li>
<li>
BitBucket<i class="fa fa-bitbucket"></i>
</li>
<li>
Dropbox<i class="fa fa-dropbox"></i>
</li>
<li>
Google drive<i class="fa fa-google"></i>
</li>
</ul>
</drop-down>
CSS
drop-down {
background-color: #e9e9e9;
border: 1px solid #d2c2c2;
border-radius: 2px;
display: flex;
flex-flow: column nowrap;
height: 40px;
justify-content: center;
position: relative;
width: 160px;
}
drop-down:hover { cursor: pointer; }
drop-down > span {
align-items: center;
color: #555;
display: flex;
font-family: 'segoe ui';
font-size: .9rem;
justify-content: space-between;
padding: 0px .75rem;
pointer-events: none;
}
drop-down > span > i {
color: inherit;
}
drop-down ul {
background-color: #e9e9e9;
border: 1px solid #d2c2c2;
border-radius: 2px;
box-shadow: 0px 2px 5px 1px rgba(0,0,0,.15);
display: block;
right: 10%;
list-style: none;
padding: .5rem 0;
position: absolute;
opacity: 0;
pointer-events: none;
visibility: hidden;
top: 160%;
transition: all .2s ease-out;
width: 100%;
z-index: 999;
}
drop-down ul > li {
color: #555;
display: block;
}
drop-down ul > li:hover {
background-color: #007095;
color: rgba(255,255,255,.9);
}
drop-down ul > li > a {
align-items: center;
color: inherit;
display: flex;
font-family: 'segoe ui';
font-size: .95rem;
justify-content: space-between;
padding: .5rem .75rem;
text-decoration: none;
}
drop-down ul > li > a > i {
color: inherit;
}
drop-down:focus {
outline: none;
}
drop-down:hover ul {
pointer-events: auto;
opacity: 1;
top: 120%;
visibility: visible;
}
You can see it running at this fiddle: http://jsfiddle.net/vt1y9ruo/1/
I can do it with javascript, but I don't want use it for something small.
Here's a working fiddle: http://jsfiddle.net/vt1y9ruo/8/
It works by inserting an invisible bridge between the button and the list.
drop-down:hover ul, #ulwrap:hover ul {
pointer-events: auto;
opacity: 1;
top:120%;
visibility: visible;
}
#ulwrap {
display: block;
height:0;
width:100%;
position:absolute;
}
drop-down:hover #ulwrap, #ulwrap:hover {
height:100px;
}
if you want to do this using the hover feature of css, the gap between the button and the list is what's killing you. either remove this gap or use js
on a side note there is no harm in using js for something small, this is what its used for, just make it nice and reusable
Well, pure css solution (many thanks #JBux) is a little dirty (mark up). I finally go for JS solution and for this, created a custom tag:
const helper = new Helper(); // helper functions
var ddProto = Object.create(HTMLElement.prototype);
ddProto.properties = {
list: null,
options: null,
value: null,
icon: null,
index: -1,
};
ddProto.initEvents = function() {
var self = this;
// mouse over button
this.addEventListener('mouseover', function(e) {
if(!helper.hasClass(this, 'dropdown-active'))
helper.addClass(this, 'dropdown-active');
});
// mouseleave over button
this.addEventListener('mouseleave', function(e){
var rect = this.getBoundingClientRect();
var left = e.pageX;
var bottom = e.pageY;
// if mouse is out of X axis of button and if mouse is
// out (only of top) of Y axis of button, hide ul
if(left < rect.left || left >= rect.right || bottom < rect.top) {
helper.delClass(this, 'dropdown-active');
}
});
// list loses hover
this.properties.list.addEventListener('mouseleave', function(e) {
if(helper.hasClass(self, 'dropdown-active'))
helper.delClass(self, 'dropdown-active');
});
// elements click
[].forEach.call(this.properties.options, function(e) {
e.addEventListener('click', function(event){
event.preventDefault();
// set the text of selected value to button
helper.text(self.properties.value, e.innerText);
// set the position of selected value
self.properties.index = helper.position(e.parentNode);
// set the <i> class name to the button (fontawesome)
self.properties.icon.className = this.children[0].className;
// hide ul
helper.delClass(self,'dropdown-active');
},true);
});
};
ddProto.value = function() {
return this.properties.value;
};
ddProto.index = function() {
return this.properties.index;
}
ddProto.createdCallback = function() {
this.properties.list = this.querySelector('ul');
this.properties.options = this.querySelectorAll('ul > li > a');
this.properties.value = this.querySelector('span');
this.properties.icon = this.querySelector('span > i');
this.initEvents();
};
document.registerElement('drop-down', {prototype: ddProto});
Working fiddle: http://jsfiddle.net/m2dtmr24/2/
Thank you so much.
The thing you could check is the + selector (more here)
In short it lets you add styles to elements right next to each other. The actual css might look something like this:
.dropdown{
display: none;
}
.button:hover+.dropdown{
display: block;
}
This will only work when .dropdown is directly below .button in the DOM
The animation might be harder, but you could achieve something similar by for example using transition on opacity, and toggle opacity instead of display

adding more button for list in responsive navigation

I have a navigation of lets say 12 items, and when resolution gets smaller items drop in a new line. I need to make that when an item doesn't fit on a navigation anymore it should put a "MORE" dropdown button on the right side of nav. and put that item that doesn't fit in a dropdown.
If you don't understand me there is image below.
But the problem is that navigation items aren't always the same width because navigation items are generated from REST api.
I tryed to make jQuery script for calculating items width and adding them to navigation.
Here is the script I created, I made it in a hurry so it's really bad.
I need to help on how to properly calculate items witdh and navigation width and calculating when to add items to navigation or remove items from navigation.
Here is image if you don't get it: http://img.hr/aagV
/*
* Here we check how many items can we put on the navigation bar
* If item doesn't fit we clone it on the more dropdown button
*/
function removeMany() {
var i = $items.length - 1;
if (itemsWidth > navWidth) {
while (itemsWidth > navWidth) {
$($items[i]).removeClass('first-level-item').addClass('second-level-item');
dropdownItems.push($items[i]);
$($items[i]).removeClass('showed');
$items.pop();
i--;
getItemsWidth();
}
$nav.append($navMore);
dropdownItems.reverse().forEach(function (element, index, array) {
$('ul.second-level').append(element);
});
getItems();
}
}
//If window is resized to bigger resolution we need to put back items on the navbar
function addMany() {
var i = dropdownItems.length - 1;
if (dropdownItems.length != 0) {
do {
$('ul.first-level').append(dropdownItems.reverse()[i]);
$items.push(dropdownItems[i]);
dropdownItems.pop();
i--;
getItemsWidth();
} while (itemsWidth < navWidth);
$navMore.remove();
$items.each(function (i) {
$(this).addClass('first-level-item showed').removeClass('second-level-item');
});
if (!(dropdownItems != 0)) {
return;
} else {
$nav.append($navMore);
}
}
}
body {
margin: 0;
padding: 0;
border: 0; }
ul, li {
margin: 0;
padding: 0;
list-style: none; }
ul.second-level li {
display: block !important; }
ul.second-level li > a {
color: black; }
a {
color: #fff;
text-decoration: none;
text-transform: uppercase; }
.second-level-item a {
color: #333 !important; }
.navigation {
width: 960px;
max-width: 100%;
background: #211;
color: #aaa;
margin: 0 auto; }
.first-level .first-level-item {
display: inline-block;
padding: 10px; }
.first-level .item-more {
display: inline-block; }
.first-level .item-more .second-level-item {
display: inline-block; }
.second-level {
position: absolute;
top: 100%;
right: 0;
width: 200px;
background: #fff;
padding: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.4); }
.has-second-level {
position: relative; }
.has-second-level .second-level {
display: none; }
.has-second-level:hover {
background: #fff;
color: #000; }
.has-second-level:hover .second-level {
display: block; }
/*# sourceMappingURL=style.css.map */
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DropDown</title>
<link rel="stylesheet" href="css/reset.css"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<nav class="navigation">
<ul class="first-level">
<li class="first-level-item showed">Introduction to Irish Culture</li>
<li class="first-level-item showed">Cellular and Molecular Neurobiology</li>
<li class="first-level-item showed">Guitar foundations</li>
<li class="first-level-item showed">Startup Inovation</li>
<li class="first-level-item showed">Astrophysics</li>
<li class="first-level-item item-more has-second-level">
<span> More </span>
<ul class="second-level">
</ul>
</li>
</ul>
</nav>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
</body>
</html>
If you have fixed-width list-items, then it is simple to collect extra list-items and push them into a separate list. Here is a simple example. Explanation is in the code comments.
View the snippet in full-screen and try changing the window width.
Also a Fiddle: http://jsfiddle.net/abhitalks/860LzgLL/
Full Screen: http://jsfiddle.net/abhitalks/860LzgLL/embedded/result/
Snippet:
var elemWidth, fitCount, fixedWidth = 120,
$menu = $("ul#menu"), $collectedSet;
// Assuming that the list-items are of fixed-width.
collect();
$(window).resize(collect);
function collect() {
// Get the container width
elemWidth = $menu.width();
// Calculate how many list-items can be accomodated in that width
fitCount = Math.floor(elemWidth / fixedWidth) - 1;
// Create a new set of list-items more than the fit count
$collectedSet = $menu.children(":gt(" + fitCount + ")");
// Empty the collection submenu and add the cloned collection set
$("#submenu").empty().append($collectedSet.clone());
}
* { box-sizing: border-box; margin: 0; padding: 0; }
div { position: relative; background-color: #ccc; height: 32px; overflow: visible; }
ul#menu, ol { height: 32px; max-width: 80%; overflow: hidden; }
ul#menu > li, ol > li { display: block; float: left; height: 32px; width: 120px; padding: 4px 8px; }
ol { position: absolute; right: 0; top: 0; overflow: visible; }
ol > li { min-width: 120px; }
ol ul { position: absolute; top: 120%; right: 10%; }
ol li ul > li { list-style: none; background-color: #eee; border: 1px solid gray; padding: 4px 8px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="menu">
<li>Option One</li><li>Option Two</li><li>Option Three</li>
<li>Option Four</li><li>Option Five</li><li>Option Six</li>
</ul>
<ol><li>Collected<ul id="submenu"></ul></li></ol>
</div>
Update:
This is regarding your query on differing / variable widths of list-items. There would be a minor change.
Also a Fiddle: http://jsfiddle.net/abhitalks/tkbmcupt/1/
Full Screen: http://jsfiddle.net/abhitalks/tkbmcupt/1/embedded/result/
Snippet:
var elemWidth, fitCount, varWidth = 0, ctr, $menu = $("ul#menu"), $collectedSet;
// Get static values here first
ctr = $menu.children().length; // number of children will not change
$menu.children().each(function() {
varWidth += $(this).outerWidth(); // widths will not change, so just a total
});
collect(); // fire first collection on page load
$(window).resize(collect); // fire collection on window resize
function collect() {
elemWidth = $menu.width(); // width of menu
// Calculate fitCount on the total width this time
fitCount = Math.floor((elemWidth / varWidth) * ctr) - 1;
// Reset display and width on all list-items
$menu.children().css({"display": "block", "width": "auto"});
// Make a set of collected list-items based on fitCount
$collectedSet = $menu.children(":gt(" + fitCount + ")");
// Empty the more menu and add the collected items
$("#submenu").empty().append($collectedSet.clone());
// Set display to none and width to 0 on collection,
// because they are not visible anyway.
$collectedSet.css({"display": "none", "width": "0"});
}
* { box-sizing: border-box; margin: 0; padding: 0; }
div { position: relative; background-color: #ccc; height: 32px; overflow: visible; }
ul#menu, ol { height: 32px; max-width: 80%; overflow: hidden; }
ul#menu > li, ol > li { display: block; float: left; height: 32px; white-space: nowrap; padding: 4px 8px; }
ol { position: absolute; right: 0; top: 0; overflow: visible; }
ol > li { min-width: 120px; }
ol ul { position: absolute; top: 120%; right: 10%; }
ol li ul > li { list-style: none; background-color: #eee; border: 1px solid gray; padding: 4px 8px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="menu">
<li>Option One</li><li>Option Two</li><li>Option Three</li>
<li>Option Four</li><li>Option Five</li><li>Option Six</li>
</ul>
<ol><li>Collected<ul id="submenu"></ul></li></ol>
</div>
Can and SHOULD be optimised (as it is quite inefficient from what i've tested), but that's up to you.
$(document).ready(function(){
var moreW = $(".more").outerWidth(), //width of your "more" element
totalW = -moreW, //cumulated width of list elements
totalN = $('.nav li').length - 1, //number of elements minus the "more" element
dw = document.documentElement.clientWidth;
$('.nav li').each(function(){
totalW += $(this).outerWidth();
});
function moveToDropdown(){
dw = document.documentElement.clientWidth;
//moves elements into the list
while(totalW > (dw - moreW)){
var temp = $(".nav li:nth-last-child(2)"); //element to be moved
totalW = totalW - temp.outerWidth();
$(".dropdown").append(temp.clone());
temp.remove();
}
//moves elements out of the list
var newList = $('.dropdown li').length; //check if we have elements
if(newList > 0){
var element = $('.dropdown li:last-child'), //element to be moved
elementW = $('.dropdown li:last-child').outerWidth(); //width of element to be moved
if(totalW + elementW < dw - moreW){
while(totalW + elementW < dw - moreW ){
var element = $('.dropdown li:last-child'),
elementW = $('.dropdown li:last-child').outerWidth();
totalW = totalW + elementW;
$(".nav > li:last-child").before(element.clone());
element.remove();
}
}
}
}
moveToDropdown();
$(window).resize(moveToDropdown)
});
.clearfix:after{
display:block;
content:'';
clear:both;
}
body,html{
width:100%;
height:100%;
margin:0;
padding:0;
}
ul{
list-style:none;
width:100%;
padding:0;
margin:0;
}
ul li{
float:left;
padding:5px;
}
.nav > li {
position:relative;
}
.nav ul{
position:absolute;
top:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav clearfix">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li class="more">
more
<ul class="dropdown">
<!-- we'll add elements here -->
</ul>
</li>
</ul>
This question is too old, but i want to post my answer too. Maybe this is more cleaner and easier way. I have created a pen: https://codepen.io/sergi95/pen/bmNoML
<div id="mainMenu" class="main-menu">
<ul id="autoNav" class="main-nav">
<li>
home
</li>
<li>
about us
</li>
<li>
portfolio
</li>
<li>
team
</li>
<li>
blog
</li>
<li>
contact
</li>
<li id="autoNavMore" class="auto-nav-more">
more
<ul id="autoNavMoreList" class="auto-nav-more-list">
<li>
policy
</li>
</ul>
</li>
</ul>
const $mainMenu = $("#mainMenu");
const $autoNav = $("#autoNav");
const $autoNavMore = $("#autoNavMore");
const $autoNavMoreList = $("#autoNavMoreList");
autoNavMore = () => {
let childNumber = 2;
if($(window).width() >= 320) {
// GET MENU AND NAV WIDTH
const $menuWidth = $mainMenu.width();
const $autoNavWidth = $autoNav.width();
if($autoNavWidth > $menuWidth) {
// CODE FIRES WHEN WINDOW SIZE GOES DOWN
$autoNav.children(`li:nth-last-child(${childNumber})`).prependTo($autoNavMoreList);
autoNavMore();
} else {
// CODE FIRES WHEN WINDOW SIZE GOES UP
const $autoNavMoreFirst = $autoNavMoreList.children('li:first-child').width();
// CHECK IF ITEM HAS ENOUGH SPACE TO PLACE IN MENU
if(($autoNavWidth + $autoNavMoreFirst) < $menuWidth) {
$autoNavMoreList.children('li:first-child').insertBefore($autoNavMore);
}
}
if($autoNavMoreList.children().length > 0) {
$autoNavMore.show();
childNumber = 2;
} else {
$autoNavMore.hide();
childNumber = 1;
}
}
}
// INIT
autoNavMore();
$(window).resize(autoNavMore);
.main-menu {
max-width: 800px;
}
.main-nav {
display: inline-flex;
padding: 0;
list-style: none;
}
.main-nav li a {
padding: 10px;
text-transform: capitalize;
white-space: nowrap;
font-size: 30px;
font-family: sans-serif;
text-decoration: none;
}
.more-btn {
color: red;
}
.auto-nav-more {
position: relative;
}
.auto-nav-more-list {
position: absolute;
right: 0;
opacity: 0;
visibility: hidden;
transition: 0.2s;
text-align: right;
padding: 0;
list-style: none;
background: grey;
border-radius: 4px;
}
.auto-nav-more:hover .auto-nav-more-list {
opacity: 1;
visibility: visible;
}
The script that Abhitalks made did not work properly for different element sizes. I modified the code a little bit do that it does:
$(function() {
function makeMenuFit() {
//Get data
var menuSize = menu.width();
//Determine how many items that fit
var menuTotalWidth = 0;
var itemThatFit = 0;
for(var i = 0; i < menuItems.length; i++) {
menuTotalWidth += menuItems[i];
if(menuTotalWidth <= menuSize) {
itemThatFit++;
continue;
}
break;
}
menu.children().css({"display": "block", "width": "auto"});
var collectedSet = menu.children(":gt(" + (itemThatFit - 1) + ")");
$("#submenu").empty().append(collectedSet.clone());
collectedSet.css({"display": "none", "width": "0"});
}
var menu = $(".tabletNavigation > ul");
var menuItems = [];
menu.children().each(function() {
menuItems.push($(this).outerWidth());
});
$(window).resize(makeMenuFit);
makeMenuFit();
});

How to Use Images as Navigation with innerfade Slideshow?

I am very new to JavaScript and only have the most basic understanding of how it works, so please bear with me. :) I'm using the jquery.innerfade.js script to create a slideshow with fade transitions for a website I'm developing, and I have added navigation buttons (which are set as background-images) that navigate between the “slides”. The navigation buttons have three states: default/off, hover, and on (each state is a separate image). I created a separate JavaScript document to set the buttons to “on” when they are clicked. The “hover” state is achieved through the CSS.
Both the slideshow and the navigation buttons work well. There is just one thing I want to add: I would like the appropriate navigation button to display as “on” while the related “slide” is “playing”.
Here's the HTML:
<div id="mainFeature">
<ul id="theFeature">
<li id="the1feature"><img src="_images/carousel/promo1.jpg" /></li>
<li id="the2feature"><img src="_images/carousel/promo2.jpg" /></li>
<li id="the3feature"><img src="_images/carousel/promo3.jpg" /></li>
</ul>
<div id="promonav-con">
<div id="primarypromonav">
<ul class="links">
<li id="the1title" class="promotop"><a rel="1" href="#promo1" class="promo1" id="promo1" onMouseDown="promo1on()"><strong>Botox Cosmetic</strong></a></li>
<li id="the2title" class="promotop"><a rel="2" href="#promo2" class="promo2" id="promo2" onMouseDown="promo2on()"><strong>Promo 2</strong></a></li>
<li id="the3title" class="promotop"><a rel="3" href="#promo3" class="promo3" id="promo3" onMouseDown="promo3on()"><strong>Promo 3</strong></a></li>
</ul>
</div>
</div>
And here is the jquery.innerfade.js, with my changes:
(function($) {
$.fn.innerfade = function(options) {
return this.each(function() {
$.innerfade(this, options);
});
};
$.innerfade = function(container, options) {
var settings = {
'speed': 'normal',
'timeout': 2000,
'containerheight': 'auto',
'runningclass': 'innerfade',
'children': null
};
if (options)
$.extend(settings, options);
if (settings.children === null)
var elements = $(container).children();
else
var elements = $(container).children(settings.children);
if (elements.length > 1) {
$(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
for (var i = 0; i < elements.length; i++) {
$(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
};
this.ifchanger = setTimeout(function() {
$.innerfade.next(elements, settings, 1, 0);
}, settings.timeout);
$(elements[0]).show();
}
};
$.innerfade.next = function(elements, settings, current, last) {
$(elements[last]).fadeOut(settings.speed);
$(elements[current]).fadeIn(settings.speed, function() {
removeFilter($(this)[0]);
});
if ((current + 1) < elements.length) {
current = current + 1;
last = current - 1;
} else {
current = 0;
last = elements.length - 1;
}
this.ifchanger = setTimeout((function() {
$.innerfade.next(elements, settings, current, last);
}), settings.timeout);
};
})(jQuery);
// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
if(element.style.removeAttribute){
element.style.removeAttribute('filter');
}
}
jQuery(document).ready(function() {
jQuery('ul#theFeature').innerfade({
speed: 1000,
timeout: 7000,
containerheight: '291px'
});
// jQuery('#mainFeature .links').children('li').children('a').attr('href', 'javascript:void(0);');
jQuery('#mainFeature .links').children('li').children('a').click(function() {
clearTimeout(jQuery.innerfade.ifchanger);
for(i=1;i<5;i++) {
jQuery('#the'+i+'feature').css("display", "none");
//jQuery('#the'+i+'title').children('a').css("background-color","#226478");
}
// if(the_widths[(jQuery(this).attr('rel')-1)]==960) {
// jQuery("#vic").hide();
// } else {
// jQuery("#vic").show();
// }
// jQuery('#the'+(jQuery(this).attr('rel'))+'title').css("background-color", "#286a7f");
jQuery('#the'+(jQuery(this).attr('rel'))+'feature').css("display", "block");
clearTimeout(jQuery.innerfade.ifchanger);
});
});
And the separate JavaScript that I created:
function promo1on() {document.getElementById("promo1").className="promo1on"; document.getElementById("promo2").className="promo2"; document.getElementById("promo2").className="promo2"; }
function promo2on() {document.getElementById("promo2").className="promo2on"; document.getElementById("promo1").className="promo1"; document.getElementById("promo3").className="promo3"; }
function promo3on() {document.getElementById("promo3").className="promo3on"; document.getElementById("promo1").className="promo1"; document.getElementById("promo2").className="promo2"; }
And, finally, the CSS:
#mainFeature {float: left; width: 672px; height: 290px; margin: 0 0 9px 0; list-style: none;}
#mainFeature li {list-style: none;}
#mainFeature #theFeature {margin: 0; padding: 0; position: relative;}
#mainFeature #theFeature li {position: absolute; top: 0; left: 0;}
#promonav-con {width: 463px; height: 26px; padding: 0; margin: 0; position: absolute; z-index: 900; top: 407px; left: 283px;}
#primarypromonav {padding: 0; margin: 0;}
#mainFeature .links {padding: 0; margin: 0; list-style: none; position: relative; font-family: arial, verdana, sans-serif; width: 463px; height: 26px;}
#mainFeature .links li.promotop {list-style: none; display: block; float: left; display: inline; margin: 0; padding: 0;}
#mainFeature .links li a {display: block; float: left; display: inline; height: 26px; text-decoration: none; margin: 0; padding: 0; cursor: pointer;}
#mainFeature .links li a strong {margin-left: -9999px;}
#mainFeature .links li a.promo1 {background: url(../_images/carouselnav/promo1.gif); width: 155px;}
#mainFeature .links li:hover a.promo1 {background: url(../_images/carouselnav/promo1_hover.gif); width: 155px;}
#mainFeature .links li a.promo1:hover {background: url(../_images/carouselnav/promo1_hover.gif); width: 155px;}
.promo1on {background: url(../_images/carouselnav/promo1_on.gif); width: 155px;}
#mainFeature .links li a.promo2 {background: url(../_images/carouselnav/promo2.gif); width: 153px;}
#mainFeature .links li:hover a.promo2 {background: url(../_images/carouselnav/promo2_hover.gif); width: 153px;}
#mainFeature .links li a.promo2:hover {background: url(../_images/carouselnav/promo2_hover.gif); width: 153px;}
.promo2on {background: url(../_images/carouselnav/promo2_on.gif); width: 153px;}
#mainFeature .links li a.promo3 {background: url(../_images/carouselnav/promo3.gif); width: 155px;}
#mainFeature .links li:hover a.promo3 {background: url(../_images/carouselnav/promo3_hover.gif); width: 155px;}
#mainFeature .links li a.promo3:hover {background: url(../_images/carouselnav/promo3_hover.gif); width: 155px;}
.promo3on {background: url(../_images/carouselnav/promo3_on.gif); width: 155px;}
Hopefully this makes sense! Again, I'm very new to JavaScript/JQuery, so I apologize if this is a mess. I'm very grateful for any suggestions. Thanks!
The JavasScript that I created does what I want it to do, i.e. it causes the navigation buttons to change states appropriately, displaying different images for "default/off", "hover", and "on". What I can't figure out how to do is create a "link" between jquery.innerfade.js (which I didn't create and, sadly, don't understand very well) and the JavaScript that I wrote. Ideally, as long as the first promo image ("_images/carousel/promo1.jpg") is displaying via jquery.innerfade.js, the first promo navigation button ("function promo1on()") would display in the "on" state.
To give an idea of the result that I want, take a look at the Martha Stewart site:
http://www.marthastewart.com/
I am trying to recreate a slideshow like that, only using JavaScript and CSS instead of Flash. Hope that makes sense! Thanks!!!
Katie

Categories