If element under of the upper div - set class "no visible" - javascript

I have Div in top page (300 px height) and items in ng-repeat.
I need to set class "no_visible" (each span element) if element "Hello World" partially or fully hidden under of top div. How i can do it?
var app = angular.module('plunker', []);
app
.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [];
for(var i =0; i<100;i++){
$scope.items.push(i);
}
})
.directive('trackVisibility', function(){
function isVisible(el) {
var rect = el.getBoundingClientRect();
var clw = (window.innerWidth || document.documentElement.clientWidth);
var clh = (window.innerHeight || document.documentElement.clientHeight) ;
// checks if element is fully visible
//return (rect.top >= 0 && rect.bottom <= clh) && (rect.left >= 0 && rect.right <= clw);
// checks if part of element is visible
return (rect.left <= clw && 0 <= rect.right && rect.top <= clh && 0 <= rect.bottom);
}
var reg = [];
function register(element, fn) {
reg.push([element, fn]);
}
function deregister(element) {
reg = angular.filter(reg, function (item) {
return item[0] !== element;
});
}
angular.element(window).on('DOMContentLoaded load resize scroll', function () {
angular.forEach(reg, function (item) {
item[1](isVisible(item[0]));
});
});
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
register(element[0], function(isVisible){
scope.$apply(function(){
scope.isVisible = isVisible;
})
});
scope.$on('$destroy', function(){
deregister(element);
})
}
};
});
span {
display: block;
height: 30px;
border: 1px solid;
}
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div style="height:300px; width:300px; position: fixed; background: #000;">
</div>
<div style="margin-top:350px; position: absolute;">
<span style="float:left; clear: both; " ng-repeat="i in items" track-visibility>Hello {{name}} {{isVisible?'yes':'no'}}!</span>
</div>
</body>
</html>

(function(){
angular.module('app')
//Each element has to be called "my-element"
.directive('myElement', function(){
return {
restrict : 'E',
link : function(scope, element, attrs){
//probably need to perfom this action on a event listener
window.on('scroll', function(){
var top = $el.getBoundingClientRect().top;
if(top < 200){
//Hide me
element.hide();
}
}
}
};
});
})();

Related

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

How to save drag/drop coordinates back to angular model?

My code allows for dragging and dropping of form fields overlaying an page image. I'm using Kendo-ui for the drag/drop but that's not critical to the answer, I don't think, and the demo is overly simplified and doesn't contain the image. I need to be able to change the angular model's coordinates to reflect the dropped location so I can save it. The meat of my question is HOW to update the model. What's the most efficient way of doing this since I can possibly have hundreds of fields? Is it possible to bind to the left/bottom CSS coordinates? Should I update the CSS manually using jQuery and then update the model?
Here's the plunker with my code
INDEX.HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common-bootstrap.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2016.2.714/styles/kendo.bootstrap.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2016.2.714/js/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="https://kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>
<script id="page-template" type="text/ng-template">
<div class="page" kendo-droptarget style="{{ 'width:' + (p.width + 2) + 'px; height:' + (p.height + 2) + 'px;' }}" ng-repeat="p in model.transaction.selectedDocument.pages">
<div class="field" data-fieldname="f.fieldName" kendo-draggable k-hint="model.draggableHint" k-dragstart="model.onDragStart" k-dragend="model.onDragEnd" ng-repeat="f in p.fields" style="{{ 'left:' + f.left + 'px;bottom:' + f.bottom + 'px;width:' + f.width + 'px;height:' + f.height + 'px;' }}">
<div></div>
</div>
</div>
<pre>{{ model | json }}</pre>
</script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<page-image-component></page-image-component>
</body>
</html>
SCRIPT.JS
// Code goes here
console.clear();
function pageImageController(TransactionFactory) {
var model = this;
model.transaction = TransactionFactory;
model.draggableHint = function (e) {
return e.clone();
}
model.onDragStart = function (e) {
console.log(e);
e.currentTarget.hide();
}
model.onDragEnd = function (e) {
console.log(e);
//e.currentTarget.css("left", "0px").css("top", "0px");
var field = e.currentTarget[0];
console.log(e.currentTarget)
e.currentTarget.show();
}
}
var app = angular.module("app", ["kendo.directives"]);
app.factory('TransactionFactory', function () {
var transaction = {
selectedDocument: {
fileName: "my.pdf",
pages: [{
pageNumber: 1,
width: 400,
height: 500,
fields: [
{
fieldName: "my field 1",
width: 75,
height: 13,
left: 50,
bottom: 300,
instance: 1
},
{
fieldName: "another field 1",
width: 65,
height: 13,
left: 200,
bottom: 440,
instance: 1
},
]
}]
}
};
return transaction;
});
app.component("pageImageComponent", {
template: $("#page-template").html(),
controllerAs: "model",
controller: ["TransactionFactory", pageImageController]
});
STYLE.CSS
/* Styles go here */
.page
{
border: 1px solid black;
position: relative;
}
.field
{
background-color: #ddd;
position: absolute;
}
I think I figured it out and I think it's efficient enough for rock and roll.
Here's the Plunker
function pageImageController(TransactionFactory) {
var model = this;
model.transaction = TransactionFactory;
var tempLeft = 0;
var tempTop = 0;
model.draggableHint = function (e) {
return e.clone();
}
model.onDragStart = function (e) {
//console.log(e);
e.currentTarget.hide();
}
model.onDrop = function (e) {
tempLeft = e.draggable.hint.offset().left -9;
tempTop = e.draggable.hint.offset().top +2;
console.log(e.draggable);
}
model.onDragEnd = function (e) {
//console.log(e);
var field = e.currentTarget[0];
//console.log(field)
var fieldIndex = field.attributes['data-fieldindex'].value;
var pageIndex = field.attributes['data-pageindex'].value;
//console.log(fieldIndex);
//console.log(pageIndex);
var tempBottom = model.transaction.selectedDocument.pages[pageIndex].height - tempTop;
model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].left = tempLeft;
model.transaction.selectedDocument.pages[pageIndex].fields[fieldIndex].bottom = tempBottom;
e.currentTarget.css("left", tempLeft + "px").css("bottom", tempBottom + "px");
e.currentTarget.show();
}
}

