How to set the height of box-slider - javascript

I have a slider(source code here) that currently has it's height set to 100%. However, I want the slider to have a height of 550px so it does not look too big, but am not managing to get that right for some reason.
Below is the full code and running snippet:
(function(factory){
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
})(function($){
var Zippy = (function(element, settings){
var instanceUid = 0;
function _Zippy(element, settings){
this.defaults = {
slideDuration: '3000',
speed: 500,
arrowRight: '.arrow-right',
arrowLeft: '.arrow-left'
};
this.settings = $.extend({},this,this.defaults,settings);
this.initials = {
currSlide : 0,
$currSlide: null,
totalSlides : false,
csstransitions: false
};
$.extend(this,this.initials);
this.$el = $(element);
this.changeSlide = $.proxy(this.changeSlide,this);
this.init();
this.instanceUid = instanceUid++;
}
return _Zippy;
})();
Zippy.prototype.init = function(){
this.csstransitionsTest();
this.$el.addClass('zippy-carousel');
this.build();
this.events();
this.activate();
this.initTimer();
};
Zippy.prototype.csstransitionsTest = function(){
var elem = document.createElement('modernizr');
var props = ["transition","WebkitTransition","MozTransition","OTransition","msTransition"];
for ( var i in props ) {
var prop = props[i];
var result = elem.style[prop] !== undefined ? prop : false;
if (result){
this.csstransitions = result;
break;
}
}
};
Zippy.prototype.addCSSDuration = function(){
var _ = this;
this.$el.find('.slide').each(function(){
this.style[_.csstransitions+'Duration'] = _.settings.speed+'ms';
});
}
Zippy.prototype.removeCSSDuration = function(){
var _ = this;
this.$el.find('.slide').each(function(){
this.style[_.csstransitions+'Duration'] = '';
});
}
Zippy.prototype.build = function(){
var $indicators = this.$el.append('<ul class="indicators" >').find('.indicators');
this.totalSlides = this.$el.find('.slide').length;
for(var i = 0; i < this.totalSlides; i++) $indicators.append('<li data-index='+i+'>');
};
Zippy.prototype.activate = function(){
this.$currSlide = this.$el.find('.slide').eq(0);
this.$el.find('.indicators li').eq(0).addClass('active');
};
Zippy.prototype.events = function(){
$('body')
.on('click',this.settings.arrowRight,{direction:'right'},this.changeSlide)
.on('click',this.settings.arrowLeft,{direction:'left'},this.changeSlide)
.on('click','.indicators li',this.changeSlide);
};
Zippy.prototype.clearTimer = function(){
if (this.timer) clearInterval(this.timer);
};
Zippy.prototype.initTimer = function(){
this.timer = setInterval(this.changeSlide, this.settings.slideDuration);
};
Zippy.prototype.startTimer = function(){
this.initTimer();
this.throttle = false;
};
Zippy.prototype.changeSlide = function(e){e
if (this.throttle) return;
this.throttle = true;
this.clearTimer();
var direction = this._direction(e);
var animate = this._next(e,direction);
if (!animate) return;
var $nextSlide = this.$el.find('.slide').eq(this.currSlide).addClass(direction + ' active');
if (!this.csstransitions){
this._jsAnimation($nextSlide,direction);
} else {
this._cssAnimation($nextSlide,direction);
}
};
Zippy.prototype._direction = function(e){
var direction;
// Default to forward movement
if (typeof e !== 'undefined'){
direction = (typeof e.data === 'undefined' ? 'right' : e.data.direction);
} else {
direction = 'right';
}
return direction;
};
Zippy.prototype._next = function(e,direction){
var index = (typeof e !== 'undefined' ? $(e.currentTarget).data('index') : undefined);
switch(true){
case( typeof index !== 'undefined'):
if (this.currSlide == index){
this.startTimer();
return false;
}
this.currSlide = index;
break;
case(direction == 'right' && this.currSlide < (this.totalSlides - 1)):
this.currSlide++;
break;
case(direction == 'right'):
this.currSlide = 0;
break;
case(direction == 'left' && this.currSlide === 0):
this.currSlide = (this.totalSlides - 1);
break;
case(direction == 'left'):
this.currSlide--;
break;
}
return true;
};
Zippy.prototype._cssAnimation = function($nextSlide,direction){
setTimeout(function(){
this.$el.addClass('transition');
this.addCSSDuration();
this.$currSlide.addClass('shift-'+direction);
}.bind(this),100);
setTimeout(function(){
this.$el.removeClass('transition');
this.removeCSSDuration();
this.$currSlide.removeClass('active shift-left shift-right');
this.$currSlide = $nextSlide.removeClass(direction);
this._updateIndicators();
this.startTimer();
}.bind(this),100 + this.settings.speed);
};
Zippy.prototype._jsAnimation = function($nextSlide,direction){
var _ = this;
if(direction == 'right') _.$currSlide.addClass('js-reset-left');
var animation = {};
animation[direction] = '0%';
var animationPrev = {};
animationPrev[direction] = '100%';
this.$currSlide.animate(animationPrev,this.settings.speed);
$nextSlide.animate(animation,this.settings.speed,'swing',function(){
_.$currSlide.removeClass('active js-reset-left').attr('style','');
_.$currSlide = $nextSlide.removeClass(direction).attr('style','');
_._updateIndicators();
_.startTimer();
});
};
Zippy.prototype._updateIndicators = function(){
this.$el.find('.indicators li').removeClass('active').eq(this.currSlide).addClass('active');
};
$.fn.Zippy = function(options){
return this.each(function(index,el){
el.Zippy = new Zippy(el,options);
});
};
});
var args = {
arrowRight : '.arrow-right',
arrowLeft : '.arrow-left',
speed : 1000,
slideDuration : 4000
};
$('.carousel').Zippy(args);
(function(factory){
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
})(function($){
var Zippy = (function(element, settings){
var instanceUid = 0;
function _Zippy(element, settings){
this.defaults = {
slideDuration: '3000',
speed: 500,
arrowRight: '.arrow-right',
arrowLeft: '.arrow-left'
};
this.settings = $.extend({},this,this.defaults,settings);
this.initials = {
currSlide : 0,
$currSlide: null,
totalSlides : false,
csstransitions: false
};
$.extend(this,this.initials);
this.$el = $(element);
this.changeSlide = $.proxy(this.changeSlide,this);
this.init();
this.instanceUid = instanceUid++;
}
return _Zippy;
})();
Zippy.prototype.init = function(){
this.csstransitionsTest();
this.$el.addClass('zippy-carousel');
this.build();
this.events();
this.activate();
this.initTimer();
};
Zippy.prototype.csstransitionsTest = function(){
var elem = document.createElement('modernizr');
var props = ["transition","WebkitTransition","MozTransition","OTransition","msTransition"];
for ( var i in props ) {
var prop = props[i];
var result = elem.style[prop] !== undefined ? prop : false;
if (result){
this.csstransitions = result;
break;
}
}
};
Zippy.prototype.addCSSDuration = function(){
var _ = this;
this.$el.find('.slide').each(function(){
this.style[_.csstransitions+'Duration'] = _.settings.speed+'ms';
});
}
Zippy.prototype.removeCSSDuration = function(){
var _ = this;
this.$el.find('.slide').each(function(){
this.style[_.csstransitions+'Duration'] = '';
});
}
Zippy.prototype.build = function(){
var $indicators = this.$el.append('<ul class="indicators" >').find('.indicators');
this.totalSlides = this.$el.find('.slide').length;
for(var i = 0; i < this.totalSlides; i++) $indicators.append('<li data-index='+i+'>');
};
Zippy.prototype.activate = function(){
this.$currSlide = this.$el.find('.slide').eq(0);
this.$el.find('.indicators li').eq(0).addClass('active');
};
Zippy.prototype.events = function(){
$('body')
.on('click',this.settings.arrowRight,{direction:'right'},this.changeSlide)
.on('click',this.settings.arrowLeft,{direction:'left'},this.changeSlide)
.on('click','.indicators li',this.changeSlide);
};
Zippy.prototype.clearTimer = function(){
if (this.timer) clearInterval(this.timer);
};
Zippy.prototype.initTimer = function(){
this.timer = setInterval(this.changeSlide, this.settings.slideDuration);
};
Zippy.prototype.startTimer = function(){
this.initTimer();
this.throttle = false;
};
Zippy.prototype.changeSlide = function(e){e
if (this.throttle) return;
this.throttle = true;
this.clearTimer();
var direction = this._direction(e);
var animate = this._next(e,direction);
if (!animate) return;
var $nextSlide = this.$el.find('.slide').eq(this.currSlide).addClass(direction + ' active');
if (!this.csstransitions){
this._jsAnimation($nextSlide,direction);
} else {
this._cssAnimation($nextSlide,direction);
}
};
Zippy.prototype._direction = function(e){
var direction;
// Default to forward movement
if (typeof e !== 'undefined'){
direction = (typeof e.data === 'undefined' ? 'right' : e.data.direction);
} else {
direction = 'right';
}
return direction;
};
Zippy.prototype._next = function(e,direction){
var index = (typeof e !== 'undefined' ? $(e.currentTarget).data('index') : undefined);
switch(true){
case( typeof index !== 'undefined'):
if (this.currSlide == index){
this.startTimer();
return false;
}
this.currSlide = index;
break;
case(direction == 'right' && this.currSlide < (this.totalSlides - 1)):
this.currSlide++;
break;
case(direction == 'right'):
this.currSlide = 0;
break;
case(direction == 'left' && this.currSlide === 0):
this.currSlide = (this.totalSlides - 1);
break;
case(direction == 'left'):
this.currSlide--;
break;
}
return true;
};
Zippy.prototype._cssAnimation = function($nextSlide,direction){
setTimeout(function(){
this.$el.addClass('transition');
this.addCSSDuration();
this.$currSlide.addClass('shift-'+direction);
}.bind(this),100);
setTimeout(function(){
this.$el.removeClass('transition');
this.removeCSSDuration();
this.$currSlide.removeClass('active shift-left shift-right');
this.$currSlide = $nextSlide.removeClass(direction);
this._updateIndicators();
this.startTimer();
}.bind(this),100 + this.settings.speed);
};
Zippy.prototype._jsAnimation = function($nextSlide,direction){
var _ = this;
if(direction == 'right') _.$currSlide.addClass('js-reset-left');
var animation = {};
animation[direction] = '0%';
var animationPrev = {};
animationPrev[direction] = '100%';
this.$currSlide.animate(animationPrev,this.settings.speed);
$nextSlide.animate(animation,this.settings.speed,'swing',function(){
_.$currSlide.removeClass('active js-reset-left').attr('style','');
_.$currSlide = $nextSlide.removeClass(direction).attr('style','');
_._updateIndicators();
_.startTimer();
});
};
Zippy.prototype._updateIndicators = function(){
this.$el.find('.indicators li').removeClass('active').eq(this.currSlide).addClass('active');
};
$.fn.Zippy = function(options){
return this.each(function(index,el){
el.Zippy = new Zippy(el,options);
});
};
});
var args = {
arrowRight : '.arrow-right',
arrowLeft : '.arrow-left',
speed : 1000,
slideDuration : 4000
};
$('.carousel').Zippy(args);
<div class="wrapper">
<div class="carousel">
<div class="inner">
<div class="slide active">
<div class="slide-box">
<h1>1</h1>
<h2>Heading 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
</div>
</div>
<div class="slide">
<div class="slide-box">
<h1>2</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
</div>
</div>
<div class="slide">
<div class="slide-box">
<h1>3</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.</p>
</div>
</div>
</div>
<div class="arrow arrow-left"></div>
<div class="arrow arrow-right"></div>
</div>
</div>
I tried giving a height of 500px to the wrapper class but it does not seem to be the best way.
How can I adjust the height of the slider and also keep the content in the middle of the box when I resize the page?
Here mycodepen if needed
Thank you in advance

