A close button for Lightbox_me - javascript

I've googled for a script for a close button for Lightbox_me, however all I've been able to find are scripts for bare-bones lightboxes.
(function ($) {
$.fn.lightbox_me = function (options) {
return this.each(function () {
var
opts = $.extend({}, $.fn.lightbox_me.defaults, options),
$overlay = $(),
$self = $(this),
$iframe = $('<iframe id="foo" style="z-index: ' + (opts.zIndex + 1) + ';border: none; margin: 0; padding: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; filter: mask();"/>');
if (opts.showOverlay) {
//check if there's an existing overlay, if so, make subequent ones clear
var $currentOverlays = $(".js_lb_overlay:visible");
if ($currentOverlays.length > 0) {
$overlay = $('<div class="lb_overlay_clear js_lb_overlay"/>');
} else {
$overlay = $('<div class="' + opts.classPrefix + '_overlay js_lb_overlay"/>');
}
}
/*----------------------------------------------------
DOM Building
---------------------------------------------------- */
$('body').append($self.hide()).append($overlay);
/*----------------------------------------------------
Overlay CSS stuffs
---------------------------------------------------- */
// set css of the overlay
if (opts.showOverlay) {
setOverlayHeight(); // pulled this into a function because it is called on window resize.
$overlay.css({
position: 'absolute',
width: '100%',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: (opts.zIndex + 2),
display: 'none'
});
if (!$overlay.hasClass('lb_overlay_clear')) {
$overlay.css(opts.overlayCSS);
}
}
/*----------------------------------------------------
Animate it in.
---------------------------------------------------- */
//
if (opts.showOverlay) {
$overlay.fadeIn(opts.overlaySpeed, function () {
setSelfPosition();
$self[opts.appearEffect](opts.lightboxSpeed, function () {
setOverlayHeight();
setSelfPosition();
opts.onLoad()
});
});
} else {
setSelfPosition();
$self[opts.appearEffect](opts.lightboxSpeed, function () {
opts.onLoad()
});
}
/*----------------------------------------------------
Hide parent if parent specified (parentLightbox should be jquery reference to any parent lightbox)
---------------------------------------------------- */
if (opts.parentLightbox) {
opts.parentLightbox.fadeOut(200);
}
/*----------------------------------------------------
Bind Events
---------------------------------------------------- */
$(window).resize(setOverlayHeight)
.resize(setSelfPosition)
.scroll(setSelfPosition);
$(window).bind('keyup.lightbox_me', observeKeyPress);
if (opts.closeClick) {
$overlay.click(function (e) {
closeLightbox();
e.preventDefault;
});
}
$self.delegate(opts.closeSelector, "click", function (e) {
closeLightbox();
e.preventDefault();
});
$self.bind('close', closeLightbox);
$self.bind('reposition', setSelfPosition);
/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/*----------------------------------------------------
Private Functions
---------------------------------------------------- */
/* Remove or hide all elements */
function closeLightbox() {
var s = $self[0].style;
if (opts.destroyOnClose) {
$self.add($overlay).remove();
} else {
$self.add($overlay).hide();
}
//show the hidden parent lightbox
if (opts.parentLightbox) {
opts.parentLightbox.fadeIn(200);
}
if (opts.preventScroll) {
$('body').css('overflow', '');
}
$iframe.remove();
// clean up events.
$self.undelegate(opts.closeSelector, "click");
$self.unbind('close', closeLightbox);
$self.unbind('repositon', setSelfPosition);
$(window).unbind('resize', setOverlayHeight);
$(window).unbind('resize', setSelfPosition);
$(window).unbind('scroll', setSelfPosition);
$(window).unbind('keyup.lightbox_me');
opts.onClose();
}
/* Function to bind to the window to observe the escape/enter key press */
function observeKeyPress(e) {
if ((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which == 0)) && opts.closeEsc) closeLightbox();
}
/* Set the height of the overlay
: if the document height is taller than the window, then set the overlay height to the document height.
: otherwise, just set overlay height: 100%
*/
function setOverlayHeight() {
if ($(window).height() < $(document).height()) {
$overlay.css({
height: $(document).height() + 'px'
});
$iframe.css({
height: $(document).height() + 'px'
});
} else {
$overlay.css({
height: '100%'
});
}
}
/* Set the position of the modal'd window ($self)
: if $self is taller than the window, then make it absolutely positioned
: otherwise fixed
*/
function setSelfPosition() {
var s = $self[0].style;
// reset CSS so width is re-calculated for margin-left CSS
$self.css({
left: '50%',
marginLeft: ($self.outerWidth() / 2) * -1,
zIndex: (opts.zIndex + 3)
});
/* we have to get a little fancy when dealing with height, because lightbox_me
is just so fancy.
*/
// if the height of $self is bigger than the window and self isn't already position absolute
if (($self.height() + 80 >= $(window).height()) && ($self.css('position') != 'absolute')) {
// we are going to make it positioned where the user can see it, but they can still scroll
// so the top offset is based on the user's scroll position.
var topOffset = $(document).scrollTop() + 40;
$self.css({
position: 'absolute',
top: topOffset + 'px',
marginTop: 0
})
} else if ($self.height() + 80 < $(window).height()) {
//if the height is less than the window height, then we're gonna make this thing position: fixed.
if (opts.centered) {
$self.css({
position: 'fixed',
top: '50%',
marginTop: ($self.outerHeight() / 2) * -1
})
} else {
$self.css({
position: 'fixed'
}).css(opts.modalCSS);
}
if (opts.preventScroll) {
$('body').css('overflow', 'hidden');
}
}
}
});
};
$.fn.lightbox_me.defaults = {
// animation
appearEffect: "fadeIn",
appearEase: "",
overlaySpeed: 250,
lightboxSpeed: 300,
// close
closeSelector: ".close",
closeClick: true,
closeEsc: true,
// behavior
destroyOnClose: false,
showOverlay: true,
parentLightbox: false,
preventScroll: false,
// callbacks
onLoad: function () {},
onClose: function () {},
// style
classPrefix: 'lb',
zIndex: 999,
centered: true,
modalCSS: {
top: '100px'
},
overlayCSS: {
background: 'black',
opacity: .3
}
}
$('.trigger').click(function (e) {
$('.lightbox').lightbox_me();
e.preventDefault();
});
})(jQuery);
This is the jsfiddle with the script for Lightbox_me.
I tried to incorporate the close-button scripts for the bare-bones lightboxes into Lightbox_me, but I simply don't know where to start. Would I have to format a close button onto each of the lightboxed divs individually and simply bind closeLightbox();? Or is there a more elegant way to do it involving only the script?

