jueves, 24 de octubre de 2013

Simple Lightbox with "img" not "a"

Soy bastante lerdote en JQuery y ayer me pasé la tarde buscando un Lightbox que cogiera el enlace de la imágen desde el "src" de la propia imágen en vez del tag "a" dentro del cual se encontraba nuestra thumbimage. Porque no siempre necesitamos tirar de "a" y su "href" ya que con el css podemos redimensionar la imágen para tener un thumb y al hacer click sobre ella simplemente mostrarla en su tamaño real. No es que sea la mejor solución hacer eso pero cuando tienes una carousel (Bootstrap) y le fijas un tamaño, estaría bien mostrar algunas imágenes en su tamaño real.
Era algo muy sencillo que finalmente esta mañana lo he conseguido. Apoyándome en lo que he encontrado en webtuts+ (enlace), he conseguido con pequeñas modificaciones.

* No olvidéis de cargar JQuery (<script src="http://code.jquery.com/jquery-1.6.2.min.js"-/script>).

Aquí tenéis el enlace al .html (descargar).

El código CSS:
<head>
<style>
#lightbox::before{
content: "";
display: block;
position: absolute;
z-index: -1;
width: 100%;
height: 100%;
background:#000;
opacity: 0.9;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=90);
}
#lightbox {
position:fixed; /* keeps the lightbox window in the current viewport */
z-index: 9999;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
#lightbox p {
text-align:right;
margin-right:20px;
font-size:12px;
color: #A0A0A0;
text-shadow: 0px 1px 1px #000000;
filter: Shadow(Color=#000000, Direction=180, Strength=2);
}
#lightbox img {
border: 10px solid #fff;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
</style>
</head>
El código HTML:
<body>
<img src="imagen1.jpg" style="width: 100px; height:100px;" class="lightbox_trigger"/>
</body>
El código JQuery:
<head>
<script>
jQuery(document).ready(function($) {
$('.lightbox_trigger').click(function(e) {

//prevent default action (hyperlink)
e.preventDefault();

//Get clicked link src
var image_href = $(this).attr("src");

if ($('#lightbox').length > 0) { // #lightbox exists

//place href as img src value
$('#content').html('<img src="' + image_href + '" />');

//show lightbox window - you could use .show('fast') for a transition
$('#lightbox').show();
}

else { //#lightbox does not exist - create and insert (runs 1st time only)

//create HTML markup for lightbox window
var lightbox =
'<div id="lightbox">'+
'<p>Click to close</p>' +
Click to close
'<div id="content">' + //insert clicked link's href into img src
'<img src="' + image_href +'" />' +
'</div>' +
'</div>';
//insert lightbox HTML into page
$('body').append(lightbox);
}
});

//Click anywhere on the page to get rid of lightbox window
$('#lightbox').live('click', function() { //must use live, as the lightbox element is inserted into the DOM
$('#lightbox').hide();
});
}
}
</script>
</head>

Publicar un comentario