How to show a custom message based on the password strength

Hi I have the following piece of code that basically checking the strength of the password and showing a div with colors based on the strength. Like a strength meter. How can I mutate the content of the div based on the strength of the password, like if the password is weak, color change to red and content says "Weak passwrd!!", if the password is moderate then content should be "Moderate password" etc. Also I would like to add a check box in the divs so if the condition is met then the color of the check box shud change to green if not then red. etc.
My codes:
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>My AngularJS App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body ng-controller="stageController">
<form name="myForm" novalidate>
<label for="pw">Type a password</label><br/>
<input type="password" ng-model="pw" name="pw" id="pw" />
<li id="strength" check-strength="pw"></li>
</form>
</body>
CSS:
input.ng-pristine + ul#strength {
display:none;
}
ul#strength {
display:inline;
list-style:none;
margin:0;
margin-left:15px;
padding:0;
vertical-align:2px;
}
.point:last {
margin:0 !important;
}
.point {
background:#DDD;
border-radius:2px;
display:inline-block;
height:5px;
margin-right:1px;
width:20px;
}
#footer {
position:fixed;
bottom:5px;
}
AngularJS:
'use strict';
angular.module('myApp', ['myApp.directives']);
/* Controllers */
function stageController($scope) {
$scope.pw = '';
}
/* Directives */
angular.module('myApp.directives', []).
directive('checkStrength', function () {
return {
replace: false,
restrict: 'EACM',
link: function (scope, iElement, iAttrs) {
var strength = {
colors: ['#F00', '#F90', '#FF0', '#9F0', '#0F0'],
mesureStrength: function (p) {
var _force = 0;
var _regex = /[$-/:-?{-~!"^_`\[\]]/g;
var _lowerLetters = /[a-z]+/.test(p);
var _upperLetters = /[A-Z]+/.test(p);
var _numbers = /[0-9]+/.test(p);
var _symbols = _regex.test(p);
var _flags = [_lowerLetters, _upperLetters, _numbers, _symbols];
var _passedMatches = $.grep(_flags, function (el) { return el === true; }).length;
_force += 2 * p.length + ((p.length >= 10) ? 1 : 0);
_force += _passedMatches * 10;
// penality (short password)
_force = (p.length <= 6) ? Math.min(_force, 10) : _force;
// penality (poor variety of characters)
_force = (_passedMatches == 1) ? Math.min(_force, 10) : _force;
_force = (_passedMatches == 2) ? Math.min(_force, 20) : _force;
_force = (_passedMatches == 3) ? Math.min(_force, 40) : _force;
return _force;
},
getColor: function (s) {
var idx = 0;
if (s <= 10) { idx = 0; }
else if (s <= 20) { idx = 1; }
else if (s <= 30) { idx = 2; }
else if (s <= 40) { idx = 3; }
else { idx = 4; }
return { idx: idx + 1, col: this.colors[idx] };
}
};
scope.$watch(iAttrs.checkStrength, function () {
if (scope.pw === '') {
iElement.css({ "display": "none" });
} else {
var c = strength.getColor(strength.mesureStrength(scope.pw));
iElement.css({ "display": "inline" });
iElement.children('div')
.css({ "background": "#DDD" })
.slice(0, c.idx)
.css({ "background": c.col });
}
});
},
template: '<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>'
};
});
I found some code related your post, this may help you a lot
http://codepen.io/yukulele/pen/xbRpRa
var app = angular.module('app',[]);
app.controller('ctrl', function($scope){
$scope.pass="abc123456";
$scope.v=function(){
return test($scope.pass);
};
});
function test(pass){
if(pass == null)
return -1;
var s = 0;
if(pass.length<6)
return 0;
if( /[0-9]/.test( pass ) )
s++;
if( /[a-z]/.test( pass ) )
s++;
if( /[A-Z]/.test( pass ) )
s++;
if( /[^A-Z-0-9]/i.test( pass ) )
s++;
return s;
}
html{
font-size: 24px;
text-align: center;
margin: 30px;
background-color: #777;
}
label{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<label>
password:
<input
autofocus
type="text"
ng-model="pass"/>
</label>
<label>
{{v()}}
<span ng-if="v() < 2">Weak passwrd!!</span>
<span ng-if="v() > 3">Strong password</span>
</label>
</div>

Why does setting css left property result in it going off by 8?

Here is a fiddle. http://jsfiddle.net/p31L86wg/4/
Ideally, the green box should always be in the centre of the container, but for some reason when I set the left property it is choosing to stop 8 pixels before the pixel value I tell it to assume.
angular.module('website', ['ngAnimate'])
.controller('MainCtrl', function ($scope) {
$scope.products = [
{name: 'p1'},
{name: 'p2'},
{name: 'p3'},
{name: 'p4'},
{name: 'p5'}
];
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
})
.directive('pan', function(panBuckets) {
return function(scope, elm, attr) {
elm.css('position', 'relative');
var parentWidth = elm.parent().width();
elm.css('left', Math.floor(parentWidth/2)-(70/2)+'px');
scope.pan = function(vector) {
var bucket = panBuckets[attr['pan']];
if (bucket) {
var result = bucket.selectNewItem(bucket.selectedIndex-vector);
var rect = elm[0].getBoundingClientRect();
console.log('amount moved',rect.left, (vector*70)+'px',rect.left+(vector*70)+'px');
if (result!==false) elm.css('left', rect.left+(vector*70)+'px');
console.log(bucket.selectedItem[0].getBoundingClientRect().left, rect.left);
}
};
};
})
.service('panBuckets', function() {
return {};
})
.directive('panItem', function(panBuckets) {
var itemBuckets = panBuckets;
return function(scope, elm, attr) {
var bucket = itemBuckets[attr['panItem']];
if (!bucket) {
itemBuckets[attr['panItem']] = [];
bucket = itemBuckets[attr['panItem']];
elm.addClass('product-active');
bucket.selectedItem = elm;
bucket.selectNewItem = function(idx) {
if (idx < 0) idx = 0;
if (bucket.selectedIndex==idx) return false;
if (!bucket[idx]) return false;
bucket.selectedItem.removeClass('product-active');
bucket.selectedItem = bucket[idx];
bucket.selectedItem.addClass('product-active');
bucket.selectedIndex = idx;
return idx;
};
bucket.selectedIndex = 0;
}
bucket.push(elm);
scope.panBucket = bucket;
};
})
;
Position relative is a bit weird when trying to achieve such positioning, because it keeps the item 'inplace' and then repositions it, it can create some weird behaviors.
A working and easy solution is to change the position of the boxes container to absolute, and the container to relative. that way precision is guaranteed.
P.s. a little off topic, but animations this way (moving elements around) is better done with transform translate, it's a lot faster (the processing goes off to the GPU when possible and some more optimizations).
angular.module('website', ['ngAnimate'])
.controller('MainCtrl', function ($scope) {
$scope.products = [
{name: 'p1'},
{name: 'p2'},
{name: 'p3'},
{name: 'p4'},
{name: 'p5'}
];
$scope.currentIndex = 0;
$scope.setCurrentSlideIndex = function (index) {
$scope.currentIndex = index;
};
$scope.isCurrentSlideIndex = function (index) {
return $scope.currentIndex === index;
};
})
.directive('pan', function(panBuckets) {
return function(scope, elm, attr) {;
elm.css('position', 'relative');
var parentWidth = elm.parent().width();
elm.css('left', Math.floor(parentWidth/2)-(70/2)+'px');
scope.pan = function(vector) {
var bucket = panBuckets[attr['pan']];
if (bucket) {
var result = bucket.selectNewItem(bucket.selectedIndex+vector);
var rect = elm[0].getBoundingClientRect();
var bucketDimensions = bucket.selectedItem[0].getBoundingClientRect();
console.log(bucketDimensions);
if (result !== false) elm.css('left', Math.floor(parentWidth/2)-parseInt(bucket.selectedIndex * 70)-(70/2)+'px');
}
};
};
})
.service('panBuckets', function() {
return {};
})
.directive('panItem', function(panBuckets) {
var itemBuckets = panBuckets;
return function(scope, elm, attr) {
var bucket = itemBuckets[attr['panItem']];
if (!bucket) {
itemBuckets[attr['panItem']] = [];
bucket = itemBuckets[attr['panItem']];
elm.addClass('product-active');
bucket.selectedItem = elm;
bucket.selectNewItem = function(idx) {
if (idx < 0) idx = 0;
if (bucket.selectedIndex==idx) return false;
if (!bucket[idx]) return false;
bucket.selectedItem.removeClass('product-active');
bucket.selectedItem = bucket[idx];
bucket.selectedItem.addClass('product-active');
bucket.selectedIndex = idx;
return idx;
};
bucket.selectedIndex = 0;
}
bucket.push(elm);
scope.panBucket = bucket;
};
})
;
.container {
width: 100%;
position: relative;
}
.product-active {
background: green !important;
}
.square {
width: 50px;
height: 50px;
display: inline-block;
margin: 0 10px 0 10px;
background: blue;
}
.slider {
width:492px;
margin:0;
transition-property: left;
transition-duration: 0.4s;
transition-timing-: function: linear;
}
body {
overflow: hidden;
padding: 0;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.10.3/TweenMax.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-animate.js"></script>
<div ng-app="website" ng-controller="MainCtrl">
<div class="container">
<div class="slider animated zoomIn" pan="one">
<div ng-repeat="p in products" class="square product" pan-item="one">{{p.name}} </div>
</div>
</div>
<button ng-click="pan(-1)"><</button>
<button ng-click="pan(1)">></button>
</div>
http://jsfiddle.net/2u29LL3L/1/
There were some inconsistencies, check the diff, I think it's how you were trying to achieve.
I didn't understand why you had 70 instead of 50 in your math, but then I saw it's because of the margin.
I basically changed the calculation of left position of slider:
if (result !== false) elm.css('left', Math.floor(parentWidth/2)-parseInt(bucket.selectedIndex * 70)-(70/2)+'px');
So everytime, Math.floor(parentWidth/2) centers the slider, then puts the selected bins to the left with -parseInt(bucket.selectedIndex * 70) and then takes half of the current bin to the left.
I removed margin and padding of body, check it.
EDIT
I changed also the orientation of pan, now it seems more like it =)
From first glance, it appears that the green box has both left and right margin.
.square:first-child {margin-left:0px;}
This will remove margin on the left and will allow the box to adjust back towards the left, where you want it.

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