By default the script has these defined:
$.fn.lightbox_me.defaults = {
// animation
appearEffect: "fadeIn",
appearEase: "",
overlaySpeed: 250,
lightboxSpeed: 300,
// close
closeSelector: ".close",
closeClick: true,
closeEsc: true,
// behavior
destroyOnClose: false,
showOverlay: true,
parentLightbox: false,
preventScroll: false,
// callbacks
onLoad: function () {},
onClose: function () {},
// style
classPrefix: 'lb',
zIndex: 999,
centered: true,
modalCSS: {
top: '100px'
},
overlayCSS: {
background: 'black',
opacity: .3
}
}
You'll notice in the close section that it defaults to looking for elements with the class "close".
So if you stick a div with that class inside your lightbox, style as you please then it will trigger the close action.
The logic for closing based on the script:
if (opts.closeClick) {
$overlay.click(function (e) {
closeLightbox();
e.preventDefault;
});
}
$self.delegate(opts.closeSelector, "click", function (e) {
closeLightbox();
e.preventDefault();
});
This part of the logic informs lightbox_me that if closeClick is true within the list of options passed to it, that it will setup clicks on the overlay to close the lightbox.
As well it will bind current and future elements with the value defined in opts.closeSelector to also initiate the closeLightbox function when clicked.
Simple example fiddle: http://jsfiddle.net/zn2hg7L8/1/

Related

Inconsistent Slide Animation in a JavaScript Switch