The padding in the slide style give problems with height:
.slide {
text-align: center;
padding-top: 25%;
background-size: cover;
}
This is my fix to your style to get the right height, I also centered horizontally and vertically the slide-box and the text:
/********For better see the text********/
p{
color:white;
}
h2{
color:white;
}
/**************************************/
.wrapper{
width:100%;
position:relative;
height: 50px;
}
.slide-box {
max-width: 1300px;
margin: 0 auto;
padding: 54px;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
/**
* Padding is set relative to the width
* of the element, so here padding-top:60% is
* a percentage of the width. This allows us
* to set the height as a ratio of the width
*
*/
.carousel{
width: 100%;
height: 500px;
position: relative;
/* padding-top: 50%; */
overflow: hidden;
}
.inner{
width: 100%;
height: 100%;
position: absolute;
top:0;
left: 0;
}
/**
* ==========================
* Animation styles
*
* Notes:
* 1. We use z-index to position active slides in-front
* of non-active slides
* 2. We set right:0 and left:0 on .slide to provide us with
* a default positioning on both sides of the slide. This allows
* us to trigger JS and CSS3 animations easily
*
*/
.slide{
width: 100%;
height: 500px;
position: absolute;
top:0;
right:0;
left:0;
z-index: 1;
opacity: 0;
}
.slide.active,
.slide.left,
.slide.right{
z-index: 2;
opacity: 1;
}
/**
* ==========================
* JS animation styles
*
* We use jQuery.animate to control the sliding animations
* when CSS3 animations are not available. In order for
* the next slide to slide in from the right, we need
* to change the left:0 property of the slide to left:auto
*
*/
.js-reset-left{left:auto}
/**
* ==========================
* CSS animation styles
*
* .slide.left and .slide.right set-up
* the to-be-animated slide so that it can slide
* into view. For example, a slide that is about
* to slide in from the right will:
* 1. Be positioned to the right of the viewport (right:-100%)
* 2. Slide in when the style is superseded with a more specific style (right:0%)
*
*/
.slide.left{
left:-100%;
right:0;
}
.slide.right{
right:-100%;
left: auto;
}
.transition .slide.left{left:0%}
.transition .slide.right{right:0%}
/**
* The following classes slide the previously active
* slide out of view before positioning behind the
* currently active slide
*
*/
.transition .slide.shift-right{right: 100%;left:auto}
.transition .slide.shift-left{left: 100%;right:auto}
/**
* This sets the CSS properties that will animate. We set the
* transition-duration property dynamically via JS.
* We use the browser's default transition-timing-function
* for simplicity's sake
*
* It is important to note that we are using CodePen's inbuilt
* CSS3 property prefixer. For your own projects, you will need
* to prefix the transition and transform properties here to ensure
* reliable support across browsers
*
*/
.transition .slide{
transition-property: right, left, margin;
}
/**
* ==========================
* Indicators
*
*/
.indicators{
width:100%;
position: absolute;
bottom:0;
z-index: 4;
padding:0;
text-align: center;
}
.indicators li{
width: 13px;
height: 13px;
display: inline-block;
margin: 5px;
background: #fff;
list-style-type: none;
border-radius: 50%;
cursor:pointer;
transition:background 0.3s ease-out;
}
.indicators li.active{background:#93278f}
.indicators li:hover{background-color:#2b2b2b}
/**
* ==========================
* Arrows
*
*/
.arrow{
width: 20px;
height: 20px;
position:absolute;
top:50%;
z-index:5;
border-top:3px solid #fff;
border-right:3px solid #fff;
cursor:pointer;
transition:border-color 0.3s ease-out;
}
.arrow:hover{border-color:#93278f}
.arrow-left{
left:20px;
transform:rotate(225deg);
}
.arrow-right{
right:20px;
transform:rotate(45deg);
}
/**
* ==========================
* For demo purposes only
*
* Please note that the styles below are used
* for the purposes of this demo only. There is no need
* to use these in any of your own projects
*
*/
.slide{
text-align:left;
background-size:cover;
display: table-cell;
vertical-align: middle;
}
h1{
width:100px;
height:100px;
background-color:rgba(146, 45, 141,0.7);
margin:auto;
line-height:100px;
color:#fff;
font-size:2.4em;
border-radius:50%;
text-align: center;
}
.slide:nth-child(1){
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-1.jpg);
}
.slide:nth-child(2){
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-2.jpg);
}
.slide:nth-child(3){
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/163697/slide-3.jpg);
}

Related

fire a classLiss.add event only once in a loop in raw JS

everybody.
I've a problem probably well-know, but I can't find a solution also looking for it in the WEB.
I'm working on a progressive bar that shows the parts included in a 'title section' during screen scrolling.
Everything works fine except when I try to add a class (and remove it), because I'm not able to fire the event only once in the for-next loop.
Here is a part of the HTLM:
<body>
<div class="container">
<section class="onTop">
<nav>
<div class="scroll-title">MENU</div>
<div id="scroll-total">
<div id="scroll-part"></div>
</div>
</nav>
</section>
<div class="wrapper">
<div class="title">FIRST TITLE</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum, aut quo blanditiis hic numquam, sapiente maiores id,
[etc.]
here is the CSS parts those apply:
.scroll-title{
text-align: right;
font-size: 10px;
width: 15.5vh;
position: absolute;
top: 14%;
left: 50%;
transform: translateX(-50%) rotate(90deg);
border: 1px solid red;
transition: font-size .25s ease-out;
}
.scroll-title.action{
font-size: 20px;
}
The JS code put titles' heigths refecences in an array, then check if the scroll position is inside a part an move the bar. In that time the code changes the single title's DIV containing "scroll-title" class.
My idea is to add a CSS class to animate (with a transition) the title. So, I'm using a addEventListener to add and remove the class, but I'd like to fire this event only once, and I can't find a way to do it.
Thisi a part of the code:
let titleScroll = document.querySelector('.scroll-title');
let band = document.getElementById('scroll-total');
let scroll = document.getElementById('scroll-part');
let pageTitlesRif =[], pageTitlesText =[];
let pageTitles = document.querySelectorAll('.wrapper .title');
pageTitlesRif = [0];
pageTitlesText =['MENU'];
let rect;
let tot = band.offsetWidth;
let totSide = bandSide.offsetHeight;
for (var i = 0; i < pageTitles.length; i++) {
rect = pageTitles[i].getBoundingClientRect();
pageTitlesText.push(pageTitles[i].innerText);
pageTitlesRif.push(rect.bottom + document.documentElement.scrollTop);
}
let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
pageTitlesRif.push(scrollHeight);
console.log(scrollHeight);
window.onscroll = function() {
for (var i = 1; i < pageTitlesRif.length; i++) {
if (window.pageYOffset > pageTitlesRif[i - 1] && window.pageYOffset < pageTitlesRif[i]) {
titleScroll.classList.add('action');
let transitionEnd = whichTransitionEvent();
titleScroll.addEventListener(transitionEnd, putClass, false);
titleScroll.innerText = pageTitlesText[i - 1];
scroll.style.left = (pageTitlesRif[i-1] * tot / scrollHeight).toString()+ 'px';
scroll.style.width = ((pageTitlesRif[i] - pageTitlesRif[i - 1]) * tot /
scrollHeight).toString() + 'px';
}
}
}
let putClass = function(){
this.classList.remove('action');
}
function whichTransitionEvent(){
var t;
var el = document.createElement('fakeelement');
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
}
for(t in transitions){
if( el.style[t] !== undefined ){
return transitions[t];
}
}
}
Has somebody a suggestion to fix this?
Well, I had the solution under my eyes, and I made a mountain out of a molehill...
It's enuogh to control if the existing title is different from the one that comes in the loop, like this:
window.onscroll = function() {
for (var i = 1; i < pageTitlesRif.length; i++) {
if (window.pageYOffset > pageTitlesRif[i - 1] && window.pageYOffset < pageTitlesRif[i]) {
if (titleScroll.innerText != pageTitlesText[i - 1]){
titleScroll.innerText = pageTitlesText[i - 1];
titleScroll.classList.add('action');
let transitionEnd = whichTransitionEvent();
titleScroll.addEventListener(transitionEnd, putClass, false);
scroll.style.left = (pageTitlesRif[i-1] * tot / scrollHeight).toString()+ 'px';
scroll.style.width = ((pageTitlesRif[i] - pageTitlesRif[i - 1]) * tot /
scrollHeight).toString() + 'px';
}
}
}
}
In this way, the code on the title (and on the other tag elements) in executed once.

Scrolling marquee w/ repeating text

I want to have a scrolling marquee that never ends, and with that, I mean that there will never be a blank space in the marquee.
So when, for example, all text has been in the screen (viewport) and the latest words are marquee'ing, the marquee will repeat without first ending the marquee (meaning: all text has gone away into the left side [marquee: right -> left]). With repeat I mean that the text will just start over right behind where the marquee is
So when I have the marquee text " Hello poeple of the earth •", and that is here:
_ = blank
! = Char of first run of marquee
^ = char of second run of marquee
& = char of third run of marquee
________!!!!!!!!!!!!!!!!!!!!!!!!!!!!****************************^^^^^^^^^^^^^^^^^^^^^^^^^^^^&&&&&&&&
Ofcourse I need it to be smooth. Something like this answer, but without the blank spaces. The use of libraries doesn't matter.
Can anyone help me?
You can use marque plugin to achieve this
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: 5000,
//gap in pixels between the tickers
gap: 0,
//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: false
});
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
<body>
<div class="marquee">stuff to say 1|</div>
<div class="marquee">stuff to say 2|</div>
<div class="marquee">stuff to say 3|</div>
<div class="marquee">stuff to say 4|</div>
<div class="marquee">stuff to say 5</div>
</body>
I think this is what you want :)))
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>
Thank You sire.....I get it....What I need....
function start() {
new mq('latest-news');
mqRotate(mqr);
}
window.onload = start;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName("span")[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName("span")[0].innerHTML;
this.mqo.innerHTML = "";
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement("div");
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = "absolute";
this.mqo.ary[i].style.left = wid * i + "px";
this.mqo.ary[i].style.width = wid + "px";
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = parseInt(x.left, 10) - 1 + "px";
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = parseInt(z.style.left) + parseInt(z.style.width) * maxa + "px";
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout("mqRotate(mqr)", 20);
}
.marquee {
position: relative;
overflow: hidden;
text-align: center;
margin: 0 auto;
width: 100%;
height: 30px;
display: flex;
align-items: center;
white-space: nowrap;
}
#latest-news {
line-height: 32px;
a {
color: #555555;
font-size: 13px;
font-weight: 300;
&:hover {
color: #000000;
}
}
span {
font-size: 18px;
position: relative;
top: 4px;
color: #999999;
}
}
<div id="latest-news" class="marquee">
<span style="white-space:nowrap;">
<span> •</span>
one Lorem ipsum dolor sit amet
<span> •</span>
two In publishing and graphic design
<span> •</span>
three Lorem ipsum is a placeholder text commonly
</span>
</div>

Two button functionality in one

I'm trying to combine the functionality of two buttons into one. This is a program that enables/disables a text or image magnifier. If I enable the zoomer than I want both the text and image to magnify if they are hovered on and vice versa with disable.
How should I edit the function/code to reflect one button that controls the magnification of both image and text?
This is the function I believe is controlling the button and zooming:
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom:eq(" + $(this).attr('data-id') + ")").anythingZoomer(state);
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
The full project is below
;
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
"use strict";
$.anythingZoomer = function(el, options) {
var n, o, t, base = this;
base.$wrap = $(el);
base.wrap = el;
// Add a reverse reference to the DOM object
base.$wrap.data('zoomer', base);
base.version = '2.2.6';
base.init = function() {
base.options = o = $.extend({}, $.anythingZoomer.defaultOptions, options);
// default class names
n = $.anythingZoomer.classNames;
// true when small element is showing, false when large is visible
base.state = true;
base.enabled = true;
base.hovered = false;
base.$wrap.addClass(n.wrap).wrapInner('<span class="' + n.wrapInner + '"/>');
base.$inner = base.$wrap.find('.' + n.wrapInner);
base.$small = base.$wrap.find('.' + o.smallArea);
base.$large = base.$wrap.find('.' + o.largeArea);
base.update();
// Add classes after getting size
base.$large.addClass(n.large);
base.$small.addClass(n.small);
base.$inner
.bind('mouseenter' + n.namespace, function() {
if (!base.enabled) {
return;
}
base.saved = base.enabled;
base.hovered = true;
if (o.delay) {
clearTimeout(base.delay);
base.enabled = false;
base.delay = setTimeout(function() {
base.enabled = base.saved;
base.position.type = 'mousemove';
base.$inner.trigger(base.position);
base.reveal();
}, o.delay);
} else {
base.reveal();
}
})
.bind('mouseleave' + n.namespace, function() {
base.hovered = false;
if (!base.enabled) {
return;
}
if (o.delay) {
clearTimeout(base.delay);
base.enabled = base.saved;
}
if (base.state && base.enabled) {
// delay hiding to prevent flash if user hovers over it again
// i.e. moving from a link to the image
base.timer = setTimeout(function() {
if (base.$zoom.hasClass(n.windowed)) {
base.hideZoom(true);
}
}, 200);
}
})
.bind('mousemove' + n.namespace, function(e) {
if (!base.enabled) {
return;
}
base.position = e;
if (!base.hovered) {
return;
}
if (base.state && base.enabled) {
clearTimeout(base.timer);
// get current offsets in case page positioning has changed
// Double demo: expanded text demo will offset image demo zoom window
var off = base.$small.offset();
base.zoomAt(e.pageX - off.left, e.pageY - off.top, null, true);
}
})
.bind(o.switchEvent + (o.switchEvent !== '' ? n.namespace : ''), function() {
if (!base.enabled) {
return;
}
// toggle visible image
if (base.state) {
base.showLarge();
} else {
base.showSmall();
}
});
base.showSmall();
// add events
$.each('initialized zoom unzoom'.split(' '), function(i, f) {
if ($.isFunction(o[f])) {
base.$wrap.bind(f, o[f]);
}
});
base.initialized = true;
base.$wrap.trigger('initialized', base);
};
base.reveal = function() {
base.enabled = base.saved;
if (base.state && base.enabled) {
base.$zoom.stop(true, true).fadeIn(o.speed);
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
base.$smInner.addClass(n.hovered);
base.$wrap.trigger('zoom', base);
}
};
base.update = function() {
// make sure the large image is hidden
if (base.initialized) {
base.showSmall();
}
base.$smInner = (base.$small.find('.' + n.smallInner).length) ?
base.$small.find('.' + n.smallInner) :
base.$small.wrapInner('<span class="' + n.smallInner + '"/>').find('.' + n.smallInner);
base.$small.find('.' + n.overly).remove();
if (o.clone) {
t = base.$smInner.clone()
.removeAttr('id')
.removeClass(n.smallInner)
.addClass(n.largeInner);
if (base.$large.length) {
// large area exists, just add content
base.$large.html(t.html());
} else {
// no large area, so add it
t.wrap('<div class="' + o.largeArea + '">');
base.$small.after(t.parent());
// set base.$large again in case small area was cloned
base.$large = base.$wrap.find('.' + o.largeArea);
}
}
base.$lgInner = (base.$large.find('.' + n.largeInner).length) ?
base.$large.find('.' + n.largeInner) :
base.$large.wrapInner('<span class="' + n.largeInner + '"/>').find('.' + n.largeInner);
if (!base.$wrap.find('.' + n.zoom).length) {
base.$large.wrap('<div class="' + n.zoom + '"/>');
base.$zoom = base.$wrap.find('.' + n.zoom);
}
if (o.edit && !base.edit) {
base.edit = $('<span class="' + n.edit + '"></span>').appendTo(base.$zoom);
}
// wrap inner content with a span to get a more accurate width
// get height from either the inner content itself or the children of the inner content since span will need
// a "display:block" to get an accurate height, but adding that messes up the width
base.$zoom.show();
base.largeDim = [base.$lgInner.children().width(), Math.max(base.$lgInner.height(), base.$lgInner.children().height())];
base.zoomDim = base.last = [base.$zoom.width(), base.$zoom.height()];
base.$zoom.hide();
base.smallDim = [base.$smInner.children().width(), base.$small.height()];
base.$overlay = $('<div class="' + n.overly + '" style="position:absolute;left:0;top:0;" />').prependTo(base.$small);
base.ratio = [
base.largeDim[0] / (base.smallDim[0] || 1),
base.largeDim[1] / (base.smallDim[1] || 1)
];
base.$inner.add(base.$overlay).css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Show small image - Setup
base.showSmall = function() {
base.state = true;
base.$small.show();
base.$zoom
.removeClass(n.expanded)
.addClass(n.windowed + ' ' + n.zoom)
.css({
width: base.zoomDim[0],
height: base.zoomDim[1]
});
base.$inner.css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Switch small and large on double click
base.showLarge = function() {
base.state = false;
base.$small.hide();
base.$zoom
.stop(true, true)
.fadeIn(o.speed)
.addClass(n.expanded)
.removeClass(n.windowed + ' ' + n.zoom)
.css({
height: 'auto',
width: 'auto'
});
base.$inner.css({
width: base.largeDim[0],
height: base.largeDim[1]
});
base.$large.css({
left: 0,
top: 0,
width: base.largeDim[0],
height: base.largeDim[1]
});
};
// x,y coords -> George Washington in image demo
// base.setTarget( 82, 50, [200,200] );
// 'selector', [xOffset, yOffset], [zoomW, zoomH] -> Aug 26 in calendar demo
// base.setTarget( '.day[rel=2009-08-26]', [0, 0], [200, 200] );
base.setTarget = function(tar, sec, sz) {
var t, x = 0,
y = 0;
clearTimeout(base.timer);
if (!base.$zoom.hasClass(n.windowed)) {
base.showSmall();
}
// x, y coords
if (!isNaN(tar) && !isNaN(sec)) {
x = parseInt(tar, 10);
y = parseInt(sec, 10);
} else if (typeof(tar) === 'string' && $(tar).length) {
// '.selector', [xOffSet, yOffSet]
t = $(tar);
x = t.position().left + t.width() / 2 + (sec ? sec[0] || 0 : 0);
y = t.position().top + t.height() / 2 + (sec ? sec[1] || 0 : 0);
}
base.zoomAt(x, y, sz);
// add overlay
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
// hovered, but not really
base.$smInner.addClass(n.hovered);
// zoom window triggered
base.$wrap.trigger('zoom', base);
};
// x, y, [zoomX, zoomY] - zoomX, zoomY are the dimensions of the zoom window
base.zoomAt = function(x, y, sz, internal) {
var sx = (sz ? sz[0] || 0 : 0) || base.last[0],
sy = (sz ? sz[1] || sz[0] || 0 : 0) || base.last[1],
sx2 = sx / 2,
sy2 = sy / 2,
ex = o.edge || (o.edge === 0 ? 0 : sx2 * 0.66), // 2/3 of zoom window
ey = o.edge || (o.edge === 0 ? 0 : sy2 * 0.66), // allows edge to be zero
m = parseInt(base.$inner.css('margin-left'), 10) || base.$inner.position().left || 0;
// save new zoom size
base.last = [sx, sy];
// save x, y for external access
base.current = [x, y];
// show coordinates
if (o.edit) {
base.edit.html(Math.round(x) + ', ' + Math.round(y));
}
if ((x < -ex) || (x > base.smallDim[0] + ex) || (y < -ey) || (y > base.smallDim[1] + ey)) {
base.hideZoom(internal);
return;
} else {
// Sometimes the mouseenter event is delayed
base.$zoom.stop(true, true).fadeIn(o.speed);
}
// center zoom under the cursor
base.$zoom.css({
left: x - sx2 + m,
top: y - sy2,
width: sx,
height: sy
});
// match locations of small element to the large
base.$large.css({
left: -(x - o.offsetX - sx2 / 2) * base.ratio[0],
top: -(y - o.offsetY - sy2 / 2) * base.ratio[1]
});
};
base.hideZoom = function(internal) {
if (internal && base.$smInner.hasClass(n.hovered)) {
base.$wrap.trigger('unzoom', base);
}
base.last = base.zoomDim;
base.$zoom.stop(true, true).fadeOut(o.speed);
base.$overlay.removeClass(n.overlay);
base.$smInner.removeClass(n.hovered);
base.lastKey = null;
};
base.setEnabled = function(enable) {
base.enabled = enable;
if (enable) {
var off = base.$small.offset();
base.zoomAt(base.position.pageX - off.left, base.position.pageY - off.top, null, true);
} else {
base.showSmall();
base.hideZoom();
base.hovered = false;
}
};
// Initialize zoomer
base.init();
};
// class names used by anythingZoomer
$.anythingZoomer.classNames = {
namespace: '.anythingZoomer', // event namespace
wrap: 'az-wrap',
wrapInner: 'az-wrap-inner',
large: 'az-large',
largeInner: 'az-large-inner',
small: 'az-small',
smallInner: 'az-small-inner',
overlay: 'az-overlay', // toggled class name
overly: 'az-overly', // overlay unstyled class
hovered: 'az-hovered',
zoom: 'az-zoom',
windowed: 'az-windowed', // zoom window active
expanded: 'az-expanded', // zoom window inactive (large is showing)
edit: 'az-coords', // coordinate window
scrollzoom: 'az-scrollzoom'
};
$.anythingZoomer.defaultOptions = {
// content areas
smallArea: 'small', // class of small content area; the element with this class name must be inside of the wrapper
largeArea: 'large', // class of large content area; this class must exist inside of the wrapper. When the clone option is true, it will add this automatically
clone: false, // Make a clone of the small content area, use css to modify the style
// appearance
overlay: false, // set to true to apply overlay class "az-overlay"; false to not apply it
speed: 100, // fade animation speed (in milliseconds)
edge: 30, // How far outside the wrapped edges the mouse can go; previously called "expansionSize"
offsetX: 0, // adjust the horizontal position of the large content inside the zoom window as desired
offsetY: 0, // adjust the vertical position of the large content inside the zoom window as desired
// functionality
switchEvent: 'dblclick', // event that allows toggling between small and large elements - default is double click
delay: 0, // time to delay before revealing the zoom window.
// edit mode
edit: false // add x,y coordinates into zoom window to make it easier to find coordinates
};
$.fn.anythingZoomer = function(options, second, sx, sy) {
return this.each(function() {
var anyZoom = $(this).data('zoomer');
// initialize the zoomer but prevent multiple initializations
if (/object|undefined/.test(typeof options)) {
if (anyZoom) {
anyZoom.update();
} else {
(new $.anythingZoomer(this, options));
}
} else if (anyZoom && (typeof options === 'string' || (!isNaN(options) && !isNaN(second)))) {
if (/(en|dis)able/.test(options)) {
anyZoom.setEnabled(options === 'enable');
} else {
anyZoom.setTarget(options, second, sx, sy);
}
}
});
};
$.fn.getAnythingZoomer = function() {
return this.data('zoomer');
};
return $.anythingzoomer;
}));
/* AnythingZoomer */
.az-wrap,
.az-small,
.az-large {
position: relative;
}
.az-wrap-inner {
display: block;
margin: 0 auto;
/* center small & large content */
}
/* This wraps the large image and hides it */
.az-zoom {
background: #fff;
border: #333 1px solid;
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
overflow: hidden;
z-index: 100;
display: none;
-moz-box-shadow: inset 0px 0px 4px #000;
-webkit-box-shadow: inset 0px 0px 4px #000;
box-shadow: inset 0px 0px 4px #000;
}
/* Class applied to az-mover when large image is windowed */
.az-windowed {
overflow: hidden;
position: absolute;
}
/* Class applied to az-mover when large image is fully shown */
.az-expanded {
height: auto;
width: auto;
position: static;
overflow: visible;
}
/* overlay small area */
.az-overlay {
background-color: #000;
opacity: 0.3;
filter: alpha(opacity=30);
z-index: 10;
}
/* edit mode coordinate styling */
.az-coords {
display: none;
/* hidden when expanded */
}
.az-zoom .az-coords {
display: block;
position: absolute;
top: 0;
right: 0;
background: #000;
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
/* ZOOM CONTAINER */
.zoom {
display: block;
margin: 0 auto;
}
.large {
background: white;
}
/* FOR TEXT DEMO */
.small p {
font-size: 16px;
width: 700px
}
.large p {
font-size: 32px;
width: 1400px;
}
/* FOR IMAGE DEMO */
.small img {
width: 250px;
}
.large img {
width: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image and Text Magnifier</title>
<!-- anythingZoomer required -->
<link rel="stylesheet" href="css/anythingzoomer.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.anythingzoomer.js"></script>
<script>
$(function() {
// clone the text
$(".zoom:first").anythingZoomer({
clone: true
});
$(".zoom:last").anythingZoomer();
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom:eq(" + $(this).attr('data-id') + ")").anythingZoomer(state);
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
});
</script>
</head>
<body id="double">
<div id="main-content">
<p>Double click within the section to toggle between the large and small versions.</p>
<p><strong>Text Demo <button data-id="0">disable</button></strong></p>
<div class="zoom">
<div class="small">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae
est. Mauris placerat eleifend leo.</p>
</div>
<!-- the clone option will automatically make a div.large if it doesn't exist -->
</div>
<br>
<p><strong>Image Demo <button data-id="1">disable</button></strong></p>
<div class="zoom second">
<div class="small">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="small rushmore">
</div>
<div class="large">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="big rushmore">
</div>
</div>
</div>
</body>
</html>
This works! Just loop through each of the elements using .each and then add the scroll zoomer function to it.when the button is pressed, loop through the elements again and apply the toggle functionality.
;
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
"use strict";
$.anythingZoomer = function(el, options) {
var n, o, t, base = this;
base.$wrap = $(el);
base.wrap = el;
// Add a reverse reference to the DOM object
base.$wrap.data('zoomer', base);
base.version = '2.2.6';
base.init = function() {
base.options = o = $.extend({}, $.anythingZoomer.defaultOptions, options);
// default class names
n = $.anythingZoomer.classNames;
// true when small element is showing, false when large is visible
base.state = true;
base.enabled = true;
base.hovered = false;
base.$wrap.addClass(n.wrap).wrapInner('<span class="' + n.wrapInner + '"/>');
base.$inner = base.$wrap.find('.' + n.wrapInner);
base.$small = base.$wrap.find('.' + o.smallArea);
base.$large = base.$wrap.find('.' + o.largeArea);
base.update();
// Add classes after getting size
base.$large.addClass(n.large);
base.$small.addClass(n.small);
base.$inner
.bind('mouseenter' + n.namespace, function() {
if (!base.enabled) {
return;
}
base.saved = base.enabled;
base.hovered = true;
if (o.delay) {
clearTimeout(base.delay);
base.enabled = false;
base.delay = setTimeout(function() {
base.enabled = base.saved;
base.position.type = 'mousemove';
base.$inner.trigger(base.position);
base.reveal();
}, o.delay);
} else {
base.reveal();
}
})
.bind('mouseleave' + n.namespace, function() {
base.hovered = false;
if (!base.enabled) {
return;
}
if (o.delay) {
clearTimeout(base.delay);
base.enabled = base.saved;
}
if (base.state && base.enabled) {
// delay hiding to prevent flash if user hovers over it again
// i.e. moving from a link to the image
base.timer = setTimeout(function() {
if (base.$zoom.hasClass(n.windowed)) {
base.hideZoom(true);
}
}, 200);
}
})
.bind('mousemove' + n.namespace, function(e) {
if (!base.enabled) {
return;
}
base.position = e;
if (!base.hovered) {
return;
}
if (base.state && base.enabled) {
clearTimeout(base.timer);
// get current offsets in case page positioning has changed
// Double demo: expanded text demo will offset image demo zoom window
var off = base.$small.offset();
base.zoomAt(e.pageX - off.left, e.pageY - off.top, null, true);
}
})
.bind(o.switchEvent + (o.switchEvent !== '' ? n.namespace : ''), function() {
if (!base.enabled) {
return;
}
// toggle visible image
if (base.state) {
base.showLarge();
} else {
base.showSmall();
}
});
base.showSmall();
// add events
$.each('initialized zoom unzoom'.split(' '), function(i, f) {
if ($.isFunction(o[f])) {
base.$wrap.bind(f, o[f]);
}
});
base.initialized = true;
base.$wrap.trigger('initialized', base);
};
base.reveal = function() {
base.enabled = base.saved;
if (base.state && base.enabled) {
base.$zoom.stop(true, true).fadeIn(o.speed);
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
base.$smInner.addClass(n.hovered);
base.$wrap.trigger('zoom', base);
}
};
base.update = function() {
// make sure the large image is hidden
if (base.initialized) {
base.showSmall();
}
base.$smInner = (base.$small.find('.' + n.smallInner).length) ?
base.$small.find('.' + n.smallInner) :
base.$small.wrapInner('<span class="' + n.smallInner + '"/>').find('.' + n.smallInner);
base.$small.find('.' + n.overly).remove();
if (o.clone) {
t = base.$smInner.clone()
.removeAttr('id')
.removeClass(n.smallInner)
.addClass(n.largeInner);
if (base.$large.length) {
// large area exists, just add content
base.$large.html(t.html());
} else {
// no large area, so add it
t.wrap('<div class="' + o.largeArea + '">');
base.$small.after(t.parent());
// set base.$large again in case small area was cloned
base.$large = base.$wrap.find('.' + o.largeArea);
}
}
base.$lgInner = (base.$large.find('.' + n.largeInner).length) ?
base.$large.find('.' + n.largeInner) :
base.$large.wrapInner('<span class="' + n.largeInner + '"/>').find('.' + n.largeInner);
if (!base.$wrap.find('.' + n.zoom).length) {
base.$large.wrap('<div class="' + n.zoom + '"/>');
base.$zoom = base.$wrap.find('.' + n.zoom);
}
if (o.edit && !base.edit) {
base.edit = $('<span class="' + n.edit + '"></span>').appendTo(base.$zoom);
}
// wrap inner content with a span to get a more accurate width
// get height from either the inner content itself or the children of the inner content since span will need
// a "display:block" to get an accurate height, but adding that messes up the width
base.$zoom.show();
base.largeDim = [base.$lgInner.children().width(), Math.max(base.$lgInner.height(), base.$lgInner.children().height())];
base.zoomDim = base.last = [base.$zoom.width(), base.$zoom.height()];
base.$zoom.hide();
base.smallDim = [base.$smInner.children().width(), base.$small.height()];
base.$overlay = $('<div class="' + n.overly + '" style="position:absolute;left:0;top:0;" />').prependTo(base.$small);
base.ratio = [
base.largeDim[0] / (base.smallDim[0] || 1),
base.largeDim[1] / (base.smallDim[1] || 1)
];
base.$inner.add(base.$overlay).css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Show small image - Setup
base.showSmall = function() {
base.state = true;
base.$small.show();
base.$zoom
.removeClass(n.expanded)
.addClass(n.windowed + ' ' + n.zoom)
.css({
width: base.zoomDim[0],
height: base.zoomDim[1]
});
base.$inner.css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Switch small and large on double click
base.showLarge = function() {
base.state = false;
base.$small.hide();
base.$zoom
.stop(true, true)
.fadeIn(o.speed)
.addClass(n.expanded)
.removeClass(n.windowed + ' ' + n.zoom)
.css({
height: 'auto',
width: 'auto'
});
base.$inner.css({
width: base.largeDim[0],
height: base.largeDim[1]
});
base.$large.css({
left: 0,
top: 0,
width: base.largeDim[0],
height: base.largeDim[1]
});
};
// x,y coords -> George Washington in image demo
// base.setTarget( 82, 50, [200,200] );
// 'selector', [xOffset, yOffset], [zoomW, zoomH] -> Aug 26 in calendar demo
// base.setTarget( '.day[rel=2009-08-26]', [0, 0], [200, 200] );
base.setTarget = function(tar, sec, sz) {
var t, x = 0,
y = 0;
clearTimeout(base.timer);
if (!base.$zoom.hasClass(n.windowed)) {
base.showSmall();
}
// x, y coords
if (!isNaN(tar) && !isNaN(sec)) {
x = parseInt(tar, 10);
y = parseInt(sec, 10);
} else if (typeof(tar) === 'string' && $(tar).length) {
// '.selector', [xOffSet, yOffSet]
t = $(tar);
x = t.position().left + t.width() / 2 + (sec ? sec[0] || 0 : 0);
y = t.position().top + t.height() / 2 + (sec ? sec[1] || 0 : 0);
}
base.zoomAt(x, y, sz);
// add overlay
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
// hovered, but not really
base.$smInner.addClass(n.hovered);
// zoom window triggered
base.$wrap.trigger('zoom', base);
};
// x, y, [zoomX, zoomY] - zoomX, zoomY are the dimensions of the zoom window
base.zoomAt = function(x, y, sz, internal) {
var sx = (sz ? sz[0] || 0 : 0) || base.last[0],
sy = (sz ? sz[1] || sz[0] || 0 : 0) || base.last[1],
sx2 = sx / 2,
sy2 = sy / 2,
ex = o.edge || (o.edge === 0 ? 0 : sx2 * 0.66), // 2/3 of zoom window
ey = o.edge || (o.edge === 0 ? 0 : sy2 * 0.66), // allows edge to be zero
m = parseInt(base.$inner.css('margin-left'), 10) || base.$inner.position().left || 0;
// save new zoom size
base.last = [sx, sy];
// save x, y for external access
base.current = [x, y];
// show coordinates
if (o.edit) {
base.edit.html(Math.round(x) + ', ' + Math.round(y));
}
if ((x < -ex) || (x > base.smallDim[0] + ex) || (y < -ey) || (y > base.smallDim[1] + ey)) {
base.hideZoom(internal);
return;
} else {
// Sometimes the mouseenter event is delayed
base.$zoom.stop(true, true).fadeIn(o.speed);
}
// center zoom under the cursor
base.$zoom.css({
left: x - sx2 + m,
top: y - sy2,
width: sx,
height: sy
});
// match locations of small element to the large
base.$large.css({
left: -(x - o.offsetX - sx2 / 2) * base.ratio[0],
top: -(y - o.offsetY - sy2 / 2) * base.ratio[1]
});
};
base.hideZoom = function(internal) {
if (internal && base.$smInner.hasClass(n.hovered)) {
base.$wrap.trigger('unzoom', base);
}
base.last = base.zoomDim;
base.$zoom.stop(true, true).fadeOut(o.speed);
base.$overlay.removeClass(n.overlay);
base.$smInner.removeClass(n.hovered);
base.lastKey = null;
};
base.setEnabled = function(enable) {
base.enabled = enable;
if (enable) {
var off = base.$small.offset();
base.zoomAt(base.position.pageX - off.left, base.position.pageY - off.top, null, true);
} else {
base.showSmall();
base.hideZoom();
base.hovered = false;
}
};
// Initialize zoomer
base.init();
};
// class names used by anythingZoomer
$.anythingZoomer.classNames = {
namespace: '.anythingZoomer', // event namespace
wrap: 'az-wrap',
wrapInner: 'az-wrap-inner',
large: 'az-large',
largeInner: 'az-large-inner',
small: 'az-small',
smallInner: 'az-small-inner',
overlay: 'az-overlay', // toggled class name
overly: 'az-overly', // overlay unstyled class
hovered: 'az-hovered',
zoom: 'az-zoom',
windowed: 'az-windowed', // zoom window active
expanded: 'az-expanded', // zoom window inactive (large is showing)
edit: 'az-coords', // coordinate window
scrollzoom: 'az-scrollzoom'
};
$.anythingZoomer.defaultOptions = {
// content areas
smallArea: 'small', // class of small content area; the element with this class name must be inside of the wrapper
largeArea: 'large', // class of large content area; this class must exist inside of the wrapper. When the clone option is true, it will add this automatically
clone: false, // Make a clone of the small content area, use css to modify the style
// appearance
overlay: false, // set to true to apply overlay class "az-overlay"; false to not apply it
speed: 100, // fade animation speed (in milliseconds)
edge: 30, // How far outside the wrapped edges the mouse can go; previously called "expansionSize"
offsetX: 0, // adjust the horizontal position of the large content inside the zoom window as desired
offsetY: 0, // adjust the vertical position of the large content inside the zoom window as desired
// functionality
switchEvent: 'dblclick', // event that allows toggling between small and large elements - default is double click
delay: 0, // time to delay before revealing the zoom window.
// edit mode
edit: false // add x,y coordinates into zoom window to make it easier to find coordinates
};
$.fn.anythingZoomer = function(options, second, sx, sy) {
return this.each(function() {
var anyZoom = $(this).data('zoomer');
// initialize the zoomer but prevent multiple initializations
if (/object|undefined/.test(typeof options)) {
if (anyZoom) {
anyZoom.update();
} else {
(new $.anythingZoomer(this, options));
}
} else if (anyZoom && (typeof options === 'string' || (!isNaN(options) && !isNaN(second)))) {
if (/(en|dis)able/.test(options)) {
anyZoom.setEnabled(options === 'enable');
} else {
anyZoom.setTarget(options, second, sx, sy);
}
}
});
};
$.fn.getAnythingZoomer = function() {
return this.data('zoomer');
};
return $.anythingzoomer;
}));
/* AnythingZoomer */
.az-wrap,
.az-small,
.az-large {
position: relative;
}
.az-wrap-inner {
display: block;
margin: 0 auto;
/* center small & large content */
}
/* This wraps the large image and hides it */
.az-zoom {
background: #fff;
border: #333 1px solid;
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
overflow: hidden;
z-index: 100;
display: none;
-moz-box-shadow: inset 0px 0px 4px #000;
-webkit-box-shadow: inset 0px 0px 4px #000;
box-shadow: inset 0px 0px 4px #000;
}
/* Class applied to az-mover when large image is windowed */
.az-windowed {
overflow: hidden;
position: absolute;
}
/* Class applied to az-mover when large image is fully shown */
.az-expanded {
height: auto;
width: auto;
position: static;
overflow: visible;
}
/* overlay small area */
.az-overlay {
background-color: #000;
opacity: 0.3;
filter: alpha(opacity=30);
z-index: 10;
}
/* edit mode coordinate styling */
.az-coords {
display: none;
/* hidden when expanded */
}
.az-zoom .az-coords {
display: block;
position: absolute;
top: 0;
right: 0;
background: #000;
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
/* ZOOM CONTAINER */
.zoom {
display: block;
margin: 0 auto;
}
.large {
background: white;
}
/* FOR TEXT DEMO */
.small p {
font-size: 16px;
width: 700px
}
.large p {
font-size: 32px;
width: 1400px;
}
/* FOR IMAGE DEMO */
.small img {
width: 250px;
}
.large img {
width: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image and Text Magnifier</title>
<!-- anythingZoomer required -->
<link rel="stylesheet" href="css/anythingzoomer.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.anythingzoomer.js"></script>
<script>
$(function() {
// clone the text
$(".zoom").each(function(){
$(this).anythingZoomer({clone: true});
});
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom").each(function(){
$(this).anythingZoomer(state);
});
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
});
</script>
</head>
<body id="double">
<div id="main-content">
<p>Double click within the section to toggle between the large and small versions.</p>
<p><button>disable</button></p>
<p><strong>Text Demo </strong></p>
<div class="zoom">
<div class="small">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae
est. Mauris placerat eleifend leo.</p>
</div>
<!-- the clone option will automatically make a div.large if it doesn't exist -->
</div>
<br>
<p><strong>Image Demo
<div class="zoom second">
<div class="small">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="small rushmore">
</div>
<div class="large">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="big rushmore">
</div>
</div>
</div>
</body>
</html>
Didn't read the code but you could create the zoom using CSS
btn:hover element{
font-size:larger;
}

Dropdowns not working in Bootstrap navbar

Building a Bootstrap template for a responsive site. It needs to show a simple horizontal navbar on desktop and tablet, then go to offcanvas slide-in on phones. Found an example by Phil Hughes (iamphill) on Github. As I adapted this, the dropdown menu items stopped working. When I click on either of the two dropdowns nothing happens. No errors in Chrome Inspector. Validating HTML, CSS and JS does not reveal anything. The bug is either too obvious or too subtle.
! function(t) {
"use strict";
"function" == typeof define && define.amd ? define(["jquery"], t) : "object" == typeof exports ? module.exports = t(require("jquery")) : t(jQuery)
}(function(t) {
"use strict";
function e(e) {
var o = e.attr("data-target");
o || (o = e.attr("href"), o = o && /#[A-Za-z]/.test(o) && o.replace(/.*(?=#[^\s]*$)/, ""));
var n = o && t(o);
return n && n.length ? n : e.parent()
}
function o(o) {
o && 3 === o.which || (t(r).remove(), t(a).each(function() {
var n = t(this),
r = e(n),
a = {
relatedTarget: this
};
r.hasClass("open") && (o && "click" == o.type && /input|textarea/i.test(o.target.tagName) && t.contains(r[0], o.target) || (r.trigger(o = t.Event("hide.bs.dropdown", a)), o.isDefaultPrevented() || (n.attr("aria-expanded", "false"), r.removeClass("open").trigger(t.Event("hidden.bs.dropdown", a)))))
}))
}
function n(e) {
return this.each(function() {
var o = t(this),
n = o.data("bs.dropdown");
n || o.data("bs.dropdown", n = new i(this)), "string" == typeof e && n[e].call(o)
})
}
var r = ".dropdown-backdrop",
a = '[data-toggle="dropdown"]',
d = ".drawer-nav",
i = function(e) {
t(e).on("click.bs.dropdown", this.toggle)
};
i.VERSION = "3.3.5", i.prototype.toggle = function(n) {
var r = t(this);
if (!r.is(".disabled, :disabled")) {
var a = e(r),
i = a.hasClass("open");
if (o(), !i) {
"ontouchstart" in document.documentElement && !a.closest(d).length && t(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(t(this)).on("click", o);
var s = {
relatedTarget: this
};
if (a.trigger(n = t.Event("show.bs.dropdown", s)), n.isDefaultPrevented()) return;
r.trigger("focus").attr("aria-expanded", "true"), a.toggleClass("open").trigger(t.Event("shown.bs.dropdown", s))
}
return !1
}
}, i.prototype.keydown = function(o) {
if (/(38|40|27|32)/.test(o.which) && !/input|textarea/i.test(o.target.tagName)) {
var n = t(this);
if (o.preventDefault(), o.stopPropagation(), !n.is(".disabled, :disabled")) {
var r = e(n),
d = r.hasClass("open");
if (!d && 27 != o.which || d && 27 == o.which) return 27 == o.which && r.find(a).trigger("focus"), n.trigger("click");
var i = " li:not(.disabled):visible a",
s = r.find(".dropdown-menu" + i);
if (s.length) {
var p = s.index(o.target);
38 == o.which && p > 0 && p--, 40 == o.which && p < s.length - 1 && p++, ~p || (p = 0), s.eq(p).trigger("focus")
}
}
}
};
var s = t.fn.dropdown;
t.fn.dropdown = n, t.fn.dropdown.Constructor = i, t.fn.dropdown.noConflict = function() {
return t.fn.dropdown = s, this
}, t(document).on("click.bs.dropdown.data-api", o).on("click.bs.dropdown.data-api", ".dropdown form", function(t) {
t.stopPropagation()
}).on("click.bs.dropdown.data-api", a, i.prototype.toggle).on("keydown.bs.dropdown.data-api", a, i.prototype.keydown).on("keydown.bs.dropdown.data-api", ".dropdown-menu", i.prototype.keydown)
});
// and now js for offcanvas
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
(function($, window) {
var Offcanvas, OffcanvasDropdown, OffcanvasTouch, transformCheck;
OffcanvasDropdown = (function() {
function OffcanvasDropdown(element) {
this.element = element;
this._clickEvent = bind(this._clickEvent, this);
this.element = $(this.element);
this.nav = this.element.closest(".nav");
this.dropdown = this.element.parent().find(".dropdown-menu");
this.element.on('click', this._clickEvent);
this.nav.closest('.navbar-offcanvas').on('click', (function(_this) {
return function() {
if (_this.dropdown.is('.shown')) {
return _this.dropdown.removeClass('shown').closest('.active').removeClass('active');
}
};
})(this));
}
OffcanvasDropdown.prototype._clickEvent = function(e) {
if (!this.dropdown.hasClass('shown')) {
e.preventDefault();
}
e.stopPropagation();
$('.dropdown-toggle').not(this.element).closest('.active').removeClass('active').find('.dropdown-menu').removeClass('shown');
this.dropdown.toggleClass("shown");
return this.element.parent().toggleClass('active');
};
return OffcanvasDropdown;
})();
OffcanvasTouch = (function() {
function OffcanvasTouch(button, element, location, offcanvas) {
this.button = button;
this.element = element;
this.location = location;
this.offcanvas = offcanvas;
this._getFade = bind(this._getFade, this);
this._getCss = bind(this._getCss, this);
this._touchEnd = bind(this._touchEnd, this);
this._touchMove = bind(this._touchMove, this);
this._touchStart = bind(this._touchStart, this);
this.endThreshold = 130;
this.startThreshold = this.element.hasClass('navbar-offcanvas-right') ? $("body").outerWidth() - 60 : 20;
this.maxStartThreshold = this.element.hasClass('navbar-offcanvas-right') ? $("body").outerWidth() - 20 : 60;
this.currentX = 0;
this.fade = this.element.hasClass('navbar-offcanvas-fade') ? true : false;
$(document).on("touchstart", this._touchStart);
$(document).on("touchmove", this._touchMove);
$(document).on("touchend", this._touchEnd);
}
OffcanvasTouch.prototype._touchStart = function(e) {
this.startX = e.originalEvent.touches[0].pageX;
if (this.element.is('.in')) {
return this.element.height($(window).outerHeight());
}
};
OffcanvasTouch.prototype._touchMove = function(e) {
var x;
if ($(e.target).parents('.navbar-offcanvas').length > 0) {
return true;
}
if (this.startX > this.startThreshold && this.startX < this.maxStartThreshold) {
e.preventDefault();
x = e.originalEvent.touches[0].pageX - this.startX;
x = this.element.hasClass('navbar-offcanvas-right') ? -x : x;
if (Math.abs(x) < this.element.outerWidth()) {
this.element.css(this._getCss(x));
return this.element.css(this._getFade(x));
}
} else if (this.element.hasClass('in')) {
e.preventDefault();
x = e.originalEvent.touches[0].pageX + (this.currentX - this.startX);
x = this.element.hasClass('navbar-offcanvas-right') ? -x : x;
if (Math.abs(x) < this.element.outerWidth()) {
this.element.css(this._getCss(x));
return this.element.css(this._getFade(x));
}
}
};
OffcanvasTouch.prototype._touchEnd = function(e) {
var end, sendEvents, x;
if ($(e.target).parents('.navbar-offcanvas').length > 0) {
return true;
}
sendEvents = false;
x = e.originalEvent.changedTouches[0].pageX;
if (Math.abs(x) === this.startX) {
return;
}
end = this.element.hasClass('navbar-offcanvas-right') ? Math.abs(x) > (this.endThreshold + 50) : x < (this.endThreshold + 50);
if (this.element.hasClass('in') && end) {
this.currentX = 0;
this.element.removeClass('in').css(this._clearCss());
this.button.removeClass('is-open');
sendEvents = true;
} else if (Math.abs(x - this.startX) > this.endThreshold && this.startX > this.startThreshold && this.startX < this.maxStartThreshold) {
this.currentX = this.element.hasClass('navbar-offcanvas-right') ? -this.element.outerWidth() : this.element.outerWidth();
this.element.toggleClass('in').css(this._clearCss());
this.button.toggleClass('is-open');
sendEvents = true;
} else {
this.element.css(this._clearCss());
}
return this.offcanvas.bodyOverflow(sendEvents);
};
OffcanvasTouch.prototype._getCss = function(x) {
x = this.element.hasClass('navbar-offcanvas-right') ? -x : x;
return {
"-webkit-transform": "translate3d(" + x + "px, 0px, 0px)",
"-webkit-transition-duration": "0s",
"-moz-transform": "translate3d(" + x + "px, 0px, 0px)",
"-moz-transition": "0s",
"-o-transform": "translate3d(" + x + "px, 0px, 0px)",
"-o-transition": "0s",
"transform": "translate3d(" + x + "px, 0px, 0px)",
"transition": "0s"
};
};
OffcanvasTouch.prototype._getFade = function(x) {
if (this.fade) {
return {
"opacity": x / this.element.outerWidth()
};
} else {
return {};
}
};
OffcanvasTouch.prototype._clearCss = function() {
return {
"-webkit-transform": "",
"-webkit-transition-duration": "",
"-moz-transform": "",
"-moz-transition": "",
"-o-transform": "",
"-o-transition": "",
"transform": "",
"transition": "",
"opacity": ""
};
};
return OffcanvasTouch;
})();
window.Offcanvas = Offcanvas = (function() {
function Offcanvas(element) {
var t, target;
this.element = element;
this.bodyOverflow = bind(this.bodyOverflow, this);
this._sendEventsAfter = bind(this._sendEventsAfter, this);
this._sendEventsBefore = bind(this._sendEventsBefore, this);
this._documentClicked = bind(this._documentClicked, this);
this._close = bind(this._close, this);
this._open = bind(this._open, this);
this._clicked = bind(this._clicked, this);
this._navbarHeight = bind(this._navbarHeight, this);
target = this.element.attr('data-target') ? this.element.attr('data-target') : false;
if (target) {
this.target = $(target);
if (this.target.length && !this.target.hasClass('js-offcanvas-done')) {
this.element.addClass('js-offcanvas-has-events');
this.location = this.target.hasClass("navbar-offcanvas-right") ? "right" : "left";
this.target.addClass(transform ? "offcanvas-transform js-offcanvas-done" : "offcanvas-position js-offcanvas-done");
this.target.data('offcanvas', this);
this.element.on("click", this._clicked);
this.target.on('transitionend', (function(_this) {
return function() {
if (_this.target.is(':not(.in)')) {
return _this.target.height('');
}
};
})(this));
$(document).on("click", this._documentClicked);
if (this.target.hasClass('navbar-offcanvas-touch')) {
t = new OffcanvasTouch(this.element, this.target, this.location, this);
}
this.target.find(".dropdown-toggle").each(function() {
var d;
return d = new OffcanvasDropdown(this);
});
this.target.on('offcanvas.toggle', (function(_this) {
return function(e) {
return _this._clicked(e);
};
})(this));
this.target.on('offcanvas.close', (function(_this) {
return function(e) {
return _this._close(e);
};
})(this));
this.target.on('offcanvas.open', (function(_this) {
return function(e) {
return _this._open(e);
};
})(this));
}
} else {
console.warn('Offcanvas: `data-target` attribute must be present.');
}
}
Offcanvas.prototype._navbarHeight = function() {
if (this.target.is('.in')) {
return this.target.height($(window).outerHeight());
}
};
Offcanvas.prototype._clicked = function(e) {
e.preventDefault();
this._sendEventsBefore();
$(".navbar-offcanvas").not(this.target).trigger('offcanvas.close');
this.target.toggleClass('in');
this.element.toggleClass('is-open');
this._navbarHeight();
return this.bodyOverflow();
};
Offcanvas.prototype._open = function(e) {
e.preventDefault();
if (this.target.is('.in')) {
return;
}
this._sendEventsBefore();
this.target.addClass('in');
this.element.addClass('is-open');
this._navbarHeight();
return this.bodyOverflow();
};
Offcanvas.prototype._close = function(e) {
e.preventDefault();
if (this.target.is(':not(.in)')) {
return;
}
this._sendEventsBefore();
this.target.removeClass('in');
this.element.removeClass('is-open');
this._navbarHeight();
return this.bodyOverflow();
};
Offcanvas.prototype._documentClicked = function(e) {
var clickedEl;
clickedEl = $(e.target);
if (!clickedEl.hasClass('offcanvas-toggle') && clickedEl.parents('.offcanvas-toggle').length === 0 && clickedEl.parents('.navbar-offcanvas').length === 0 && !clickedEl.hasClass('navbar-offcanvas')) {
if (this.target.hasClass('in')) {
e.preventDefault();
this._sendEventsBefore();
this.target.removeClass('in');
this.element.removeClass('is-open');
this._navbarHeight();
return this.bodyOverflow();
}
}
};
Offcanvas.prototype._sendEventsBefore = function() {
if (this.target.hasClass('in')) {
return this.target.trigger('hide.bs.offcanvas');
} else {
return this.target.trigger('show.bs.offcanvas');
}
};
Offcanvas.prototype._sendEventsAfter = function() {
if (this.target.hasClass('in')) {
return this.target.trigger('shown.bs.offcanvas');
} else {
return this.target.trigger('hidden.bs.offcanvas');
}
};
Offcanvas.prototype.bodyOverflow = function(events) {
if (events === null) {
events = true;
}
if (this.target.is('.in')) {
$('body').addClass('offcanvas-stop-scrolling');
} else {
$('body').removeClass('offcanvas-stop-scrolling');
}
if (events) {
return this._sendEventsAfter();
}
};
return Offcanvas;
})();
transformCheck = (function(_this) {
return function() {
var asSupport, el, regex, translate3D;
el = document.createElement('div');
translate3D = "translate3d(0px, 0px, 0px)";
regex = /translate3d\(0px, 0px, 0px\)/g;
el.style.cssText = "-webkit-transform: " + translate3D + "; -moz-transform: " + translate3D + "; -o-transform: " + translate3D + "; transform: " + translate3D;
asSupport = el.style.cssText.match(regex);
return _this.transform = asSupport.length !== null;
};
})(this);
return $(function() {
transformCheck();
$('[data-toggle="offcanvas"]').each(function() {
var oc;
return oc = new Offcanvas($(this));
});
$(window).on('resize', function() {
$('.navbar-offcanvas.in').each(function() {
return $(this).height('').removeClass('in');
});
return $('.offcanvas-toggle').removeClass('is-open');
});
return $('.offcanvas-toggle').each(function() {
return $(this).on('click', function(e) {
var el, selector;
if (!$(this).hasClass('js-offcanvas-has-events')) {
selector = $(this).attr('data-target');
el = $(selector);
if (el) {
el.height('');
el.removeClass('in');
return $('body').css({
overflow: '',
position: ''
});
}
}
});
});
});
})(window.jQuery, window);
}).call(this);
/* CSS used here will be applied after bootstrap.css */
#media (max-width: 767px) {
.offcanvas-stop-scrolling {
height: 100%;
overflow: hidden; }
.navbar-default .navbar-offcanvas {
background-color: #f8f8f8; }
.navbar-inverse .navbar-offcanvas {
background-color: #222; }
.navbar-offcanvas {
position: fixed;
width: 100%;
max-width: 250px;
left: -250px;
top: 0;
padding-left: 15px;
padding-right: 15px;
z-index: 999;
overflow: scroll;
-webkit-overflow-scrolling: touch;
-webkit-transition: all 0.15s ease-in;
transition: all 0.15s ease-in; }
.navbar-offcanvas.in {
box-shadow: 0 0 20px rgba(0, 0, 0, 0.3); }
.navbar-offcanvas.navbar-offcanvas-fade {
opacity: 0; }
.navbar-offcanvas.navbar-offcanvas-fade.in {
opacity: 1; }
.navbar-offcanvas.offcanvas-transform.in {
-webkit-transform: translateX(250px);
transform: translateX(250px); }
.navbar-offcanvas.offcanvas-position.in {
left: 0; }
.navbar-offcanvas.navbar-offcanvas-right {
left: auto;
right: -250px; }
.navbar-offcanvas.navbar-offcanvas-right.offcanvas-transform.in {
-webkit-transform: translateX(-250px);
transform: translateX(-250px); }
.navbar-offcanvas.navbar-offcanvas-right.offcanvas-position.in {
left: auto;
right: 0; }
.navbar-offcanvas .dropdown.active .caret {
border-top: 0;
border-bottom: 4px solid; }
.navbar-offcanvas .dropdown-menu {
position: relative;
width: 100%;
border: inherit;
box-shadow: none;
-webkit-transition: height 0.15s ease-in;
transition: height 0.15s ease-in; }
.navbar-offcanvas .dropdown-menu.shown {
display: block;
margin-bottom: 10px; } }
.offcanvas-toggle .icon-bar {
background: #000;
-webkit-transition: all .25s ease-in-out;
transition: all .25s ease-in-out; }
.offcanvas-toggle.is-open .icon-bar:nth-child(1) {
-webkit-transform: rotate(45deg) translate(5px, 4px);
transform: rotate(45deg) translate(5px, 4px); }
.offcanvas-toggle.is-open .icon-bar:nth-child(2) {
opacity: 0; }
.offcanvas-toggle.is-open .icon-bar:nth-child(3) {
-webkit-transform: rotate(-45deg) translate(4px, -4px);
transform: rotate(-45deg) translate(4px, -4px); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<body class="body-offcanvas">
<header class="clearfix">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle offcanvas-toggle" data-toggle="offcanvas" data-target="#js-bootstrap-offcanvas">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brandhere</a>
</div>
<div class="navbar-offcanvas navbar-offcanvas-touch" id="js-bootstrap-offcanvas">
<ul class="nav navbar-nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">NUMBERS<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>One</li>
<li>Two</li>
<li>Thirty-six</li>
<li>-7</li>
<li>Eighteen</li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">MUSIC<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>BJ Cole</li>
<li>C. Debussy</li>
<li>Brian Eno</li>
<li>Robert Fripp</li>
<li>Skip James</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<div class="row">
<div>
<h1>Page Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin feugiat hendrerit feugiat. In cursus nisl id arcu ullamcorper, eget euismod ante tincidunt. Aliquam tincidunt felis eget quam euismod cursus. Nam aliquet a tellus ut pretium. Pellentesque fermentum nulla tempus mauris sagittis, eget imperdiet quam tristique. Pellentesque quis mauris mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sodales turpis fringilla ligula rutrum, eget mattis justo bibendum. Integer imperdiet mi non cursus bibendum. Nullam vitae cursus justo. Integer quis elit sit amet arcu pellentesque sit amet a sapien. Aliquam tincidunt felis eget quam euismod cursus. Suspendisse lobortis ut elit vitae rhoncus. Ut tincidunt, ante eu egestas sodales, dui nulla aliquet mi, a eleifend lacus risus sit amet lacus.</p>
</div>
</div>
</div>
</body>
Here it is on Bootply http://www.bootply.com/ONyk2E5GWv
There are 2 things here:
1) You're using same class for dropdown-toggle for both Numbers as well as Music. Try to keep it unique like below -
<li class="dropdown numbers">
<a class="dropdown-toggle" data-toggle="numbers" href="#">NUMBERS<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>One</li>
</ul>
</li>
<li class="dropdown music">
<a class="dropdown-toggle" data-toggle="music" href="#">MUSIC<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>BJ Cole</li>
</ul>
</li>
2) You're using CSS Media Query max-width: 767px which means that this styling is applied only for screens whose width are less than 767 pixels, ideally Tablets and Mobile devices. Upon click of dropdown, on the dropdown-menu, 'shown' class is being added which will have the styling of displaying the list by changing the CSS attribute display from 'none' to 'block'
.navbar-offcanvas .dropdown-menu.shown {
display: block;
margin-bottom: 10px;
}

Prevent bubbles in carousel with native javascript

How can I stop this carousel from bubbling the animation? If you click right faster, it will start to mix up things. I need to stop the event handler function if the animation is running, inside that timeOut, the handlers should go offline.
Please see snippet below:
var Carousel = function(element, options) {
this.carousel = document.querySelector(element);
this.slides = Array.prototype.slice.call(this.carousel.querySelectorAll('.item'), null);
this.prev = this.carousel.querySelector("[data-slide='prev']");
this.next = this.carousel.querySelector("[data-slide='next']");
this.indicators = this.carousel.querySelectorAll(".carousel-indicators li");
this.interval = options && options.interval ? options.interval : 5000;
this.duration = 600; // bootstrap carousel default transition duration
this.paused = null;
this.direction = null;
this.index = 0;
this.total = this.slides.length;
this.init();
};
Carousel.prototype = {
init: function() {
this.cycle();
this.actions();
},
_slideTo: function(next, e) {
var self = this;
//determine type
var active = self._getActiveIndex(); // the current active
var direction = self.direction;
var type = direction === 'left' ? 'next' : 'prev';
if (!this.slides[next].classList.contains(type)) {
//e.preventDefault();
//e.defaultPrevented = false;
this.slides[next].classList.add(type);
this.slides[next].offsetWidth;
this.slides[active].classList.add(direction);
this.slides[next].classList.add(direction);
setTimeout(function() {
console.log('inside timeout prevented? ' + e.defaultPrevented);
self.slides[next].classList.remove(type, direction);
self.slides[next].classList.add('active');
self.slides[active].classList.remove('active', direction);
self._curentPage(self.indicators[next]);
//e.defaultPrevented = false;
}, self.duration + 200);
}
},
_getActiveIndex: function() {
return this._getItemIndex('.item.active')
},
_getItemIndex: function(itm) {
return this.slides.indexOf(this.carousel.querySelector(itm))
},
_curentPage: function(p) {
for (var i = 0; i < this.indicators.length; ++i) {
var a = this.indicators[i];
a.className = "";
}
p.className = "active";
},
cycle: function() {
var self = this;
//deleted some shit
},
actions: function() {
var self = this;
self.next.addEventListener("click", function(e) {
e.preventDefault();
self.index++;
self.direction = 'left'; //set direction first
if (self.index == self.total - 1) {
self.index = self.total - 1;
} else if (self.index == self.total) {
self.index = 0
}
self._slideTo(self.index, e);
}, false);
self.prev.addEventListener("click", function(e) {
e.preventDefault();
self.index--;
self.direction = 'right'; //set direction first
if (self.index == 0) {
self.index = 0;
} else if (self.index < 0) {
self.index = self.total - 1
}
self._slideTo(self.index, e);
}, false);
for (var i = 0; i < self.indicators.length; ++i) {
var a = self.indicators[i];
a.addEventListener("click", function(e) {
e.preventDefault();
var n = parseInt(this.getAttribute("data-slide-to"), 10);
self.index = n;
if (self.index == 0) {
self.index = 0;
}
if (self.index > 0) {}
if (self.index == self.total - 1) {
self.index = self.total - 1;
} else {}
//determine direction first
var active = self._getActiveIndex(); // the current active
if ((active < self.index) || (active === self.total - 1 && self.index === 0)) {
self.direction = 'left'; // next
} else if ((active > self.index) || (active === 0 && self.index === self.total - 1)) {
self.direction = 'right'; // prev
}
self._slideTo(self.index, e);
}, false);
}
window.addEventListener('keydown', function(e) {
if (/input|textarea/i.test(e.target.tagName)) return;
switch (e.which) {
case 39:
self.index++;
self.direction = 'left';
if (self.index == self.total - 1) {
self.index = self.total - 1;
} else
if (self.index == self.total) {
self.index = 0
}
break;
case 37:
self.index--;
self.direction = 'right';
if (self.index == 0) {
self.index = 0;
} else
if (self.index < 0) {
self.index = self.total - 1
}
break;
default:
return;
}
// e.preventDefault();
self._slideTo(self.index, e);
}, false)
}
}
var slider = new Carousel("#myCarousel1");
#myCarousel1 {
height: 300px;
max-width: 100%
}
.item {
height: 300px;
background: url(http://placehold.it/100x100/069/069.png) repeat center center;
background-size: cover
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<div id="myCarousel1" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel1" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel1" data-slide-to="1"></li>
<li data-target="#myCarousel1" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<div class="container">
<div class="carousel-caption">
<h1>Example headline.</h1>
<p>Note: If you're viewing this page via a <code>file://</code> URL, the "next" and "previous" Glyphicon buttons on the left and right might not load/display properly due to web browser security rules.</p>
<p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a>
</p>
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="carousel-caption">
<h1>Another example headline.</h1>
<p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a>
</p>
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="carousel-caption">
<h1>One more for good measure.</h1>
<p>Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<p><a class="btn btn-lg btn-primary" href="#" role="button">Browse gallery</a>
</p>
</div>
</div>
</div>
</div>
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="glyphicon glyphicon-chevron-right"></span>
</div>
Perhaps checking the time interval between the clicks and returning false from the function that slides the carousel can solve this problem:
var oldTs = 0;
element.removeEventListener("click", slideClickHandler);
function slideClickHandler(e) {
var ts = e.timeStamp;
if ((oldTs !== 0) && (ts - oldTs < 500)) return false; //If time between clicks is 500 miliseconds and its not the first click cancel slide
else {
oldTs = ts; //Update timestamp buffer
slide(); //Do the sliding stuff
}
}
element.addEventListener('click', slideClickHandler);
Edit: You should put this code in a function and refresh the click handler after every slide for it to work.

Categories

Resources