Crea un botón flotante de “Volver al inicio” con jQuery

¿Estás buscando una forma sencilla de hacer que tus lectores naveguen fácilmente por larguísimas páginas web? ¿Estás cansado de darle a la rueda del ratón durante un buen rato para llegar al principio del documento?

Aquí tienes un sencillo botón de “Volver al inicio” que flota sobre la esquina inferior derecha de la pantalla. Y lo mejor de todo es que está completamente hecho en jQuery, CSS y HTML, por lo que vas a poder integrarlo con facilidad en páginas que ya tengas hechas y personalizarlo para dejarlo a tu gusto.

Volver al inicio de la página

El código está en gran parte una adaptación de los trabajos de Brian Cray y David Walsh, aunque es una combinación de sus ideas con el añadido de un efecto fade en el botón y un movimiento de scroll suave. El botón se ha colocado en la esquina inferior derecha para que resulte menos intrusivo. El navegador hará un scroll hasta el texto ancla de forma suave y agradable, gracias al estupendo plugin de jQuery ScrollTo, creado por Ariel Flesler.

¿Y cuál es ese plugin? ¿Quieres verlo en acción? Vale, entonces échale un ojo a la demo.

Sin más que añadir, aquí está el código. Primero, hay que añadir el botón y el texto ancla a la página o la plantilla. El botón debería ir al final de la página, justo encima de la etiqueta </body>. Y el texto ancla debería ir al principio de la página.

<div id="top"></div> <!--esto va al principio-->
<div id="message"><a href="#top" id="top-link">Volver al inicio</a></div> <!--esto va al final-->

Ahora, necesitaremos algo de CSS para formatear el aspecto del botón. Seguramente habrás visto que se ha dejado un espacio al final de la página para que puedan leerse las últimas líneas de texto sin que se vean obstruidas por el botón. Aquí está la hoja de estilos:

.container {padding: 0 0 70px 0;} /* el espacio del final */

#message
{
/* display: block antes de ocultarlo */
display: block;
display: none;

/* el enlace va sobre todos los otros elementos */
z-index: 999;

/* el enlace no oculta texto tras él */
opacity: .8;

/* el enlace se queda en el mismo lugar de la página */
position: fixed;

/* el enlace va al final de la página */
top: 100%;
margin-top: -80px; /* = altura + margen inferior elegido */

/* centrando el enlace */
left: 80%;
margin-left: -80px;

/* redondea las esquinas (como prefieras) */
-moz-border-radius: 24px;
-webkit-border-radius: 24px;

/* hazlo grande y fácil de ver (tamaño y estilo a tu elección) */
width: 300px;
line-height: 48px;
height: 48px;
padding: 10px;
background-color: #000;
font-size: 24px;
text-align: center;
}

#message a {color: #fff;}

Y naturalmente, el jQuery. Asegúrate de haber incluido jQuery y el plugin ScrollTo en el código fuente:

$(function () // ejecuta este código al cargar la página (AKA DOM load)
{
/* inicia las variables localmente para mejorar el rendimiento */
var scroll_timer;
var displayed = false;
var $message = $('#message');
var $window = $(window);
var top = $(document.body).children(0).position().top;

/* reacciona al evento 'scroll' en window */
$window.scroll(function () {
window.clearTimeout(scroll_timer);
scroll_timer = window.setTimeout(function () { // usa un temporizador para el rendimiento
if($window.scrollTop() <= top) // ocúltalo si está al principio de la página
{
displayed = false;
$message.fadeOut(500);
}
else if(displayed == false) // muéstralo si se hace scroll hacia abajo
{
displayed = true;
$message.stop(true, true).fadeIn(500).click(function () { $message.fadeOut(500); });
}
}, 100);
});
$('#top-link').click(function(e) {
e.preventDefault();
$.scrollTo(0,300);
});
});

… y listo! Comparte este código con tus amigos, y aprovecha los comentarios para contar qué tal te funciona. También puedes aportar tus sugerencias para mejorar sus funciones.

Fuente: Create a Hovering Scroll to Top button With jQuery [cherrysave]

Create a Hovering Scroll to Top Button With JQuery

JQuery Hovering Scroll to Top Button

JQuery Hovering Scroll to Top Button

Looking for an easy way to help your readers power through long web pages? Sick of scrolling for minutes at a time to get to the top of the document? Here’s a simple Scroll to Top button that hovers in the bottom right corner of your screen. Best of all, it’s made entirely from JQuery, CSS, and HTML, so you can easily drop it into preexisting pages and customize it to your hearts content.

The code is largely adapted from Brian Cray and David Walsh, but it’s a combination of the two ideas with the addition of a fade effect on the button and smooth scrolling action. Also, I moved the button to the bottom right corner of the page because I thought it was a little less intrusive. The browser will nicely and smoothly scroll up to the anchor when users click the link, and this is thanks to the super helpful ScrollTo plugin for JQuery, built by Ariel Flesler.

What’s that? You want to see it in action? Okay, you should check out the demo!

And without further ado, here’s the code. First, add the button and the anchor to your web page or template. The button should go at the bottom of your page, right above the </body> tag. And, the anchor should go at the top of your page.

·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
1.<div id="top"></div> <!--this goes at the top-->
2.<div id="message"><a href="#top" id="top-link">Scroll to Top</a></div> <!--this goes at the bottom-->

Now, you’ll need some CSS to format the look and feel of the button. As you probably noticed, I left a gap at the bottom of the page so you can read the last few lines of text without being obstructed by the button. Here’s the stylesheet:

·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
01..container {padding: 0 0 70px 0;} /* the gap for the bottom */
02.
03.#message
04.{
05./* display: block before hiding */
06.display: block;
07.display: none;
08.
09./* link is above all other elements */
10.z-index: 999;
11.
12./* link doesn't hide text behind it */
13.opacity: .8;
14.
15./* link stays at same place on page */
16.position: fixed;
17.
18./* link goes at the bottom of the page */
19.top: 100%;
20.margin-top: -80px; /* = height + preferred bottom margin */
21.
22./* link is centered */
23.left: 80%;
24.margin-left: -80px;
25.
26./* round the corners (to your preference) */
27.-moz-border-radius: 24px;
28.-webkit-border-radius: 24px;
29.
30./* make it big and easy to see (size, style to preferences) */
31.width: 300px;
32.line-height: 48px;
33.height: 48px;
34.padding: 10px;
35.background-color: #000;
36.font-size: 24px;
37.text-align: center;
38.}
39.
40.#message a { color: #fff; }

And, of course, the JQuery. Make sure you have JQuery and the ScrollTo plugin included in the source:

¿Te ha gustado este artículo? ¡Compártelo!
  • RSS
  • Facebook
  • Twitter
  • BarraPunto
  • Meneame
  • Google Bookmarks
  • Digg
  • del.icio.us
  • LinkedIn
  • Reddit

Tienes que identificarte para escibir comentarios.

line
footer
Desarrollado por Wordpress | Diseñado por Elegant Themes