I am trying to implement a left/right sliding animation inside of a JavaScript switch statement and the animation (sliding left and right without a bounce effect and no whitespace in between images) is not consistently activating. Also, the slide animation still activates when the previous button is clicked on the first slide and when the next button is clicked on the last slide. This should not be happening. Does anyone have any thoughts? Please see the code example.
$(function() {
// USER EDITABLE CONTROLS
var content = 'img'; // accepts any DOM element - div, img, table, etc...
var showControls = true; // true/false shows/hides the slider's navigational controls
var transition = 'slide'; // supports default, fade, slide
var transitionDuration = .5; // adjust the time of the transition measured in seconds
// VARIABLE DECLARATIONS
var contentType = $(content);
var $el = $('#showcase');
var $leftArrow = '#left_arrow';
var $rightArrow = '#right_arrow';
var $load = $el.find(contentType)[0];
var slideCount = $el.children().length;
var slideNum = 1;
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
// ADD SLIDER CONTROLS TO PAGE
if (showControls === true) {
$('<div id="controls">« Previous Next »</div>').insertAfter('#showcase');
$('#controls').find('#left_arrow').addClass('disabled');
}
// LOGIC FOR SLIDE TRANSITIONS
function transitions() {
switch (transition) {
// FADE TRANSITION
case 'fade':
$('.slide').stop().animate({opacity : 0}, transitionDuration*300, function(){
$('.active').stop().animate({opacity : 1}, transitionDuration*1000);
});
break;
// SLIDE TRANSITION
case 'slide':
if (slideNum > 1) {
$('.slide').stop().animate({left : -160}, transitionDuration*800, function(){
$('.active').stop().animate({left : 0}, transitionDuration*1000);
});
}
if (slideNum < slideCount) {
$('.slide').stop().animate({left : 160}, transitionDuration*800, function(){
$('.active').stop().animate({left : 0}, transitionDuration*1000);
});
}
break;
// DEFAULT TRANSITION
case 'default':
break;
}
}
// CHECKS FOR FIRST AND LAST INDEX IN THE SLIDER
function checkSlide() {
if (slideNum == 1) {
$($leftArrow).addClass('disabled');
} else {
$($leftArrow).removeClass('disabled');
}
if (slideNum == slideCount) {
$($rightArrow).addClass('disabled');
} else {
$($rightArrow).removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$(document).on('click', $leftArrow, function() {
if (slideNum > 1) {
var counter = $('.active').index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions();
$el.find(contentType).eq(counter).addClass('active');
slideNum--;
checkSlide();
}
})
$(document).on('click', $rightArrow, function() {
if (slideNum < slideCount) {
var counter = $('.active').index();
counter++;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions();
$el.find(contentType).eq(counter).addClass('active');
slideNum++;
checkSlide();
}
})
});
#showcase {
width: 160px;
overflow: hidden;
}
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
opacity: 0;
position: relative;
left: 0px;
right: 0px;
}
.active {
display: block;
opacity: 1;
position: relative;
left: 0px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" src="https://picsum.photos/458/354/?image=626" />
</div>
As said in the comments you need to fix your conditional statements. Awhile ago you had set two click handlers - one of which is binded (and is triggered regardless of any condition) when the other handler is triggered, this caused the slide animation still activates when the previous button is clicked on the first slide and when the next button is clicked on the last slide issue.
As for the animations, see my code below. I hacked your conditions a litte. When previous is clicked, the slide is to move from left to right. When next is clicked the slide is to move from right to left. I used a flag to determine the movement it will make - see the new paramter for transition function
$(function() {
// USER EDITABLE CONTROLS
var content = 'img'; // accepts any DOM element - div, img, table, etc...
var showControls = true; // true/false shows/hides the slider's navigational controls
var transition = 'slide'; // supports default, fade, slide
var transitionDuration = .5; // adjust the time of the transition measured in seconds
// VARIABLE DECLARATIONS
var contentType = $(content);
var $el = $('#showcase');
var $leftArrow = '#left_arrow';
var $rightArrow = '#right_arrow';
var $load = $el.find(contentType)[0];
var slideCount = $el.children().length;
var slideNum = 1;
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
// ADD SLIDER CONTROLS TO PAGE
if (showControls === true) {
$('<div id="controls">« Previous Next »</div>').insertAfter('#showcase');
$('#controls').find('#left_arrow').addClass('disabled');
}
// LOGIC FOR SLIDE TRANSITIONS
function transitions(impl = null) {
switch (transition) {
// FADE TRANSITION
case 'fade':
$('.slide').stop().animate({
opacity: 0
}, transitionDuration * 300, function() {
$('.active').stop().animate({
opacity: 1
}, transitionDuration * 1000);
});
break;
// SLIDE TRANSITION
case 'slide':
if (impl == "next") {
$('.slide').css("left", '160px');
$('.slide').stop().animate({
left: 160
}, transitionDuration * 800, function() {
$('.active').stop().animate({
left: 0
}, transitionDuration * 1000);
});
} else if (impl == "prev") {
$('.slide').css("left", '-160px');
$('.slide').stop().animate({
left: -160
}, transitionDuration * 800, function() {
$('.active').stop().animate({
left: 0
}, transitionDuration * 1000);
});
}
break;
// DEFAULT TRANSITION
case 'default':
break;
}
}
// CHECKS FOR FIRST AND LAST INDEX IN THE SLIDER
function checkSlide() {
if (slideNum == 1) {
$($leftArrow).addClass('disabled');
} else {
$($leftArrow).removeClass('disabled');
}
if (slideNum == slideCount) {
$($rightArrow).addClass('disabled');
} else {
$($rightArrow).removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$(document).on('click', $leftArrow, function() {
if (slideNum > 1) {
var counter = $('.active').index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions('prev');
$el.find(contentType).eq(counter).addClass('active');
slideNum--;
checkSlide();
}
})
$(document).on('click', $rightArrow, function() {
if (slideNum < slideCount) {
var counter = $('.active').index();
counter++;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions('next');
$el.find(contentType).eq(counter).addClass('active');
slideNum++;
checkSlide();
}
})
});
#showcase {
width: 160px;
overflow: hidden;
}
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
opacity: 0;
position: relative;
left: 0px;
right: 0px;
}
.active {
display: block;
opacity: 1;
position: relative;
left: 0px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" style="left: 160px;" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" style="left: 160px;" src="https://picsum.photos/458/354/?image=626" />
</div>

How to scrollLock body when a modal/lightbox is open

I am using the lightbox jquery plugin to open a lightbox when a user clicks on a product. Often the lightbox content stretches below the fold, and at the moment the right scrollbar moves the entire page when you scroll down.
I'd like it to work like the pinterest lightbox, whereby the right scrollbar only scrolls the lightbox, and the rest of the page stays fixed. I've seen a few posts on this, but nothing seems to work for me.
Problem is I want the lightbox to scroll if the content is bigger than the viewport of the browser but not the background.
CSS:
#lightbox{ position: absolute; left: 0; width: 100%; z-index: 100; text-align: center; line-height: 0;}
#lightbox img{ width: auto; height: auto;}
#lightbox a img{ border: none; }
#outerImageContainer{ position: relative; background-color: #fff; width: 250px; height: 250px; margin: 0 auto; }
#imageContainer{ padding: 10px; }
#loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; text-align: center; line-height: 0; }
#hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; }
#imageContainer>#hoverNav{ left: 0;}
#hoverNav a{ outline: none;}
#prevLink, #nextLink{ width: 49%; height: 100%; background-image: url(data:image2/gif;base64,AAAA); /* Trick IE into showing hover */ display: block; }
#prevLink { left: 0; float: left;}
#nextLink { right: 0; float: right;}
#prevLink:hover, #prevLink:visited:hover { background: url(../images2/prevlabel.gif) left 15% no-repeat; }
#nextLink:hover, #nextLink:visited:hover { background: url(../images2/nextlabel.gif) right 15% no-repeat; }
#imageDataContainer{ font: 10px Verdana, Helvetica, sans-serif; background-color: #fff; margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100% ; }
#imageData{ padding:0 10px; color: #666; }
#imageData #imageDetails{ width: 70%; float: left; text-align: left; }
#imageData #caption{ font-weight: bold; }
#imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em; }
#imageData #bottomNavClose{ width: 66px; float: right; padding-bottom: 0.7em; outline: none;}
#overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; height: 500px; background-color: #000; }
JS:
// -----------------------------------------------------------------------------------
//
// Lightbox v2.04
// by Lokesh Dhakar - http://www.lokeshdhakar.com
// Last Modification: 2/9/08
//
// For more information, visit:
// http://lokeshdhakar.com/projects/lightbox2/
//
// Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
// - Free for use in both personal and commercial projects
// - Attribution requires leaving author name, author link, and the license info intact.
//
// Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
// Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------
/*
Table of Contents
-----------------
Configuration
Lightbox Class Declaration
- initialize()
- updateImageList()
- start()
- changeImage()
- resizeImageContainer()
- showImage()
- updateDetails()
- updateNav()
- enableKeyboardNav()
- disableKeyboardNav()
- keyboardAction()
- preloadNeighborImages()
- end()
Function Calls
- document.observe()
*/
// -----------------------------------------------------------------------------------
//
// Configurationl
//
LightboxOptions = Object.extend({
fileLoadingImage: 'images2/loading.gif',
fileBottomNavCloseImage: 'images2/closelabel.gif',
overlayOpacity: 0.8, // controls transparency of shadow overlay
animate: true, // toggles resizing animations
resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest)
borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable
// When grouping images this is used to write: Image # of #.
// Change it for non-english localization
labelImage: "Image",
labelOf: "of"
}, window.LightboxOptions || {});
// -----------------------------------------------------------------------------------
var Lightbox = Class.create();
Lightbox.prototype = {
imageArray: [],
activeImage: undefined,
// initialize()
// Constructor runs on completion of the DOM loading. Calls updateImageList and then
// the function inserts html at the bottom of the page which is used to display the shadow
// overlay and the image container.
//
initialize: function() {
this.updateImageList();
this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10;
if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1;
this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration
// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
// If animations are turned off, it will be hidden as to prevent a flicker of a
// white 250 by 250 box.
var size = (LightboxOptions.animate ? 250 : 1) + 'px';
// Code inserts html at the bottom of the page that looks similar to this:
//
// <div id="overlay"></div>
// <div id="lightbox">
// <div id="outerImageContainer">
// <div id="imageContainer">
// <img id="lightboxImage">
// <div style="" id="hoverNav">
//
//
// </div>
// <div id="loading">
// <a href="#" id="loadingLink">
// <img src="images/loading.gif">
// </a>
// </div>
// </div>
// </div>
// <div id="imageDataContainer">
// <div id="imageData">
// <div id="imageDetails">
// <span id="caption"></span>
// <span id="numberDisplay"></span>
// </div>
// <div id="bottomNav">
// <a href="#" id="bottomNavClose">
// <img src="images/close.gif">
// </a>
// </div>
// </div>
// </div>
// </div>
var objBody = $$('body')[0];
objBody.appendChild(Builder.node('div',{id:'overlay'}));
objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
Builder.node('div',{id:'outerImageContainer'},
Builder.node('div',{id:'imageContainer'}, [
Builder.node('img',{id:'lightboxImage'}),
Builder.node('div',{id:'hoverNav'}, [
Builder.node('a',{id:'prevLink', href: '#' }),
Builder.node('a',{id:'nextLink', href: '#' })
]),
Builder.node('div',{id:'loading'},
Builder.node('a',{id:'loadingLink', href: '#' },
Builder.node('img', {src: LightboxOptions.fileLoadingImage})
)
)
])
),
Builder.node('div', {id:'imageDataContainer'},
Builder.node('div',{id:'imageData'}, [
Builder.node('div',{id:'imageDetails'}, [
Builder.node('span',{id:'caption'}),
Builder.node('span',{id:'numberDisplay'})
]),
Builder.node('div',{id:'bottomNav'},
Builder.node('a',{id:'bottomNavClose', href: '#' },
Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
)
)
])
)
]));
$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
$('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
$('outerImageContainer').setStyle({ width: size, height: size });
$('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
$('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
$('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
$('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
var th = this;
(function(){
var ids =
'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' +
'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose';
$w(ids).each(function(id){ th[id] = $(id); });
}).defer();
},
//
// updateImageList()
// Loops through anchor tags looking for 'lightbox' references and applies onclick
// events to appropriate links. You can rerun after dynamically adding images w/ajax.
//
updateImageList: function() {
this.updateImageList = Prototype.emptyFunction;
document.observe('click', (function(event){
var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
if (target) {
event.stop();
this.start(target);
}
}).bind(this));
},
//
// start()
// Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
//
start: function(imageLink) {
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
// stretch overlay to fill page and fade in
var arrayPageSize = this.getPageSize();
$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });
this.imageArray = [];
var imageNum = 0;
if ((imageLink.rel == 'lightbox')){
// if image is NOT part of a set, add single image to imageArray
this.imageArray.push([imageLink.href, imageLink.title]);
} else {
// if image is part of a set..
this.imageArray =
$$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
collect(function(anchor){ return [anchor.href, anchor.title]; }).
uniq();
while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
}
// calculate top and left offset for the lightbox
var arrayPageScroll = document.viewport.getScrollOffsets();
var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
var lightboxLeft = arrayPageScroll[0];
this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
this.changeImage(imageNum);
},
//
// changeImage()
// Hide most elements and preload image in preparation for resizing image container.
//
changeImage: function(imageNum) {
this.activeImage = imageNum; // update global var
// hide elements during transition
if (LightboxOptions.animate) this.loading.show();
this.lightboxImage.hide();
this.hoverNav.hide();
this.prevLink.hide();
this.nextLink.hide();
// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
this.imageDataContainer.setStyle({opacity: .0001});
this.numberDisplay.hide();
var imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload = (function(){
this.lightboxImage.src = this.imageArray[this.activeImage][0];
this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
}).bind(this);
imgPreloader.src = this.imageArray[this.activeImage][0];
},
//
// resizeImageContainer()
//
resizeImageContainer: function(imgWidth, imgHeight) {
// get current width and height
var widthCurrent = this.outerImageContainer.getWidth();
var heightCurrent = this.outerImageContainer.getHeight();
// get new width and height
var widthNew = (imgWidth + LightboxOptions.borderSize * 2);
var heightNew = (imgHeight + LightboxOptions.borderSize * 2);
// scalars based on change from old to new
var xScale = (widthNew / widthCurrent) * 100;
var yScale = (heightNew / heightCurrent) * 100;
// calculate size difference between new and old image, and resize if necessary
var wDiff = widthCurrent - widthNew;
var hDiff = heightCurrent - heightNew;
if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'});
if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration});
// if new and old image are same size and no scaling transition is necessary,
// do a quick pause to prevent image flicker.
var timeout = 0;
if ((hDiff == 0) && (wDiff == 0)){
timeout = 100;
if (Prototype.Browser.IE) timeout = 250;
}
(function(){
this.prevLink.setStyle({ height: imgHeight + 'px' });
this.nextLink.setStyle({ height: imgHeight + 'px' });
this.imageDataContainer.setStyle({ width: widthNew + 'px' });
this.showImage();
}).bind(this).delay(timeout / 1000);
},
//
// showImage()
// Display image and begin preloading neighbors.
//
showImage: function(){
this.loading.hide();
new Effect.Appear(this.lightboxImage, {
duration: this.resizeDuration,
queue: 'end',
afterFinish: (function(){ this.updateDetails(); }).bind(this)
});
this.preloadNeighborImages();
},
//
// updateDetails()
// Display caption, image number, and bottom nav.
//
updateDetails: function() {
// if caption is not null
if (this.imageArray[this.activeImage][1] != ""){
this.caption.update(this.imageArray[this.activeImage][1]).show();
}
// if image is part of set display 'Image x of x'
if (this.imageArray.length > 1){
this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show();
}
new Effect.Parallel(
[
new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }),
new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration })
],
{
duration: this.resizeDuration,
afterFinish: (function() {
// update overlay size and update nav
var arrayPageSize = this.getPageSize();
this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
this.updateNav();
}).bind(this)
}
);
},
//
// updateNav()
// Display appropriate previous and next hover navigation.
//
updateNav: function() {
this.hoverNav.show();
// if not first image in set, display prev image button
if (this.activeImage > 0) this.prevLink.show();
// if not last image in set, display next image button
if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
this.enableKeyboardNav();
},
//
// enableKeyboardNav()
//
enableKeyboardNav: function() {
document.observe('keydown', this.keyboardAction);
},
//
// disableKeyboardNav()
//
disableKeyboardNav: function() {
document.stopObserving('keydown', this.keyboardAction);
},
//
// keyboardAction()
//
keyboardAction: function(event) {
var keycode = event.keyCode;
var escapeKey;
if (event.DOM_VK_ESCAPE) { // mozilla
escapeKey = event.DOM_VK_ESCAPE;
} else { // ie
escapeKey = 27;
}
var key = String.fromCharCode(keycode).toLowerCase();
if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
this.end();
} else if ((key == 'p') || (keycode == 37)){ // display previous image
if (this.activeImage != 0){
this.disableKeyboardNav();
this.changeImage(this.activeImage - 1);
}
} else if ((key == 'n') || (keycode == 39)){ // display next image
if (this.activeImage != (this.imageArray.length - 1)){
this.disableKeyboardNav();
this.changeImage(this.activeImage + 1);
}
}
},
//
// preloadNeighborImages()
// Preload previous and next images.
//
preloadNeighborImages: function(){
var preloadNextImage, preloadPrevImage;
if (this.imageArray.length > this.activeImage + 1){
preloadNextImage = new Image();
preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
}
if (this.activeImage > 0){
preloadPrevImage = new Image();
preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
}
},
//
// end()
//
end: function() {
this.disableKeyboardNav();
this.lightbox.hide();
new Effect.Fade(this.overlay, { duration: this.overlayDuration });
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
},
//
// getPageSize()
//
getPageSize: function() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
return [pageWidth,pageHeight];
}
}
document.observe('dom:loaded', function () { new Lightbox(); });
Here's a class that'll allow you to do just that:
class ScrollLock {
constructor () {
this.pageBody = document.querySelector('body');
this.scrollY = 0;
}
saveScrollY = (num) => {
this.scrollY = num;
}
setScrollY = (num) => {
window.scroll(0, num);
}
setScrollOffset = (vOffset) => {
this.pageBody.style.top = `-${vOffset}px`;
}
freezeBodyScroll = () => {
this.saveScrollY(window.scrollY);
this.setScrollOffset(this.scrollY);
this.pageBody.classList.add('is-fixed');
}
unfreezeBodyScroll = () => {
this.pageBody.classList.remove('is-fixed');
// Don't reset scroll position if lock hasn't occurred
if (this.scrollY === 0) return;
this.setScrollOffset(0);
this.setScrollY(this.scrollY);
this.saveScrollY(0);
}
}
Include the following style declaration:
// In your CSS
body.is-fixed {
position: fixed;
max-width: 100%;
}
Use:
const { freezeBodyScroll, unfreezeBodyScroll } = new ScrollLock();
// Call when you open your modal
freezeBodyScroll();
// Call when you close your modal
unfreezeBodyScroll();

infinite loop for div scroll

I am trying to impliment tweet scroller on http://www.hubspot.com/
which is i guess using tweet-scroller from http://code.divshot.com/tweetscroller/
but this link is broken as demo is not working.
i looked for alternative.
I found http://jsfiddle.net/doktormolle/4c5tt/
HTML:
<ul class="slide">
<li><img src="http://www.google.com/logos/2010/canadianthanksgiving2010-hp.jpg"/></li>
<li><img src="http://www.google.com/logos/2010/germany10-hp.gif"/></li>
<li><img src="http://www.google.com/logos/stpatricks_02.gif"/></li>
</ul>
CSS:
ul.slide{margin:0;
padding:0;
height:80px;
list-style-type:none;}
ul.slide li{float:left;
list-style-type:none;}
ul.slide img{border:1px solid silver;
height:80px;}
JS:
//Plugin start
(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var _this = $(this);
_this.data('marquee', options);
var _li = $('>li', _this);
_this.wrap('<div class="slide_container"></div>')
.height(_this.height())
.hover(function () {
if ($(this).data('marquee').stop) {
$(this).stop(true, false);
}
},
function () {
if ($(this).data('marquee').stop) {
$(this).marquee('slide');
}
})
.parent()
.css({
position: 'relative',
overflow: 'hidden',
'height': $('>li', _this).height()
})
.find('>ul')
.css({
width: screen.width * 2,
position: 'absolute'
});
for (var i = 0; i < Math.ceil((screen.width * 3) / _this.width()); ++i) {
_this.append(_li.clone());
}
_this.marquee('slide');
});
},
slide: function () {
var $this = this;
$this.animate({
'left': $('>li', $this).width() * -1
},
$this.data('marquee').duration,
'swing',
function () {
$this.css('left', 0).append($('>li:first', $this));
$this.delay($this.data('marquee').delay).marquee('slide');
}
);
}
};
$.fn.marquee = function (m) {
var settings = {
'delay': 2000,
'duration': 900,
'stop': true
};
if (typeof m === 'object' || !m) {
if (m) {
$.extend(settings, m);
}
return methods.init.apply(this, [settings]);
} else {
return methods[m].apply(this);
}
};
})(jQuery);
//Plugin end
//call
$(document).ready(
function () {
$('.slide').marquee({
delay: 3000
});
}
);
which works fine with little modification i did
http://jsfiddle.net/3pZwR/1/
only problem is it stops after each div is scrolled.
I want it to be infinite scroll like effect without getting it stopped. like on hubspot.
You should use another JQuery Easing method instead of "swing".
Have a look at the Easings on the JQuery website: http://api.jqueryui.com/easings/

