Last active
August 29, 2015 13:57
-
-
Save Bellfalasch/9389589 to your computer and use it in GitHub Desktop.
Goes through every image in a page on certain html nodes and adds quick preview functionality to linked content. Centers image h and v onload, mouseout to close, or click body to close.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createImagePreview() { | |
// Create one element to hold the popup image | |
var $popup = $("<div>"); | |
$popup.attr("class","img-popup"); | |
$popup.mouseover( function() { | |
$(this).mouseout( function() { | |
$(this).fadeOut(); | |
}); | |
}); | |
// Append click-event to body for closing img popups | |
$("body").click( function() { | |
$popup.fadeOut(); | |
}); | |
// Create the img placeholder, set source on each hover (later) | |
var $img = $("<img>"); | |
$img.attr("alt","Preview image"); | |
// This way to create elements with a set of attributes doesn't work in IE8, using old way instead. | |
/* | |
var $img = $("<img>", { | |
alt: "Testbild" | |
}); | |
*/ | |
$popup.append($img); | |
$popup.hide(); | |
$('.relatert-info').append( $popup ); | |
// Run through all the images to use this preview-function | |
$('.relatert-info div.image, .trinn .push-right div.image, #rutinebeskrivelse > p > div.image, #rutinebeskrivelse > div.image').each( function() { | |
// Get the big image from the href-value on the links | |
var ajaxUrl = $(this).find('a').attr("href"); | |
var timer; | |
var denna; | |
var windowH = $(window).height(); | |
var windowW = $(window).width(); | |
$(this).hover( function() { | |
denna = $(this); | |
// We need a timer to show preview first after X milliseconds, too annoying if it pops up instantly. | |
if (timer) { | |
clearTimeout(timer); | |
timer = null; | |
} | |
timer = setTimeout( function() { | |
// Update image source to the correct image | |
$img.load(function() { | |
// Move the box so it sits right over everything, in the middle of the screen | |
$popup.css({ | |
//"top": theimg.position().top + theimg.outerHeight(true) + "px" | |
position: "fixed", | |
left: ( windowW - $popup.outerWidth() ) / 2 - 10, // 10 here is (border + padding) / 2 | |
top: ( windowH - $popup.outerHeight() ) / 2 - 10 | |
}); | |
if ( $("body").hasClass("popup") ) { | |
$popup.css({ left: 0 }); | |
} | |
}).attr("src",ajaxUrl); | |
// If not visible from before, show the image container | |
if ( $(".img-popup").not(":visible") ) { | |
$(".img-popup").fadeIn(); | |
} | |
}, 250); | |
}, function() { | |
// Reset the timer if we leave the link (leaving the link indicates you don't want the popup anyway) | |
if (timer) { | |
clearTimeout(timer); | |
timer = null; | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment