jQuery: html shows nothing with no error, maybe head error? - javascript

Sorry for poor English, it is my second language.
I am trying to fix a code from codepen that uses jQuery. It is a code for carousel that slides auto. However, when I try to move these code to my own file, my html does not show up carousel. There is no error on console log.
Here is my HTML header
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="main.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.1.0/velocity.min.js"></script>
<script src="main.js"></script>
</head>
This is the javascript file(main.js) that I am trying to use
var sliderTeam = (function(document, $) {
'use strict';
var $sliderTeams = $('.slider--teams'),
$list = $('#list'),
$listItems = $('#list li'),
$nItems = $listItems.length,
$nView = 3,
autoSlider,
$current = 0,
$isAuto = true,
$acAuto = 2500,
_init = function() {
_initWidth();
_eventInit();
},
_initWidth = function() {
$list.css({
'margin-left': ~~(100 / $nView) + '%',
'width': ~~(100 * ($nItems / $nView)) + '%'
});
$listItems.css('width', 100 / $nItems + '%');
$sliderTeams.velocity({ opacity: 1 }, { display: "block" }, { delay:1000 });
},
_eventInit = function() {
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element){
window.setTimeout(callback, 1000 / 60);
};
})();
window.requestInterval = function(fn, delay) {
if( !window.requestAnimationFrame &&
!window.webkitRequestAnimationFrame &&
!window.mozRequestAnimationFrame &&
!window.oRequestAnimationFrame &&
!window.msRequestAnimationFrame)
return window.setInterval(fn, delay);
var start = new Date().getTime(),
handle = new Object();
function loop() {
var current = new Date().getTime(),
delta = current - start;
if(delta >= delay) {
fn.call();
start = new Date().getTime();
}
handle.value = requestAnimFrame(loop);
};
handle.value = requestAnimFrame(loop);
return handle;
}
window.clearRequestInterval = function(handle) {
window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) :
window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(handle.value) :
window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(handle.value) :
window.oCancelRequestAnimationFrame ? window.oCancelRequestAnimationFrame(handle.value) :
window.msCancelRequestAnimationFrame ? msCancelRequestAnimationFrame(handle.value) :
clearInterval(handle);
};
$.each($listItems, function(i) {
var $this = $(this);
$this.on('touchstart click', function(e) {
e.preventDefault();
_stopMove(i);
_moveIt($this, i);
});
});
autoSlider = requestInterval(_autoMove, $acAuto);
},
_moveIt = function(obj, x) {
var n = x;
obj.find('figure').addClass('active');
$listItems.not(obj).find('figure').removeClass('active');
$list.velocity({
translateX: ~~((-(100 / $nItems)) * n) + '%',
translateZ: 0
}, {
duration: 1000,
easing: [400, 26],
queue: false
});
},
_autoMove = function(currentSlide) {
if ($isAuto) {
$current = ~~(($current + 1) % $nItems);
} else {
$current = currentSlide;
}
console.log($current);
_moveIt($listItems.eq($current), $current);
},
_stopMove = function(x) {
clearRequestInterval(autoSlider);
$isAuto = false;
_autoMove(x);
};
return {
init: _init
};
})(document, jQuery);
$(window).load(function(){
'use strict';
sliderTeam.init();
});
This is the codepen:
https://codepen.io/fixcl/pen/KwpKvb
Did I add the wrong version of js file? Or did I miss something else?
Edited:
main.js is connected to html file. I can check with the code from main.js
console.log($current);
Edited2: This is my body of html file
<body>
<div class="slider--teams">
<div class="slider--teams__team">
<ul id="list" class="cf">
<li>
<figure class="active">
<figcaption>
<img src="https://odium.kr/assets/css/images/symbol-cernium.png">
<h2>Billie</h2>
<p>Head of Team</p>
</figcaption>
</figure>
</li>
<li>
<figure>
<figcaption>
<img src="https://odium.kr/assets/css/images/symbol-arcus.png">
<h2>Roger</h2>
<p>Art Director</p>
</figcaption>
</figure>
</li>
<li>
<figure>
<figcaption>
<img src="https://odium.kr/assets/css/images/symbol-odium.png">
<h2>Wendy</h2>
<p>Designer</p>
</figcaption>
</figure>
</li>
</ul>
</div>
</div>
</body>

you should put the main.js before body close tag, since you need to start execute main.js after DOM element is ready.
please check the plnkr for detail:
https://plnkr.co/edit/CuN7q7j6lrQE57DH?open=lib%2Fscript.js&preview
<body>
...
<script src="main.js"></script>
</body>

Related

Is there a way to not stop the transition when the tab is inactive?

I'm trying to make a carousel but I found the problem that every time I switch tabs and return, the animations are delayed, is there a way to solve this?
I tried to do something with the page visibility API, but couldn't fix it.
My code:
"use strict";
class Carousel {
constructor(_options) {
this.images = [];
this.imgIndex = 1;
this.transitionStatus = null;
this.options = {
autoplay: {
enabled: true,
speed: 5000
},
speed: 5000
};
this.nextQueue = 0;
//config options
Object.assign(this.options, _options);
//set props
this.container = document.getElementsByClassName("carousel__container")[0];
this.itemsContainer = document.getElementsByClassName("carousel__items")[0];
//get imgs from carousel items and remove #text's childs
document.querySelectorAll(".carousel__item").forEach(item => {
item.childNodes.forEach((child) => child.nodeName === "IMG" ? this.images.push(child) : false);
});
this.setup();
}
setup() {
//add class to all images in carouselContainer
for (let index = 0; index < this.images.length; index++) {
const image = this.images[index];
image === null || image === void 0 ? void 0 : image.classList.add('carousel__itemImg'); /* img */
}
const toContainerFragment = document.createDocumentFragment();
// create span index image counter
this.spanIndex = document.createElement('span');
this.spanIndex.classList.add('container__number'); //imgIndex
this.updateIndexContent();
toContainerFragment.appendChild(this.spanIndex);
//create next prev arrows
const arrowNext = document.createElement("span");
arrowNext.id = "carousel_next";
arrowNext.textContent = "=>";
toContainerFragment.appendChild(arrowNext);
const arrowPrev = document.createElement("span");
arrowPrev.id = "carousel_prev";
arrowPrev.textContent = "<=";
toContainerFragment.appendChild(arrowPrev);
arrowNext.addEventListener("click", () => this.next());
arrowPrev.addEventListener("click", () => this.prev());
//add arrows and span index to container
this.container.appendChild(toContainerFragment);
//autoplay
if (this.options.autoplay.enabled) {
this.autoPlay();
}
}
next() {
if (this.imgIndex == this.images.length) {
this.imgIndex = 0;
}
if (this.transitionStatus == "started") {
this.nextQueue++;
return;
}
const clientWidth = this.container.clientWidth;
this.imgIndex++;
this.updateIndexContent();
this.itemsContainer.style.transition = `transform ${this.options.speed}ms linear`;
this.itemsContainer.style.transform = `translateX(-${clientWidth}px)`;
this.transitionStatus = "started";
const transitionEndEvent = () => {
this.itemsContainer.removeEventListener("transitionend", transitionEndEvent);
this.itemsContainer.style.transition = "";
this.itemsContainer.style.transform = `translateX(-${0}px)`;
const previousElement = document.querySelectorAll(".carousel__item")[0];
this.itemsContainer.insertAdjacentElement("beforeend", previousElement);
this.transitionStatus = "ended";
if (this.nextQueue) {
this.nextQueue--;
this.next();
}
};
this.itemsContainer.addEventListener("transitionend", transitionEndEvent);
let currentTranslateX;
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
const computedStyle = window.getComputedStyle(this.itemsContainer);
var matrix = new WebKitCSSMatrix(computedStyle.transform);
currentTranslateX = matrix.m41;
}
else {
console.log(clientWidth);
console.log(currentTranslateX);
const resume = clientWidth + currentTranslateX;
console.log(resume);
}
});
}
updateIndexContent() {
this.spanIndex.textContent = `${this.imgIndex} / ${this.images.length}`;
}
autoPlay() {
setInterval(() => {
this.next();
}, this.options.autoplay.speed);
}
}
const carousel = new Carousel({
autoplay: {
enabled: false,
speed: 1000
},
speed: 5000
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<title>Document</title>
</head>
<body>
<div class="carousel__container">
<div class="carousel__items">
<div class="carousel__item">
<img src="../assets/1.jpg" alt="" />
</div>
<div class="carousel__item">
<img src="../assets/2.jpg" alt="" />
</div>
<div class="carousel__item">
<img src="../assets/3.jpg" alt="" />
</div>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
IGNORE: It looks like your post is mostly code; please add some more details.
Timers are throttled when the page is not visible. You'll need your code to not rely on them.
The easiest solution in your specific case is to switch to CSS animations. While these animations are also subject to throttling, at least they're managed by the browser for you. When the user switches back to the tab, the browser should handle the updates for you.

determine if element is in viewport - during scroll - return true / false

I am writing a small script to determine if an element is in the viewport...
The problem that I am having is my variable RET is always coming back as UNDEFINED
myscript.js
function myScriptObj() {
this.isElementInView = function (element, fullyInView) {
var RET;
$(window).scroll(function () {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
RET = (pageTop < elementTop) && (pageBottom > elementBottom);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
} else {
RET = (elementTop <= pageBottom) && (elementBottom >= pageTop);
console.log(`myscript.js: RET >>> ${RET}`);
return RET;
}
});
console.log(`myscript.js: RET >>> ${RET}`);
}
}
In example index.html looks like
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
...
<div class="row center" id="banner">
<img src="img/banner.jpg" width="514px" height="65px" border="0" />
</div>
...
<script src="js/myscript.js"></script>
<script type="text/javascript">
var myObj = new myScriptObj();
var _isInView = myObj.isElementInView(document.getElementById("banner"), false);
console.log(`index.html: myObj.RET >>> ${myObj.RET}`);
if (_isInView) {
console.log(`index.html: in view >>> ${_isInView}`);
} else {
console.log(`index.html: out of view >>> ${_isInView}`);
}
</script>
</body>
</html>
Again, myObj.RET is undefined, however, inside the function isElementInView the variable RET does get a value of true or false
can someone tell me what I am missing

Problems returning href class from Jquery

I have downloaded and implemented some jquery code that makes a photo gallery on my website from an instagram hashtag. I have been trying to edit this code so that clicking on the images in the gallery show up in a lightbox rather than following a link back to instagram.
Here is the the source for the code: http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Create-An-Endless-Instagram-Gallery-embedstagram.html
The Lightbox code I have been using is fancybox: http://www.jqueryscript.net/lightbox/Responsive-jQuery-Lightbox-With-Amazing-CSS3-Effects-Fancy-Box-2.html
On my site the necessary components are loaded for both Jqueries and the function is run like so:
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
I have found the href in the original gallery jquery that links to instagram and edited it to include the class 'ins_popup' like so:
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
This does not seem to work however and the link now just opens an enlarged version of the picture rather than opening it in fancybox. I have tested each of the components (fancybox / hashtag gallery) separetly without problem, I just can't seem to get them to talk to one another.
And the associated code:
<!DOCTYPE html>
<html>
<head>
<title>Embedstagram jQuery Plugin Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<!-- Include CSS Fies -->
<link href="https://www.googledrive.com/host/0B_9gRWttmryISVpkTGFhVV8yajQ" rel="stylesheet" type="text/css" >
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Include fancybox library -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
</head>
<body>
<div class="jquery-script-clear"></div>
<h1 style="margin:150px auto 30px auto;">Embedstagram jQuery Plugin Demo</h1>
<div id="embedstagram"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://www.googledrive.com/host/0B_9gRWttmryIbE0yNUJaeHNOQVk"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#embedstagram').embedstagram({
client_id: '6f3244d01df94bb98785d04861561307',
hashtag: '#neverlutionsoundsystem' ,
thumb: 'tile'
});
});
</script>
</body>
</html>
and the Jquery for the gallery which I have edited:
/*global jQuery, window*/
(function ($) {
$.fn.embedstagram = function (options) {
var $this = this,
next_url = '';
var settings = $.extend({
client_id: '',
username: '',
hashtag: '#neverlutionsoundsystem',
count: 20,
responsive: true,
load_more: true,
thumb: 'default',
theme: 'default'
}, options);
settings.hashtag = settings.hashtag.replace('#', '');
$this
.addClass('embedstagram')
.addClass('thumb-' + settings.thumb)
.addClass('theme-' + settings.theme)
.append('<ul></ul>')
.append('Loading..');
var $photos = $this.find('ul'),
$button = $this.find('#function-button');
function resize() {
if (settings.responsive) {
var e = $this.width();
var $photo = $('.photo');
if (1024 >= e && e > 768) {
$photo.css({'width': '25%', 'padding-bottom': '25%'});
} else if (768 >= e && e > 570) {
$photo.css({'width': '33.3%', 'padding-bottom': '33.3%'});
} else if (570 >= e && e > 400) {
$photo.css({'width': '50%', 'padding-bottom': '50%'});
} else if (400 > e) {
$photo.css({'width': '100%', 'padding-bottom': '100%'});
} else {
$photo.css({'width': '20%', 'padding-bottom': '20%'});
}
}
}
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
}
function getUrl(user_id) {
var modifier;
if (user_id) {
modifier = 'users/' + user_id;
} else if (settings.hashtag) {
modifier = 'tags/' + settings.hashtag;
}
if (next_url) {
return next_url;
}
return 'https://api.instagram.com/v1/' + modifier + '/media/recent/?&client_id=' + settings.client_id + '&count=' + settings.count;
}
function getPhotos(user_id) {
$button.text('Loading..');
$.ajax({
type: "GET",
dataType: 'jsonp',
url: getUrl(user_id),
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (!settings.load_more) {
$this.addClass('hide-load-more');
}
$button.text('Load More');
renderPhotos(data);
next_url = data.pagination.next_url;
if (!next_url) {
$button.text('No more images').addClass('disabled');
}
resize();
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
}
if (settings.username) {
$.ajax({
type: "GET",
dataType: 'jsonp',
url: 'https://api.instagram.com/v1/users/search?q=' + settings.username + '&client_id=' + settings.client_id,
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (data.data.length) {
var num_items = data.data.length - 1;
$.each(data.data, function (i, user) {
if (settings.username === user.username) {
var user_id = user.id;
getPhotos(user_id);
return false;
}
if (i === num_items) {
$button.text('Error: no users found').addClass('error');
}
});
} else {
$button.text('Error: no users found').addClass('error');
}
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
} else if (settings.hashtag) {
getPhotos();
} else {
$button.text('Error: missing username or hashtag').addClass('error');
}
$button.click(function (e) {
e.preventDefault();
if (!$(this).is('.disabled, .error')) {
getPhotos();
}
});
$(window).on('load resize', resize);
};
}(jQuery));
If you need to see any of the other code please ask! Any help is much appreciated as you may have well guessed - I'm new to all of this
Thanks!
when you are calling the fancybox, images may not have been loaded to the DOM. call the fancybox plugin after the image load, not on the $(document).ready();
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
}
Also I see in your sample website that you have included jquery twice in the page
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Remove the 2nd Jquery include. this might be the issue.

How to create an simple slider using jquery(not using plug in)?

<script>
var img = function(){
$("#slider").animate({"left":"-=1775px"},10000,function(){
$("#slider").animate({"left":"0px"},10000);
img();
});
};
img();
</script>
I used animation properties in jquery but i want the loop to display the three image continuously.
I once created a small js plugin that does this, you can see the code here:
$.fn.luckyCarousel = function(options) {
var car = this;
var settings = $.extend( {
'delay' : 8000,
'transition' : 400
}, options);
car.append($('<div>').addClass('nav'));
var nav = $('.nav', car);
var cnt = $("ul", car);
var car_w = car.width();
var carItems = $('li', car);
$(cnt).width((carItems.length * car_w) + car_w);
$(carItems).each(function(i) {
var dot_active = (!i) ? ' active' : '';
$(nav).prepend($('<div>').addClass('dot dot' + i + dot_active).bind('click', function(e) {
slideSel(i);
}));
});
$(carItems).css('visibility', 'visible');
$(cnt).append($(carItems).first().clone());
car.append(nav);
var sel_i = 0;
var spin = setInterval(function() {
slideSel('auto')
}, settings.delay);
function slideSel(i) {
if (i == 'auto') {
sel_i++;
i = sel_i;
} else {
clearInterval(spin)
}
var position = $(cnt).position();
var t = car_w * -i;
var last = false;
var d = t - position.left;
if (Math.abs(t) == cnt.width() - car_w) {
sel_i = i = 0;
}
$(cnt).animate({
left: '+=' + d
}, settings.transition, function() {
$('.dot', car).removeClass('active');
$('.dot' + i, car).addClass('active');
if (!sel_i) {
$(cnt).css('left', '0');
}
});
sel_i = i;
}
}
http://plnkr.co/edit/bObWoQD8sGYTV2TEQ3r9
https://github.com/luckyape/lucky-carousel/blob/master/lucky-carousel.js
The code has been adapted to be used without plugin architecture here:
http://plnkr.co/edit/9dmfzcyEMtukAb4RAYO9
Hope it helps,
g
var Slider = new function () {
var that = this;
var Recursion = function (n) {
setTimeout(function () {
console.log(n);
$('#sub_div img').attr('src', '/Images/' + n + '.JPG').addClass('current'); // n like 1.JPG,2.JPG .... stored images into Images folder.
if (n != 0)
Recursion(n - 1);
else
Recursion(5);
}, 3000);
};
var d = Recursion(5);
};
var Slider = new function () {
var that = this;
var Recursion = function (n) {
setTimeout(function () {
console.log(n);
$('#sub_div img').attr('src', '/Images/' + n + '.JPG').addClass('current'); // n like 1.JPG,2.JPG .... stored images into Images folder.
if (n != 0)
Recursion(n - 1);
else
Recursion(5);
}, 3000);
};
var d = Recursion(5);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="~/JS/Ajaxcall.js"></script>
<title>Index</title>
</head>
<body>
<div style="background: rgb(255, 106, 0) none repeat scroll 0% 0%; padding: 80px;" id="slider_div">
<div id="sub_div">
<img src="~/Images/0.JPG" style="width: 100%; height: 452px;">
</div>
</div>
</body>
</html>

How to start the popup lightbox onLoad?

I want to make a lightbox popup. I want it to pop up when the webpage loads and close it when they click the lightbox popup. How can I do this?
Here is what I have so far but it doesn't work.
HTML FILE:
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Lightbox 2</title>
<meta name="description" lang="en" content="testing" />
<meta name="author" content="Lokesh Dhakar">
<meta name="viewport" content="width=device-width">
<link rel="shortcut icon" type="image/ico" href="images/favicon.gif" />
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/lightbox.css" type="text/css"
media="screen" />
<link
href='http://fonts.googleapis.com/css?family=Fredoka+One|Open+Sans:400,700'
rel='stylesheet' type='text/css'>
</head>
<body>
<a href="images/examples/image-1.jpg" rel="lightbox">
<img src="images/examples/thumb-1.jpg" alt="" /></a>
<a href="images/examples/image-2.jpg" rel="lightbox"
title="Optional caption."><img src="images/examples/thumb-2.jpg"
alt="" /></a>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/lightbox.js"></script>
</body>
</html>
JS FILE:
(function() {
var $, Lightbox, LightboxOptions;
$ = jQuery;
LightboxOptions = (function() {
function LightboxOptions() {
this.fileLoadingImage = 'images/loading.gif';
this.fileCloseImage = 'images/close.png';
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
return LightboxOptions;
})();
Lightbox = (function() {
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
Lightbox.prototype.init = function() {
this.enable();
return this.build();
};
Lightbox.prototype.enable = function() {
var _this = this;
return $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox]', function(e) {
_this.start($(e.currentTarget));
return false;
});
};
Lightbox.prototype.build = function() {
var $lightbox,
_this = this;
$("<div>", {
id: 'lightboxOverlay'
}).after($('<div/>', {
id: 'lightbox'
}).append($('<div/>', {
"class": 'lb-outerContainer'
}).append($('<div/>', {
"class": 'lb-container'
}).append($('<img/>', {
"class": 'lb-image'
}), $('<div/>', {
"class": 'lb-nav'
}).append($('<a/>', {
"class": 'lb-prev'
}), $('<a/>', {
"class": 'lb-next'
})), $('<div/>', {
"class": 'lb-loader'
}).append($('<a/>', {
"class": 'lb-cancel'
}).append($('<img/>', {
src: this.options.fileLoadingImage
}))))), $('<div/>', {
"class": 'lb-dataContainer'
}).append($('<div/>', {
"class": 'lb-data'
}).append($('<div/>', {
"class": 'lb-details'
}).append($('<span/>', {
"class": 'lb-caption'
}), $('<span/>', {
"class": 'lb-number'
})), $('<div/>', {
"class": 'lb-closeContainer'
}).append($('<a/>', {
"class": 'lb-close'
}).append($('<img/>', {
src: this.options.fileCloseImage
}))))))).appendTo($('body'));
$('#lightboxOverlay').hide().on('click', function(e) {
_this.end();
return false;
});
$lightbox = $('#lightbox');
$lightbox.hide().on('click', function(e) {
if ($(e.target).attr('id') === 'lightbox') _this.end();
return false;
});
$lightbox.find('.lb-outerContainer').on('click', function(e) {
if ($(e.target).attr('id') === 'lightbox') _this.end();
return false;
});
$lightbox.find('.lb-prev').on('click', function(e) {
_this.changeImage(_this.currentImageIndex - 1);
return false;
});
$lightbox.find('.lb-next').on('click', function(e) {
_this.changeImage(_this.currentImageIndex + 1);
return false;
});
$lightbox.find('.lb-loader, .lb-close').on('click', function(e) {
_this.end();
return false;
});
};
Lightbox.prototype.start = function($link) {
var $lightbox, $window, a, i, imageNumber, left, top, _len, _ref;
$(window).on("resize", this.sizeOverlay);
$('select, object, embed').css({
visibility: "hidden"
});
$('#lightboxOverlay').width($(document).width()).height($(document).height()).fadeIn(this.options.fadeDuration);
this.album = [];
imageNumber = 0;
if ($link.attr('rel') === 'lightbox') {
this.album.push({
link: $link.attr('href'),
title: $link.attr('title')
});
} else {
_ref = $($link.prop("tagName") + '[rel="' + $link.attr('rel') + '"]');
for (i = 0, _len = _ref.length; i < _len; i++) {
a = _ref[i];
this.album.push({
link: $(a).attr('href'),
title: $(a).attr('title')
});
if ($(a).attr('href') === $link.attr('href')) imageNumber = i;
}
}
$window = $(window);
top = $window.scrollTop() + $window.height() / 10;
left = $window.scrollLeft();
$lightbox = $('#lightbox');
$lightbox.css({
top: top + 'px',
left: left + 'px'
}).fadeIn(this.options.fadeDuration);
this.changeImage(imageNumber);
};
Lightbox.prototype.changeImage = function(imageNumber) {
var $image, $lightbox, preloader,
_this = this;
this.disableKeyboardNav();
$lightbox = $('#lightbox');
$image = $lightbox.find('.lb-image');
this.sizeOverlay();
$('#lightboxOverlay').fadeIn(this.options.fadeDuration);
$('.loader').fadeIn('slow');
$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb- numbers, .lb-caption').hide();
$lightbox.find('.lb-outerContainer').addClass('animating');
preloader = new Image;
preloader.onload = function() {
$image.attr('src', _this.album[imageNumber].link);
$image.width = preloader.width;
$image.height = preloader.height;
return _this.sizeContainer(preloader.width, preloader.height);
};
preloader.src = this.album[imageNumber].link;
this.currentImageIndex = imageNumber;
};
Lightbox.prototype.sizeOverlay = function() {
return $('#lightboxOverlay').width($(document).width()).height($(document).height());
};
Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
var $container, $lightbox, $outerContainer, containerBottomPadding, containerLeftPadding, containerRightPadding, containerTopPadding, newHeight, newWidth, oldHeight, oldWidth,
_this = this;
$lightbox = $('#lightbox');
$outerContainer = $lightbox.find('.lb-outerContainer');
oldWidth = $outerContainer.outerWidth();
oldHeight = $outerContainer.outerHeight();
$container = $lightbox.find('.lb-container');
containerTopPadding = parseInt($container.css('padding-top'), 10);
containerRightPadding = parseInt($container.css('padding-right'), 10);
containerBottomPadding = parseInt($container.css('padding-bottom'), 10);
containerLeftPadding = parseInt($container.css('padding-left'), 10);
newWidth = imageWidth + containerLeftPadding + containerRightPadding;
newHeight = imageHeight + containerTopPadding + containerBottomPadding;
if (newWidth !== oldWidth && newHeight !== oldHeight) {
$outerContainer.animate({
width: newWidth,
height: newHeight
}, this.options.resizeDuration, 'swing');
} else if (newWidth !== oldWidth) {
$outerContainer.animate({
width: newWidth
}, this.options.resizeDuration, 'swing');
} else if (newHeight !== oldHeight) {
$outerContainer.animate({
height: newHeight
}, this.options.resizeDuration, 'swing');
}
setTimeout(function() {
$lightbox.find('.lb-dataContainer').width(newWidth);
$lightbox.find('.lb-prevLink').height(newHeight);
$lightbox.find('.lb-nextLink').height(newHeight);
_this.showImage();
}, this.options.resizeDuration);
};
Lightbox.prototype.showImage = function() {
var $lightbox;
$lightbox = $('#lightbox');
$lightbox.find('.lb-loader').hide();
$lightbox.find('.lb-image').fadeIn('slow');
this.updateNav();
this.updateDetails();
this.preloadNeighboringImages();
this.enableKeyboardNav();
};
Lightbox.prototype.updateNav = function() {
var $lightbox;
$lightbox = $('#lightbox');
$lightbox.find('.lb-nav').show();
if (this.currentImageIndex > 0) $lightbox.find('.lb-prev').show();
if (this.currentImageIndex < this.album.length - 1) {
$lightbox.find('.lb-next').show();
}
};
Lightbox.prototype.updateDetails = function() {
var $lightbox,
_this = this;
$lightbox = $('#lightbox');
if (typeof this.album[this.currentImageIndex].title !== 'undefined' && this.album[this.currentImageIndex].title !== "") {
$lightbox.find('.lb-caption').html(this.album[this.currentImageIndex].title).fadeIn('fast');
}
if (this.album.length > 1) {
$lightbox.find('.lb-number').html(this.options.labelImage + ' ' + (this.currentImageIndex + 1) + ' ' + this.options.labelOf + ' ' + this.album.length).fadeIn('fast');
} else {
$lightbox.find('.lb-number').hide();
}
$lightbox.find('.lb-outerContainer').removeClass('animating');
$lightbox.find('.lb-dataContainer').fadeIn(this.resizeDuration, function() {
return _this.sizeOverlay();
});
};
Lightbox.prototype.preloadNeighboringImages = function() {
var preloadNext, preloadPrev;
if (this.album.length > this.currentImageIndex + 1) {
preloadNext = new Image;
preloadNext.src = this.album[this.currentImageIndex + 1].link;
}
if (this.currentImageIndex > 0) {
preloadPrev = new Image;
preloadPrev.src = this.album[this.currentImageIndex - 1].link;
}
};
Lightbox.prototype.enableKeyboardNav = function() {
$(document).on('keyup.keyboard', $.proxy(this.keyboardAction, this));
};
Lightbox.prototype.disableKeyboardNav = function() {
$(document).off('.keyboard');
};
Lightbox.prototype.keyboardAction = function(event) {
var KEYCODE_ESC, KEYCODE_LEFTARROW, KEYCODE_RIGHTARROW, key, keycode;
KEYCODE_ESC = 27;
KEYCODE_LEFTARROW = 37;
KEYCODE_RIGHTARROW = 39;
keycode = event.keyCode;
key = String.fromCharCode(keycode).toLowerCase();
if (keycode === KEYCODE_ESC || key.match(/x|o|c/)) {
this.end();
} else if (key === 'p' || keycode === KEYCODE_LEFTARROW) {
if (this.currentImageIndex !== 0) {
this.changeImage(this.currentImageIndex - 1);
}
} else if (key === 'n' || keycode === KEYCODE_RIGHTARROW) {
if (this.currentImageIndex !== this.album.length - 1) {
this.changeImage(this.currentImageIndex + 1);
}
}
};
Lightbox.prototype.end = function() {
this.disableKeyboardNav();
$(window).off("resize", this.sizeOverlay);
$('#lightbox').fadeOut(this.options.fadeDuration);
$('#lightboxOverlay').fadeOut(this.options.fadeDuration);
return $('select, object, embed').css({
visibility: "visible"
});
};
return Lightbox;
})();
$(function() {
var lightbox, options;
options = new LightboxOptions;
return lightbox = new Lightbox(options);
});
}).call(this);
if your using jquery you can just create the link element as per the instructions and then use the following:
e.g
HTML:
<a id ="ele_id" href="images/image-1.jpg" rel="lightbox" title="my caption">image #1</a>
JS:
$('document').ready(function(){
$('#ele_id').trigger('click');
});
UPDATE
If you wanted you could use a cookie to check if it's hte users first time on the site and only run the light box if that is the case.
Using jquery cookie plugin: https://github.com/carhartl/jquery-cookie
$('document').ready(function(){
if ($.cookie('has_visited') != TRUE){
$('#ele_id').trigger('click');
$.cookie('has_visited', TRUE, { expires: 1 }); //this will set the cookie to expire after one day but you could make it longer
});
<!DOCTYPE html>
<html>
<head>
<Style>
#fade{
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #000;
z-index:1001;
-moz-opacity: 0.7;
opacity:.70;
filter: alpha(opacity=70);
}
#light{
display: none;
position: absolute;
top: 5%;
left: 45%;
width: 640px;
height: 453px;
margin-left: -250px;
margin-top: 100px;
background: #CCC;
z-index:1002;
overflow:visible;
}
</style>
<script>
window.document.onkeydown = function (e)
{
if (!e){
e = event;
}
if (e.keyCode == 27){
lightbox_close();
}
}
function lightbox_open(){
window.scrollTo(0,0);
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
function lightbox_close(){
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
</script>
<head>
<body onload="lightbox_open()";>
<div class="light" onClick="lightbox_close();" id="light"><img src="your_img.jpg"></div>
<div id="fade" onClick="lightbox_close();"></div>
</body>
</html>

Categories