Very Simple, Very Smooth, JavaScript Marquee

I'm trying to find a very simple and smooth, lightweight javascript or jquery marquee. I already tried silk marquee or something, but it wouldn't work with the application I was using. So the simpler and shorter, the better - and easier to debug. Does anybody know of a easy to implement javascript replacement for the marquee?
Pastebin
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px'; // width (in pixels)
var tHeight='25px'; // height (in pixels)
var tcolour='#ffffcc'; // background colour:
var moStop=true; // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3; // scroll speed (1 = slow, 5 = fast)
// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
this is a simple scrolling text!
</div>
</body>
</html>
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>​
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })​
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/
It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
I just created a simple jQuery plugin for that. Try it ;)
https://github.com/aamirafridi/jQuery.Marquee
The following works:
http://jsfiddle.net/xAGRJ/4/
The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:
lefttime = setInterval(scrollticker, 50);
instead of
lefttime = setInterval("scrollticker()", 50);
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
I made my own version, based in the code presented above by #Tats_innit .
The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
My text marquee for more text,
and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Responsive resist jQuery marquee simple plugin. Tutorial:
// start plugin
(function($){
$.fn.marque = function(options, callback){
// check callback
if(typeof callback == 'function'){
callback.call(this);
} else{
console.log("second argument (callback) is not a function");
// throw "callback must be a function"; //only if callback for some reason is required
// return this; //only if callback for some reason is required
}
//set and overwrite default functions
var defOptions = $.extend({
speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
select: $('.message div'),
clickSelect: '', // selector that on click will redirect user ... (optional)
clickUrl: '' //... to this url. (optional)
}, options);
//Run marque plugin
var windowWidth = $(window).width();
var textWidth = defOptions.select.outerWidth();
var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
var startingPosition = (windowWidth + textWidth);
var curentPosition = (windowWidth + textWidth);
var speedProportionToLocation = curentPosition / startingPosition;
defOptions.select.css({'right': -(textWidth)});
defOptions.select.show();
var animation;
function marquee(animation){
curentPosition = (windowWidth + defOptions.select.outerWidth());
speedProportionToLocation = curentPosition / startingPosition;
animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
defOptions.select.css({'right': -(textWidth)});
});
}
var play = setInterval(marquee, 200);
//add onclick behaviour
if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
defOptions.clickSelect.click(function(){
window.location.href = defOptions.clickUrl;
});
}
return this;
};
}(jQuery));
// end plugin
Use this custom jQuery plugin as bellow:
//use example
$(window).marque({
speedPixelsInOneSecound: 150, // spped pixels/secound
select: $('.message div'), // select an object on which you want to apply marquee effects.
clickSelect: $('.message'), // select clicable object (optional)
clickUrl: 'services.php' // define redirection url (optional)
});
Marquee using CSS animations.
`<style>
.items-holder {
animation: moveSlideshow 5s linear infinite;
}
.items-holder:hover {
animation-play-state: paused;
}
#keyframes moveSlideshow {
100% {
transform: translateX(100%);
}
}
</style>`
I try use only css for it this link.
<style>
.header {
background: #212121;
overflow: hidden;
height: 65px;
position: relative;
}
.header div {
display: flex;
flex-direction: row;
align-items: center;
overflow: hidden;
height: 65px;
transform: translate(100%, 0);
}
.header div * {
font-family: "Roboto", sans-serif;
color: #fff339;
text-transform: uppercase;
text-decoration: none;
}
.header div img {
height: 60px;
margin-right: 20px;
}
.header .ticker-wrapper__container{
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
top: 0;
right: 0;
animation: ticker 30s infinite linear forwards;
}
.header:hover .ticker-wrapper__container{
animation-play-state: paused;
}
.ticker-wrapper__container a{
display: flex;
margin-right: 60px;
align-items: center;
}
#keyframes ticker {
0% {
transform: translate(100%, 0);
}
50% {
transform: translate(0, 0);
}
100% {
transform: translate(-100%, 0);
}
}
</style>

