Passa al contingut principal

Stairway Navigation (A jQuery Plugin?)

On a whim the other day I thought I'd build out an idea for navigation I had. It's nothing but a visual effect in which the hovered (or active) navigation item becomes the tallest "stair" and other items before and after it step down. It's simple, but it's not something you see very often. Probably for one major reason: you can't select "previous" elements in CSS.


stairwaynavView Demo

You can select "next" elements in CSS. You'd use the general sibling combinator to get all the next elements or the adjacent sibling combinator to get the very next one (which you could chain). Neither of those allow you to get the previous elements which, as you can see by the image above, is needed to do this effect justice.


In pseudo code, we're trying to do this:



/* Not Real Code */

a:hover { /* top stair stuff */ }

a:hover-1,
a:hover+1 { /* second stair stuff *}

a:hover-2,
a:hover-2 { /* third stair stuff *}


Rather than get too tricky for our own good with CSS, let's rely on a technology that can select previous elements: jQuery. jQuery has a .prev() function (and a few other related functions) that we can use to get what we need. Our psuedo code would become more like this real code:



$("nav a").hover(function() {
$(this)
.addClass("stair-1")
.prev()
.addClass("stair-2")
.prev()
.addClass("stair-3")
.end()
.end()
.next()
.addClass("stair-2")
.next()
.addClass("stair-3");
});


Presumably we'd clear all classes on all nav elements on a mouseleave event as well. That means to be most efficient we'd already have a pointer to all those elements.



var navEls = $("nav a");

navEls
.on("mouseenter", function() {
// add classes as above
})
.on("mouseleave", function() {
navsEls.removeClass("stair-1 stair-2 stair-3");
})


So now that we have a set, we might as well get a bit more efficient. Using .next() and .prev() means a lot of jQuery going back out to the DOM to figure out what to select (I think, correct me if I'm wrong there). Rather than do that, we can just select based on the set we already have selected based on it's position within that set. The .index() function helps us figure that out and .eq() let's us grab the element based on its index.



navEls
.mouseenter(function() {

$(this).addClass("stair-1");

var index = $(this).index();

allLinks.eq(index+1).addClass("stair-2");
allLinks.eq(index-1).addClass("stair-2");

allLinks.eq(index+2).addClass("stair-3");
allLinks.eq(index-2).addClass("stair-3");

})


That'll do the trick.


CSS does the design work


Notice that all the jQuery is doing is adding and removing classes. That's how UI and JavaScript should hang out the majority of the time. JavaScript is in charge of knowing about and changing states - CSS does the work of making the page look different.


The entire "stairway" visual effect comes in now, when we apply styles based on those classes.



.stair-1 {
transform:
scale(1.10)
translateX(24px)
box-shadow: 0 0 10px rgba(black, 0.75);
z-index: 3;
}
.stair-2 {
transform:
scale(1.07)
translateX(12px)
box-shadow: 0 0 10px rgba(black, 0.5);
z-index: 2;
}
.stair-3 {
transform:
scale(1.04)
translateX(4px)
z-index: 1;
}


The "top" stair (stair-1) enlarges, moves to the right, and has a deep shadow. Each of the subsequents stairs does a bit less of all those things. You could also change colors here or do anything else that would make sense to your own application.


A jQuery Plugin?


I put those words in the title of this post because I think this is interesting territory.


Does this kind of thing "deserve" to be pluginized? For one thing - this is heavily dependent on CSS. Calling it a "Stairway Navigation" plugin isn't descriptive of what the actual jQuery code is doing. It also doesn't make use of any of jQuery's built-in features that are built for this, like it's ability to animate things - we instead leave that to CSS.


Anyway - we are going to pluginize it because it makes things more interesting.


Plugin Options


We'll make it the simplest set of options possible: how many stairs do you want stepping down? You'll call it on a navigation element that contains only anchor links:



$(".main-nav").stairwayNav({
stairs: 2
});


Then in the plugin, we make sure we have access to a "stairs" variable that is either the passed in value or some default.



$.fn.stairwayNav = function(options) {

var defaults = {
stairs: 3
};
this.options = $.extend({}, defaults, options);
var stairs = this.options.stairs;


I love that pattern. It means we don't have to do any fancy crap checking if the object contains certain keys and ensuring they aren't blank and blah blah. If you pass in a value for "stairs", that's what ends up in the options object. If you don't, it gets a default value. Cool.


Looping


To honor that option, we now just run a little for loop as many times as there are stairs. We adjust the index value the more iterations it runs, just never selecting negative values.



navEls
.mouseenter(function() {
$(this).addClass("stair-1");
var index = $(this).index(), i, bef, aft;
for(i = 1; i < stairs; i++) {

bef = index - i;
aft = index + i;

allLinks.eq(aft).addClass("stair-" + (i+1));
if (bef > 0) {
allLinks.eq(bef).addClass("stair-" + (i+1));
}
}
})


Stairway Navigation Demo


Here is the demo on CodePen.


Stairway Navigation (A jQuery Plugin?) is a post from CSS-Tricks






via CSS-Tricks http://css-tricks.com/stairway-navigation-a-jquery-plugin/

Comentaris

Entrades populars d'aquest blog

10 alternativas a Cuevana para ver películas online

10 alternativas a Cuevana para ver películas online : Durante este último tiempo, en Cuevana se sucedieron varios “problemas” por los cuales hubo que ajustar algunas cosas antes de tiempo (como el rediseño del sitio), que dejaron a algunos usuarios ciertos problemas para acceder a las películas o series del portal. Pero realmente esto es algo que no incumbe a los usuarios y, como sabemos, existen muchas otras alternativas a Cuevana dando vueltas por Internet, que intentaremos presentar aquí mismo. Los sitios que repasaremos funcionan del mismo modo que Cuevana, mediante la instalación de un plugin que permite visualizar los videos de Megaupload o WUShare, entre otros servicios, en una calidad de imágen realmente excelente. Tal como sucede con el más popular servicio, todos ellos tienen publicidad que en algunos casos resulta insoportable, pero como dice Federico en DotPod “a caballo regalado no se le miran los dientes”. Alternativas a Cuevana 1. Moviezet Posiblemente el mejor clon d...

Learn Composition from the Photography of Henri Cartier-Bresson

“Do you see it?” This question is a photographic mantra. Myron Barnstone , my mentor, repeats this question every day with the hopes that we do “see it.” This obvious question reminds me that even though I have seen Cartier-Bresson’s prints and read his books, there are major parts of his work which remain hidden from public view. Beneath the surface of perfectly timed snap shots is a design sensibility that is rarely challenged by contemporary photographers. Henri Cartier-Bresson. © Martine Franck Words To Know 1:1.5 Ratio: The 35mm negative measures 36mm x 24mm. Mathematically it can be reduced to a 3:2 ratio. Reduced even further it will be referred to as the 1:1.5 Ratio or the 1.5 Rectangle. Eyes: The frame of an image is created by two vertical lines and two horizontal lines. The intersection of these lines is called an eye. The four corners of a negative can be called the “eyes.” This is extremely important because the diagonals connecting these lines will form the breakdown ...

Más de 50 de las mejores herramientas online para profesores

No es una exageración afirmar que hay ciento de aplicaciones educativas por ahí por la red, para todos los gustos y de todos los colores, por lo que es difícil tratar de recogerlas todas en un listado. Sin embargo, algunas destacan más que otras por su innovación y por su capacidad para conseguir adeptos, y esas son las que protagonizan la presente recopilación. Son 50 interesantes herramientas online basadas en las recopilaciones de EduArea , las muchas ya tratadas en Wwwhat’s new y las destacadas por la experiencia. 1. Dropbox : Un disco duro virtual con varios GB gratuitos y al que se accede desde casi cualquier dispositivo. Sin embargo, es muchísimo más que eso, de hecho ya comentamos 20 razones . 2. Google Drive : La evolución de Google Docs que suma a sus múltiples herramientas de creación de documentos, un considerable espacio virtual gratuito. 3. CloudMagic : Una extensión y una app multidispositivo para buscar información simultáneamente en Gmail, Twitter, Facebook, Evernote ...