Internet Explorer: Issue with Overlay / opacity

I'm trying to create a dialog window using the following CSS:
#blackOverlay {
display: block;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000000;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";
filter: alpha(opacity=80);
-moz-opacity: 0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
z-index: 1001;
}
#whiteOverlay {
display: block;
position: absolute;
top: 10%;
left: 10%;
width: 80%;
height: 80%;
z-index:2002;
overflow: auto;
background: #c4e982;
}
and the following JS:
var div = $("<div id='blackOverlay'></div");
$("body").prepend(div);
var div = $("<div id='whiteOverlay'></div");
div.html("Loading......");
var u = "myurl?function=example";
div.load(u);
$("body").prepend(div);
This works correctly in Firefox, Safari, Chrome and Opera.
Unfortunately it fails in IE, at least on version 8.0. The color/opacity is only applied to body and NOT on other DIV's. Instead of "hidding" everything behind the blackOverlay, everything (links, buttons, input fields, ...) is still usable although the loaded content is displayed correctly (in front, center of screen).
Any help is appreciated!
Thank you jduren for pointing me in the right direction. After attempting to handle it in similar way as described here I came up with the following workaround:
function shime() {
jQuery.each(jQuery.browser, function(i) {
if($.browser.msie){
$('div').each(function() {
$(this).addClass("shine");
});
}
});
}
function unshime() {
jQuery.each(jQuery.browser, function(i) {
if($.browser.msie){
$(".shine").each(function() {
$(this).removeClass("shine");
});
}
});
}
And the following CSS:
div.shine {
display: none;
}
I know that it's not the best solution, but I'm getting tired of running in circles due to IE "features".
You need to create what's called an iFrame shim. IE paints controls over everything that isn't windowed so you won't be able to handle this by CSS/HTML hacks alone.
Here is a quick overview of Iframe Shimming http://www.macridesweb.com/oltest/IframeShim.html
Also, the Mootools More library includes an iFrame shim Feature http://mootools.net/docs/more/Utilities/IframeShim as do most popular javascript frameworks that create overlayed UI elements.
This is the IFrame Shim class from mootools more library to give you an idea of what's involved, don't use this as it depends on other Mootoosl classes.
var IframeShim = new Class({
Implements: [Options, Events, Class.Occlude],
options: {
className: 'iframeShim',
src: 'javascript:false;document.write("");',
display: false,
zIndex: null,
margin: 0,
offset: {x: 0, y: 0},
browsers: (Browser.Engine.trident4 || (Browser.Engine.gecko && !Browser.Engine.gecko19 && Browser.Platform.mac))
},
property: 'IframeShim',
initialize: function(element, options){
this.element = document.id(element);
if (this.occlude()) return this.occluded;
this.setOptions(options);
this.makeShim();
return this;
},
makeShim: function(){
if(this.options.browsers){
var zIndex = this.element.getStyle('zIndex').toInt();
if (!zIndex){
zIndex = 1;
var pos = this.element.getStyle('position');
if (pos == 'static' || !pos) this.element.setStyle('position', 'relative');
this.element.setStyle('zIndex', zIndex);
}
zIndex = ($chk(this.options.zIndex) && zIndex > this.options.zIndex) ? this.options.zIndex : zIndex - 1;
if (zIndex < 0) zIndex = 1;
this.shim = new Element('iframe', {
src: this.options.src,
scrolling: 'no',
frameborder: 0,
styles: {
zIndex: zIndex,
position: 'absolute',
border: 'none',
filter: 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
},
'class': this.options.className
}).store('IframeShim', this);
var inject = (function(){
this.shim.inject(this.element, 'after');
this[this.options.display ? 'show' : 'hide']();
this.fireEvent('inject');
}).bind(this);
if (!IframeShim.ready) window.addEvent('load', inject);
else inject();
} else {
this.position = this.hide = this.show = this.dispose = $lambda(this);
}
},
position: function(){
if (!IframeShim.ready || !this.shim) return this;
var size = this.element.measure(function(){
return this.getSize();
});
if (this.options.margin != undefined){
size.x = size.x - (this.options.margin * 2);
size.y = size.y - (this.options.margin * 2);
this.options.offset.x += this.options.margin;
this.options.offset.y += this.options.margin;
}
this.shim.set({width: size.x, height: size.y}).position({
relativeTo: this.element,
offset: this.options.offset
});
return this;
},
hide: function(){
if (this.shim) this.shim.setStyle('display', 'none');
return this;
},
show: function(){
if (this.shim) this.shim.setStyle('display', 'block');
return this.position();
},
dispose: function(){
if (this.shim) this.shim.dispose();
return this;
},
destroy: function(){
if (this.shim) this.shim.destroy();
return this;
}
});
window.addEvent('load', function(){
IframeShim.ready = true;
});

Categories

Resources