Adding translate class to mobile navigation - javascript

I am new to javascript and I don't quite know where I should be adding in my class that allows for the website to be translated.
I have a mobile nav that appears when the screen width is X small and in that nav I have numerous directional buttons that lead to other parts of the website, BUT two buttons (The english and Chinese translation buttons) don't work when being pressed.
I assume this is because I have not added the 'lang' class in my 'is-mobile' class but I am unaware of how to do this.
Here is my code
(function($) {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
$banner = $('#banner'),
settings = {
banner: {
// Indicators (= the clickable dots at the bottom).
indicators: true,
// Transition speed (in ms)
// For timing purposes only. It *must* match the transition speed of "#banner > article".
speed: 1500,
// Transition delay (in ms)
delay: 5000,
// Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
parallax: 0.25
}
};
/**
* Applies parallax scrolling to an element's background image.
* #return {jQuery} jQuery object.
*/
$.fn._parallax = (browser.name == 'ie' || browser.name == 'edge' || browser.mobile) ? function() {
return $(this)
} : function(intensity) {
var $window = $(window),
$this = $(this);
if (this.length == 0 || intensity === 0)
return $this;
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i])._parallax(intensity);
return $this;
}
if (!intensity)
intensity = 0.25;
$this.each(function() {
var $t = $(this),
on, off;
on = function() {
$t.css('background-position', 'center 100%, center 100%, center 0px');
$window
.on('scroll._parallax', function() {
var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);
$t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');
});
};
off = function() {
$t
.css('background-position', '');
$window
.off('scroll._parallax');
};
breakpoints.on('<=medium', off);
breakpoints.on('>medium', on);
});
$window
.off('load._parallax resize._parallax')
.on('load._parallax resize._parallax', function() {
$window.trigger('scroll');
});
return $(this);
};
/**
* #return {jQuery} jQuery object.
*/
$.fn._slider = function(options) {
var $window = $(window),
$this = $(this);
if (this.length == 0)
return $this;
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i])._slider(options);
return $this;
}
// Vars.
var current = 0,
pos = 0,
lastPos = 0,
slides = [],
indicators = [],
$indicators,
$slides = $this.children('article'),
intervalId,
isLocked = false,
i = 0;
// Turn off indicators if we only have one slide.
if ($slides.length == 1)
options.indicators = false;
// Functions.
$this._switchTo = function(x, stop) {
if (isLocked || pos == x)
return;
isLocked = true;
if (stop)
window.clearInterval(intervalId);
// Update positions.
lastPos = pos;
pos = x;
// Hide last slide.
slides[lastPos].removeClass('top');
if (options.indicators)
indicators[lastPos].removeClass('visible');
// Show new slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Finish hiding last slide after a short delay.
window.setTimeout(function() {
slides[lastPos].addClass('instant').removeClass('visible');
window.setTimeout(function() {
slides[lastPos].removeClass('instant');
isLocked = false;
}, 100);
}, options.speed);
};
// Indicators.
if (options.indicators)
$indicators = $('<ul class="indicators"></ul>').appendTo($this);
// Slides.
$slides
.each(function() {
var $slide = $(this),
$img = $slide.find('img');
// Slide.
$slide
.css('background-image', 'url("' + $img.attr('src') + '")')
.css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));
// Add to slides.
slides.push($slide);
// Indicators.
if (options.indicators) {
var $indicator_li = $('<li>' + i + '</li>').appendTo($indicators);
// Indicator.
$indicator_li
.data('index', i)
.on('click', function() {
$this._switchTo($(this).data('index'), true);
});
// Add to indicators.
indicators.push($indicator_li);
}
i++;
})
._parallax(options.parallax);
// Initial slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Bail if we only have a single slide.
if (slides.length == 1)
return;
// Main loop.
intervalId = window.setInterval(function() {
current++;
if (current >= slides.length)
current = 0;
$this._switchTo(current);
}, options.delay);
};
// Breakpoints.
breakpoints({
xlarge: ['1281px', '1680px'],
large: ['981px', '1280px'],
medium: ['737px', '980px'],
small: ['481px', '736px'],
xsmall: [null, '480px']
});
// Play initial animations on page load.
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-preload');
}, 100);
});
// Mobile?
if (browser.mobile)
$body.addClass('is-mobile', 'tr');
else {
breakpoints.on('>medium', function() {
$body.removeClass('is-mobile');
});
breakpoints.on('<=medium', function() {
$body.addClass('is-mobile');
});
}
// Dropdowns.
$('#nav > ul').dropotron({
alignment: 'center',
hideDelay: 400
});
// Header.
if ($banner.length > 0 &&
$header.hasClass('alt')) {
$window.on('resize', function() {
$window.trigger('scroll');
});
$banner.scrollex({
bottom: $header.outerHeight(),
terminate: function() {
$header.removeClass('alt');
},
enter: function() {
$header.addClass('alt');
},
leave: function() {
$header.removeClass('alt');
$header.addClass('reveal');
}
});
}
// Banner.
$banner._slider(settings.banner);
// Off-Canvas Navigation.
// Navigation Panel Toggle.
$('')
.appendTo($header);
// Navigation Panel.
$(
'<div id="navPanel">' +
'<nav>' +
$('#nav').navList() +
'</nav>' +
'' +
'</div>'
)
.appendTo($body)
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'right'
});
// onclick behavior
$('.lang').click('touchstart', function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i) {
$(this).text(aLangKeys[lang][$(this).attr('key')]);
});
});
document.getElementById('ch').onclick = function() {
var lang = $(this).attr('id'); // obtain language id
// translate all translatable elements
$('.tr').each(function(i) {
$(this).text(aLangKeys[lang][$(this).attr('key')]);
});
}
// preparing language file
var aLangKeys = new Array();
aLangKeys['en'] = new Array();
aLangKeys['ch'] = new Array();
aLangKeys['en']['home'] = 'Home';
aLangKeys['en']['about'] = 'About Us';
aLangKeys['en']['serv'] = 'Services';
aLangKeys['en']['sem'] = 'Search Engine Marketing';
aLangKeys['en']['webdev'] = 'Website Development';
aLangKeys['en']['app'] = 'Mobile App Development';
aLangKeys['en']['tbd'] = 'Technical Business Development';
aLangKeys['en']['ourteam'] = 'Our Team';
aLangKeys['en']['contactus'] = 'Contact Us';
aLangKeys['en']['submit'] = 'Send Message';
aLangKeys['en']['reset'] = 'Reset';
aLangKeys['ch']['home'] = '首页';
aLangKeys['ch']['about'] = '关于我们';
aLangKeys['ch']['serv'] = '服务';
aLangKeys['ch']['sem'] = '谷歌与雅虎推广';
aLangKeys['ch']['webdev'] = '品牌网站建设';
aLangKeys['ch']['app'] = 'APP 开发';
aLangKeys['ch']['tbd'] = '加拿大工商业与市场拓展';
aLangKeys['ch']['ourteam'] = '我们的团队';
aLangKeys['ch']['contactus'] = '联络我们';
aLangKeys['ch']['submit'] = '发留言';
aLangKeys['ch']['reset'] = '重新';
})(jQuery);
<!-- Header -->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<header id="header" class="alt">
<h1>
<img src="images/Artboard%201.png" alt="logo" class="logo">
</h1>
<nav id="nav">
<ul class="translate">
<li>Home</li>
<li>About Us</li>
<li>
Services
<ul>
<li>Search Engine Marketing</li>
<li>Website Development </li>
<li>App Development</li>
<li>Technical Business Development</li>
</ul>
</li>
<li>Our Team</li>
<li>English</li>
<li>中文</li>
<li>Contact Us</li>
</ul>
</nav>
</header>
<!-- begin snippet: js hide: false console: true babel: false -->
Here is the other part of JS code:
(function($) {
/**
* Generate an indented list of links from a nav. Meant for use with panel().
* #return {jQuery} jQuery object.
*/
$.fn.navList = function() {
var $this = $(this);
$a = $this.find('a'),
b = [];
$a.each(function() {
var $this = $(this),
indent = Math.max(0, $this.parents('li').length - 1),
href = $this.attr('href'),
target = $this.attr('target');
b.push(
'<a ' +
'class="link depth-' + indent + '"' +
((typeof target !== 'undefined' && target != '') ? ' target="' + target + '"' : '') +
((typeof href !== 'undefined' && href != '') ? ' href="' + href + '"' : '') +
'>' +
'<span class="indent-' + indent + '"></span>' +
$this.text() +
'</a>'
);
});
return b.join('');
};
/**
* Panel-ify an element.
* #param {object} userConfig User config.
* #return {jQuery} jQuery object.
*/
$.fn.panel = function(userConfig) {
// No elements?
if (this.length == 0)
return $this;
// Multiple elements?
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i]).panel(userConfig);
return $this;
}
// Vars.
var $this = $(this),
$body = $('body'),
$window = $(window),
id = $this.attr('id'),
config;
// Config.
config = $.extend({
// Delay.
delay: 0,
// Hide panel on link click.
hideOnClick: false,
// Hide panel on escape keypress.
hideOnEscape: false,
// Hide panel on swipe.
hideOnSwipe: false,
// Reset scroll position on hide.
resetScroll: false,
// Reset forms on hide.
resetForms: false,
// Side of viewport the panel will appear.
side: null,
// Target element for "class".
target: $this,
// Class to toggle.
visibleClass: 'visible'
}, userConfig);
// Expand "target" if it's not a jQuery object already.
if (typeof config.target != 'jQuery')
config.target = $(config.target);
// Panel.
// Methods.
$this._hide = function(event) {
// Already hidden? Bail.
if (!config.target.hasClass(config.visibleClass))
return;
// If an event was provided, cancel it.
if (event) {
event.preventDefault();
event.stopPropagation();
}
// Hide.
config.target.removeClass(config.visibleClass);
// Post-hide stuff.
window.setTimeout(function() {
// Reset scroll position.
if (config.resetScroll)
$this.scrollTop(0);
// Reset forms.
if (config.resetForms)
$this.find('form').each(function() {
this.reset();
});
}, config.delay);
};
// Vendor fixes.
$this
.css('-ms-overflow-style', '-ms-autohiding-scrollbar')
.css('-webkit-overflow-scrolling', 'touch');
// Hide on click.
if (config.hideOnClick) {
$this.find('a')
.css('-webkit-tap-highlight-color', 'rgba(0,0,0,0)');
$this
.on('click', 'a', function(event) {
var $a = $(this),
href = $a.attr('href'),
target = $a.attr('target');
if (!href || href == '#' || href == '' || href == '#' + id)
return;
// Cancel original event.
event.preventDefault();
event.stopPropagation();
// Hide panel.
$this._hide();
// Redirect to href.
window.setTimeout(function() {
if (target == '_blank')
window.open(href);
else
window.location.href = href;
}, config.delay + 10);
});
}
// Event: Touch stuff.
$this.on('touchstart', function(event) {
$this.touchPosX = event.originalEvent.touches[0].pageX;
$this.touchPosY = event.originalEvent.touches[0].pageY;
})
$this.on('touchmove', function(event) {
if ($this.touchPosX === null ||
$this.touchPosY === null)
return;
var diffX = $this.touchPosX - event.originalEvent.touches[0].pageX,
diffY = $this.touchPosY - event.originalEvent.touches[0].pageY,
th = $this.outerHeight(),
ts = ($this.get(0).scrollHeight - $this.scrollTop());
// Hide on swipe?
if (config.hideOnSwipe) {
var result = false,
boundary = 20,
delta = 50;
switch (config.side) {
case 'left':
result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX > delta);
break;
case 'right':
result = (diffY < boundary && diffY > (-1 * boundary)) && (diffX < (-1 * delta));
break;
case 'top':
result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY > delta);
break;
case 'bottom':
result = (diffX < boundary && diffX > (-1 * boundary)) && (diffY < (-1 * delta));
break;
default:
break;
}
if (result) {
$this.touchPosX = null;
$this.touchPosY = null;
$this._hide();
return false;
}
}
// Prevent vertical scrolling past the top or bottom.
if (($this.scrollTop() < 0 && diffY < 0) ||
(ts > (th - 2) && ts < (th + 2) && diffY > 0)) {
event.preventDefault();
event.stopPropagation();
}
});
// Event: Prevent certain events inside the panel from bubbling.
$this.on('click touchend touchstart touchmove', function(event) {
event.stopPropagation();
});
// Event: Hide panel if a child anchor tag pointing to its ID is clicked.
$this.on('click', 'a[href="#' + id + '"]', function(event) {
event.preventDefault();
event.stopPropagation();
config.target.removeClass(config.visibleClass);
});
// Body.
// Event: Hide panel on body click/tap.
$body.on('click touchend', function(event) {
$this._hide(event);
});
// Event: Toggle.
$body.on('click', 'a[href="#' + id + '"]', function(event) {
event.preventDefault();
event.stopPropagation();
config.target.toggleClass(config.visibleClass);
});
// Window.
// Event: Hide on ESC.
if (config.hideOnEscape)
$window.on('keydown', function(event) {
if (event.keyCode == 27)
$this._hide(event);
});
return $this;
};
/**
* Apply "placeholder" attribute polyfill to one or more forms.
* #return {jQuery} jQuery object.
*/
$.fn.placeholder = function() {
// Browser natively supports placeholders? Bail.
if (typeof(document.createElement('input')).placeholder != 'undefined')
return $(this);
// No elements?
if (this.length == 0)
return $this;
// Multiple elements?
if (this.length > 1) {
for (var i = 0; i < this.length; i++)
$(this[i]).placeholder();
return $this;
}
// Vars.
var $this = $(this);
// Text, TextArea.
$this.find('input[type=text],textarea')
.each(function() {
var i = $(this);
if (i.val() == '' ||
i.val() == i.attr('placeholder'))
i
.addClass('polyfill-placeholder')
.val(i.attr('placeholder'));
})
.on('blur', function() {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
return;
if (i.val() == '')
i
.addClass('polyfill-placeholder')
.val(i.attr('placeholder'));
})
.on('focus', function() {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
return;
if (i.val() == i.attr('placeholder'))
i
.removeClass('polyfill-placeholder')
.val('');
});
// Password.
$this.find('input[type=password]')
.each(function() {
var i = $(this);
var x = $(
$('<div>')
.append(i.clone())
.remove()
.html()
.replace(/type="password"/i, 'type="text"')
.replace(/type=password/i, 'type=text')
);
if (i.attr('id') != '')
x.attr('id', i.attr('id') + '-polyfill-field');
if (i.attr('name') != '')
x.attr('name', i.attr('name') + '-polyfill-field');
x.addClass('polyfill-placeholder')
.val(x.attr('placeholder')).insertAfter(i);
if (i.val() == '')
i.hide();
else
x.hide();
i
.on('blur', function(event) {
event.preventDefault();
var x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
if (i.val() == '') {
i.hide();
x.show();
}
});
x
.on('focus', function(event) {
event.preventDefault();
var i = x.parent().find('input[name=' + x.attr('name').replace('-polyfill-field', '') + ']');
x.hide();
i
.show()
.focus();
})
.on('keypress', function(event) {
event.preventDefault();
x.val('');
});
});
// Events.
$this
.on('submit', function() {
$this.find('input[type=text],input[type=password],textarea')
.each(function(event) {
var i = $(this);
if (i.attr('name').match(/-polyfill-field$/))
i.attr('name', '');
if (i.val() == i.attr('placeholder')) {
i.removeClass('polyfill-placeholder');
i.val('');
}
});
})
.on('reset', function(event) {
event.preventDefault();
$this.find('select')
.val($('option:first').val());
$this.find('input,textarea')
.each(function() {
var i = $(this),
x;
i.removeClass('polyfill-placeholder');
switch (this.type) {
case 'submit':
case 'reset':
break;
case 'password':
i.val(i.attr('defaultValue'));
x = i.parent().find('input[name=' + i.attr('name') + '-polyfill-field]');
if (i.val() == '') {
i.hide();
x.show();
} else {
i.show();
x.hide();
}
break;
case 'checkbox':
case 'radio':
i.attr('checked', i.attr('defaultValue'));
break;
case 'text':
case 'textarea':
i.val(i.attr('defaultValue'));
if (i.val() == '') {
i.addClass('polyfill-placeholder');
i.val(i.attr('placeholder'));
}
break;
default:
i.val(i.attr('defaultValue'));
break;
}
});
});
return $this;
};
/**
* Moves elements to/from the first positions of their respective parents.
* #param {jQuery} $elements Elements (or selector) to move.
* #param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
*/
$.prioritize = function($elements, condition) {
var key = '__prioritize';
// Expand $elements if it's not already a jQuery object.
if (typeof $elements != 'jQuery')
$elements = $($elements);
// Step through elements.
$elements.each(function() {
var $e = $(this),
$p,
$parent = $e.parent();
// No parent? Bail.
if ($parent.length == 0)
return;
// Not moved? Move it.
if (!$e.data(key)) {
// Condition is false? Bail.
if (!condition)
return;
// Get placeholder (which will serve as our point of reference for when this element needs to move back).
$p = $e.prev();
// Couldn't find anything? Means this element's already at the top, so bail.
if ($p.length == 0)
return;
// Move element to top of parent.
$e.prependTo($parent);
// Mark element as moved.
$e.data(key, $p);
}
// Moved already?
else {
// Condition is true? Bail.
if (condition)
return;
$p = $e.data(key);
// Move element back to its original location (using our placeholder).
$e.insertAfter($p);
// Unmark element as moved.
$e.removeData(key);
}
});
};
})(jQuery);
Here is the code snippet of my dropotron jquery file I have been using for the menu drop down if needed.
Where would I go to insert my lang class so that when it is in mobile nav the class is recognized? Thank you!

I figured it out!
I needed to add the class 'tr' into:
'class="tr link depth-' + indent + '"' +
Just forgot that little thing...

Related

jQuery click mobile problems (slider)

I have coded a small script for scrolling in a vertical gallery on mobile devices – in browser everything works fine, but I can't make it work on my smartphone. What am I doing wrong?
Thats my query:
jQuery( '.single-cinema-cat .next' ).on('click touchstart', function () {
alert("The btn was clicked.");
if( jQuery( this ).hasClass( 'disabled' ) )
return;
jQuery( this ).addClass( 'disabled' );
var $el = jQuery( this );
if( jQuery( window ).innerWidth() >= 970 )
scrollVertical_next( $el );
else
scrollHorizontal_next( $el );
});
the click element is a span-element in my html markup – could this be a problem? screenshot of my markup: https://picload.org/image/ralwaarg/jquerymobile.png
please save me for further headaches :-)
scrollVertical_next
function scrollVertical_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 4 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
scrollHorizontal_next
function scrollHorizontal_next($el) {
var $wrapper = $el.closest('.single-cinema-cat').find('.inner');
var margin = parseInt($wrapper.find('article').css('margin-bottom')) + parseInt($wrapper.find('article').css('margin-top'));
var current_height = parseInt($wrapper.find('ul').css('top'));
var single_height = $wrapper.find('article').outerHeight() + margin;
var target_height = current_height - single_height;
var total_height = $wrapper.find('ul').innerHeight();
var stopper_height = -1 * total_height + 1 * single_height;
if (target_height < stopper_height)
return;
$wrapper.find('ul').animate({
'top': target_height + 'px'
}, 250, 'swing', function() {
if (target_height > stopper_height)
$el.removeClass('disabled');
$el.closest('.single-cinema-cat').find('.prev').removeClass('disabled');
});
}
Touch event must be handled this way
jQuery('.single-cinema-cat .next').on('click touchstart', function (event) {
event.stopPropagation();
event.preventDefault();
if (event.handled !== true) {
////////// your stuff //////////////////////////
alert("The btn was clicked.");
if (jQuery(this).hasClass('disabled'))
return;
jQuery(this).addClass('disabled');
var $el = jQuery(this);
if (jQuery(window).innerWidth() >= 970)
scrollVertical_next($el);
else
scrollHorizontal_next($el);
////////////////////////////////////////////////////
event.handled = true;
} else {
return false;
}
});

Userscript works in Tampermonkey on Chrome but not in Greasemonkey on Firefox

I have been using a userscript in Greasemonkey on Firefox and Tampermonkey on Chrome for over a year and a half now. It adds a scroll to top button on every webpage. I tried adding another site to include in Greasemonkey but then it seemed to have broken it. Now, the scroll to top button doesn't show up on any site in Firefox but the exact same userscript has no issues working in Chrome on Tampermonkey. I did not create this script. I got it from Userscripts.org back before it went down. Below is the script. Does anyone know what might need to be changed in the script to make it compatible with Greasemonkey again?
I'm using Firefox 41.0 for xUbuntu and Greasemonkey 3.4.1.
My Chrome is 45.0.2454.101 and Tampermonkey 3.11.
// ==UserScript==
// #name Scroll To Top Button
// #version v1.3.2
// #include http://*
// #include https://*
// ==/UserScript==
(function(global) {
if(global !== window) return;
function _(id) {
return document.getElementById(id);
}
function bind(context, name) {
return function() {
return context[name].apply(context, arguments);
}
}
global.addEventListener('scroll', scrollHandler, false);
function scrollHandler() {
!scroll.isScrolling && ((scroll.getScrollY() > 0) ? scroll.showBtn() : scroll.hideBtn());
}
var scroll = {
__scrollY : 0,
isScrolling : false, //is scrolling
imgBtn : null,
isBtnShow : false,
pageHeight : 0,
speed : 0.75,
init : function() {
var document = global.document,
div = document.createElement('div'),
css;
css = '#__scrollToTop{font:12px/1em Arial,Helvetica,sans-serif;margin:0;padding:0;position:fixed;display:none;left:92%;top:80%;text-align:center;z-index:999999; width:74px;height:50px;' +
'cursor:pointer;opacity:0.5;padding:2px;}' +
'#__scrollToTop:hover{opacity:1;}' +
'#__scrollToTop span.__scroll__arrow{ position:relative;top:20px;background:none repeat scroll 0 0 #eee;border-style:solid; border-width:1px;' +
'border-color:#ccc #ccc #aaa; border-radius:5px;color:#333;font-size:36px;padding:5px 8px 2px;}' +
' #__scroll__scroll{height:50px;width:50px;float:left;z-index:100001;position:absolute;} ' +
'#__scroll__util{font:12px/1em Arial,Helvetica,sans-serif;text-align:center;height:44px;width:20px;float:right;position:absolute;left:54px;z-index:100000; ' +
'border-style:solid; border-width:1px;border-color:#ccc #ccc #aaa; border-radius:2px;top:5px;display:none;}' +
'#__scroll__util span{display:block;height:18px;padding-top:4px;text-align:center;text-shadow:2px 2px 2px #888;font-size:16px;} ' +
'#__scroll__util span:hover{background-color: #fc9822;}';
GM_addStyle(css);
div.id = '__scrollToTop';
div.title = 'Back To Top';
div.innerHTML = '<div id="__scroll__scroll">' +
'<span class="__scroll__arrow">▲</span>' +
'</div>' +
'<div id="__scroll__util">' +
'<span name="__hide" title="Hide the Button">x</span>' +
'<span name="__bottom" title="Scroll to the bottom">▼</span>' +
'</div>';
document.body.appendChild(div);
div.addEventListener('mousedown', bind(this, 'control'),false);
div.addEventListener('mouseover', bind(this, 'showUtil'),false);
div.addEventListener('mouseout', bind(this, 'hideUtil'),false);
this.util = _('__scroll__util');
this.pageUtil = _('__scroll__page');
this.pageHeight = document.body.scrollHeight;
return this.imgBtn = div;
},
getImgBtn : function() {
return this.imgBtn || this.init();
},
show : function(elem) {
elem.style.display = 'block';
},
hide : function(elem) {
elem.style.display = 'none';
},
showBtn : function() {
if(this.isBtnShow) return;
this.isBtnShow = true;
this.show(this.getImgBtn());
},
hideBtn : function() {
if(!this.isBtnShow) return;
this.isBtnShow = false;
this.hide(this.getImgBtn());
},
getScrollY : function() {
//this piece of code is from John Resig's book 'Pro JavaScript Techniques'
var de = document.documentElement;
return this.__scrollY = (self.pageYOffset ||
( de && de.scrollTop ) ||
document.body.scrollTop);
},
closeBtn : function(event) {
event.preventDefault();
event.stopPropagation();
this.hideBtn();
window.removeEventListener('scroll', scrollHandler, false);
},
showUtil : function() {
this.show(this.util);
},
hideUtil : function() {
this.hide(this.util);
},
scroll : function() {
if(!this.isScrolling) {
this.isScrolling = true;
}
var isStop = false,
scrollY = this.__scrollY;
if(this.direction === 'top') {
isStop = scrollY > 0;
this.__scrollY = Math.floor(scrollY * this.speed);
} else {
isStop = scrollY < this.pageHeight;
this.__scrollY += Math.ceil((this.pageHeight - scrollY) * (1 - this.speed)) + 10;
}
this.isScrolling = isStop;
window.scrollTo(0, this.__scrollY);
isStop ? setTimeout(bind(scroll, 'scroll'), 20) : (this.direction === 'top' && this.hideBtn());
},
control : function(e) {
var t = e.target, name = t.getAttribute('name');
switch(name) {
case '__bottom':
this.scrollToBottom();
break;
case '__hide' :
this.closeBtn(e);
break;
default :
this.scrollToTop();
break;
}
},
scrollToTop : function() {
this.direction = 'top';
this.scroll();
},
scrollToBottom : function() {
this.direction = 'bottom';
var bodyHeight = global.document.body.scrollHeight,
documentElementHeight = global.document.documentElement.scrollHeight;
this.pageHeight = Math.max(bodyHeight, documentElementHeight);
this.scroll();
}
};
//Autoscroll
(function() {
var isAutoScroll = false;
var autoScroll = {
__autoScrollID : 0,
isAutoScroll : false,
defaultSpeed : 1,
currentSpeed : 1,
intervalTime : 100,
reset : function() {
this.isAutoScroll && (this.currentSpeed = this.defaultSpeed);
},
startOrStop : function() {
var that = this;
if(that.isAutoScroll) {
that.isAutoScroll = false;
clearInterval(that.__autoScrollID);
} else {
that.isAutoScroll = true;
that.__autoScrollID = setInterval(function() {
global.scrollBy(0, that.currentSpeed);
}, that.intervalTime);
}
},
fast : function() {
this.isAutoScroll && this.currentSpeed <= 10 && this.currentSpeed++;
},
slow : function() {
this.isAutoScroll && this.currentSpeed > 1 && this.currentSpeed--;
},
keyControl : function(e) {
if(e.target != global.document.body && e.target != global.document.documentElement) return false; // only when the cursor focus on the page rather than the input area can trigger this event.
var charCode = e.charCode,
key = this.keyMap[charCode];
key && this[key]();
},
keyMap : {
'100' : 'slow', // press 'd', slow the speed of the scroll
'102' : 'fast', // press 'f', speed scroll
'114' : 'reset', // press 'r', reset the autoscroll's speed
'115' : 'startOrStop' //when you click 's' at the first time, the autoscroll is begin, and then you click again, it will stop.
}
};
global.addEventListener('keypress', bind(autoScroll, 'keyControl'), false);
}())
}(window.top))
Add before // ==/UserScript== on a new line:
// #grant GM_addStyle
Actually I'm surprised it did work until now because Greasemonkey requires #grant for over a year.

Add Lightbox in my code

I am working with thumnail image slider (jquery).Here i want to add a icon of zoom.when click then the selected image popup.this is current jquery code.
;(function($) {
// TODO:
// make sure we use ids, dont select stuff outside of plugin
var pluginName = 'pGallery',
defaults = {
printableVersionText: "Printable Version",
prevPhotoText: "<",
nextPhotoText: " >",
prevButtonText: "<",
nextButtonText: "Next >",
mobileCloseMarkup: "<i class='icon-remove'/>",
mobilePrevMarkup: "<i class='icon-chevron-left'/>",
mobileNextMarkup: "<i class='icon-chevron-right'/>",
mobileSlide: true
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new pGallery( this, options ));
}
});
};
// Primary Galleriffic initialization function that should be called on the thumbnail container.
function pGallery(element, options) {
// Extend Gallery Object
$.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this._element = element;
this.init();
}
pGallery.prototype.init = function(){
// here should set elements to variables to avoid searching again
// call methods to set up
// break down methods as much as possible
// simplify initial markup - add it all in init
this.addMarkup();
this.addControls();
}
pGallery.prototype.addMarkup = function() {
// is there a way to make the code in this method prettier? :|
this.$list = $(this._element);
this.$list.wrap("<div id='thumbs-container'/>");
this.$thumbsContainer = this.$list.parent();
this.$pagination = $("<div class='pagination1 '/>");
this.$thumbsContainer.append(this.$pagination.clone());
this.$pagination = this.$thumbsContainer.find("div.pagination1 ");
this.$pGalleryContainer = $("<div id='pGalleryContainer'/>");
this.$pGalleryContainer.insertBefore(this.$thumbsContainer);
this.$pGalleryContainer.append(this.$thumbsContainer);
this.$content = $("<div/>").addClass("pgallery-content");
this.$controls = $("<div/>").addClass("controls");
this.$bigSlideshowContainer = $("<div/>").addClass("big-slideshow-container");
this.$loadingSlideshowContainer = $("<div/>").addClass("loading-slideshow-container");
this.$loadingSlideshowContainer.append(this.$loading = $("<div/>").addClass("loading"));
this.$loadingSlideshowContainer.append(this.$loadingCaptionContainer = $("<div/>").addClass("caption-container"));
this.$slideshowContainer = $("<div/>").addClass("slideshow-container");
this.$slideshowContainer.append(this.$slideshow = $("<div/>").addClass("slideshow"));
this.$slideshowContainer.append(this.$captionContainer = $("<div/>").addClass("caption-container"));
this.$bigSlideshowContainer.append(this.$loadingSlideshowContainer);
this.$bigSlideshowContainer.append(this.$slideshowContainer);
this.$content.append(this.$controls);
this.$content.append(this.$bigSlideshowContainer);
$("body").append(this.$mobileOverlay = $("<div id='mobile-overlay'></div>"));
this.$mobileCloseButton = $("<div id='mobile-close-button'/>");
this.$mobileCloseWrap = $("<div id='mobile-close-wrap'/>").append($("<a href='#'/>").append(this.$mobileCloseButton));
this.$mobileCloseButton.append($(this._defaults.mobileCloseMarkup));
this.$mobilePrevButton = $("<div id='mobile-prev-button'/>");
this.$mobilePrevWrap = $("<div id='mobile-prev-wrap'/>").append($("<a href='#'/>").append(this.$mobilePrevButton));
this.$mobilePrevButton.append($(this._defaults.mobilePrevMarkup));
this.$mobileNextButton = $("<div id='mobile-next-button'/>");
this.$mobileNextWrap = $("<div id='mobile-next-wrap'/>").append($("<a href='#'/>").append(this.$mobileNextButton));
this.$mobileNextButton.append($(this._defaults.mobileNextMarkup));
this.$mobileThumbs = $("<ul/>").addClass("mobile-thumbs");
this.$mobileLoader = $("<div id='mobile-loader'/>");
this.$mobileOverlay.append(this.$mobileCloseWrap);
this.$mobileOverlay.append(this.$mobilePrevWrap);
this.$mobileOverlay.append(this.$mobileNextWrap);
this.$mobileOverlay.append(this.$mobileThumbs);
this.$mobileOverlay.append(this.$mobileLoader);
this.$pGalleryContainer.append(this.$content);
//this.$pGalleryContainer.append(this.$mobileOverlayTemp);
var self = this;
this.$list.children().each(function(i){
var $this = $(this);
$image = $this.find("img"),
imageURI = $image.attr("src"),
title = $image.attr("title");
$image.wrap("<a class='thumb' href='"+imageURI+"'/>");
$image.wrap("<div class='thumb-wrap'/>");
var $thumbWrap = $image.parent();
$thumbWrap.css("background-image", "url('"+imageURI+"')");
$image.hide();
var $caption = $("<div/>").addClass("caption"),
$download = $("<div/>").addClass("magnify").appendTo($caption),
$printable = $("<a/>").attr("href", imageURI).text(self._defaults.printableVersionText).appendTo($download),
$title = $("<div/>").addClass("image-title").text(title).appendTo($caption);
$caption.appendTo($this);
$this.addClass("image"+(i+1));
self.$mobileThumbs.append($("<li/>").addClass("m-image"+(i+1)));
self.overlayImageHtml(i+1);
});
self.$mobileThumbs.children().hide();
}
pGallery.prototype.addControls = function() {
var self = this;
// count the thumbs
this.numThumbs = this.$list.children().length;
this.divWidth = this.$thumbsContainer.width();
this.liWidth = this.$list.children().first().outerWidth(true);
this.currImage = 0;
this.currPage = 0;
this.perPage = 12;
this.changingImage = false;
// arrange them
this.cols = Math.floor(this.divWidth/this.liWidth);
// arrange the left controls
this.numPages = Math.ceil(this.numThumbs/this.perPage);
this.$navPrevButton = $("<a/>").addClass("p-prev").text(this._defaults.prevButtonText).appendTo(this.$pagination);
for (var i = 0; i < this.numPages; i++)
{
this.$pagination.append($("<a/>").addClass("p"+(i+1)).text((i+1)));
var $pageButton = this.$pagination.find(".p"+(i+1));
$pageButton.click(function(e) {
e.preventDefault();
self.pageChange($(this).text());
return false;
});
}
this.$navNextButton = $("<a/>").addClass("p-next").text(this._defaults.nextButtonText).appendTo(this.$pagination);
this.$navPrevButton.click(function(e) {
e.preventDefault();
self.pagePrev();
return false;
});
this.$navNextButton.click(function(e) {
e.preventDefault();
self.pageNext();
return false;
});
this.$navPrevButton.hide();
// make ellipses for hiding the page numbers on smaller screens and hide them
this.$ellRight = $("<span class='r-ell'>...</span>").insertBefore(this.$pagination.children(".p"+this.numPages)).hide();
this.$ellLeft = $("<span class='l-ell'>...</span>").insertAfter(this.$pagination.children(".p1")).hide();
// place the right controls
this.$controls.append(this.$prevButton = $("<a/>").addClass("prev").text(this._defaults.prevPhotoText));
this.$controls.append(this.$nextButton = $("<a/>").addClass("next").text(this._defaults.nextPhotoText));
this.$prevButton.click(function(e) {
e.preventDefault();
self.imagePrev();
return false;
});
this.$nextButton.click(function(e) {
e.preventDefault();
self.imageNext();
return false;
});
// setup thumb clicking
this.$list.find("li > a").click(function(e) {
e.preventDefault();
if (self.mobileScreenSize()){
self.showOverlay($(this).parent().attr('class'));
}
else{
self.changeImage($(this).parent().attr('class'));
}
return false;
});
this.$mobileCloseWrap.children("a").click(function(e) {
e.preventDefault();
self.hideOverlay();
return false;
});
this.$mobileNextWrap.children("a").click(function(e) {
e.preventDefault();
self.imageNext();
return false;
});
this.$mobilePrevWrap.children("a").click(function(e) {
e.preventDefault();
self.imagePrev();
return false;
});
this.changeImage('image1');
var image = this.$list.children().first().find("img").attr('src');
var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
self.resize();
}
}
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key
console.log("escape");
self.hideOverlay();
}
if (e.keyCode == 39) { // right arrow
console.log("right");
self.imageNext();
}
if (e.keyCode == 37) { // right arrow
console.log("left");
self.imagePrev();
}
});
this.resize();
}
pGallery.prototype.changeImage = function(liClass, right) {
right = typeof right !== 'undefined' ? right : true;
if (parseInt(liClass.replace("image","")) == this.currImage)
return;
this.currImage = parseInt(liClass.replace("image",""));
this.$list.children().removeClass("current");
this.$list.children("."+liClass).addClass("current");
var title = this.$list.children("."+liClass).find("a").attr('title');
//var imageURI = this.$list.children("."+liClass).find("div").css("background-image").replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
var imageURI = this.$list.children("."+liClass).find("img").attr('src');
var slideshowHtml = "<img title='"+(title != null?title:"")+"' src='"+imageURI+"'/>";
this.$loadingSlideshowContainer.children(".loading").html(this.$slideshow.html());
this.$slideshow.html(slideshowHtml);
this.$loadingCaptionContainer.html(this.$captionContainer.html());
this.$captionContainer.html(this.$list.children("."+liClass).find(".caption").html());
var time = 500;
if (this.$loadingSlideshowContainer.is(':animated') || this.$slideshowContainer.is(':animated')){
time = 0;
}
if (this.$loadingSlideshowContainer.children(".loading").html() != "")
{
this.$loadingSlideshowContainer.fadeTo(0, 1);
this.$slideshowContainer.fadeTo(0, 0);
this.$loadingSlideshowContainer.fadeTo(time, 0);
this.$slideshowContainer.fadeTo(time, 1);
}
// also do this for the mobile overlay, regardless of its showing or not
this.loadOverlayImage(this.currImage, right);
this.checkPageBounds();
}
pGallery.prototype.resize = function() {
var self = this;
this.$list.children().each(function(){
$(this).height($(this).width());
$(this).find(".thumb-wrap").height($(this).height()-2);
});
this.fixMargins(this.currImage);
}
pGallery.prototype.imageNext = function() {
if (this.currImage == this.numThumbs)
this.changeImage("image1");
else
this.changeImage("image"+(this.currImage+1));
}
pGallery.prototype.imagePrev = function() {
if (this.currImage == 1)
this.changeImage("image"+this.numThumbs, false);
else
this.changeImage("image"+(this.currImage-1), false);
}
pGallery.prototype.pageNext = function() {
if (this.currPage < this.numPages)
this.pageChange(parseInt(this.currPage)+1);
}
pGallery.prototype.pagePrev = function() {
if (this.currPage > 1)
this.pageChange(parseInt(this.currPage)-1);
}
pGallery.prototype.pageChange = function(page, changeSlideshow) {
changeSlideshow = typeof changeSlideshow !== 'undefined' ? changeSlideshow : true;
if (page == this.currPage)
return;
this.currPage = page;
this.$pagination.children().removeClass("current");
this.$pagination.children(".p"+this.currPage).addClass("current");
// hide all thumbs, then show thumbs on current page
this.$list.children().hide();
for (var i = (this.currPage-1)*this.perPage + 1; i < Math.min(this.currPage*this.perPage+1, this.numThumbs+1); i++)
{
this.$list.children(".image" + i).show();
}
if (changeSlideshow)
{
this.changeImage("image"+this.getPageLowerBounds(this.currPage));
}
this.adjustPagination();
this.resize();
// TODO: make this all happen at the same time, and add fadein/fadeout effects
}
pGallery.prototype.checkPageBounds = function() {
// TODO: make sure we're one the right page
// (typically after hiting prev/next image)
var correctPage = this.getPageFromIndex(this.currImage);
if (correctPage != this.currPage)
{
this.pageChange(correctPage, false);
}
}
pGallery.prototype.getPageLowerBounds = function(page) {
return ((this.currPage-1)*this.perPage)+1;
}
pGallery.prototype.getPageUpperBounds = function(page) {
return this.page*this.perPage
}
pGallery.prototype.getPageFromIndex = function(index) {
return (((index-1 - ((index-1)%this.perPage))/this.perPage) +1);
}
pGallery.prototype.adjustPagination = function() {
var tempPage = parseInt(this.currPage);
var tempNumPages = this.numPages;
var totalWidth = 0;
var allowedToRemove = new Array();
this.$pagination.children().each(function(index) {
$(this).show();
totalWidth += $(this).outerWidth(true);
$(this).removeClass("current");
var thisClass = $(this).attr("class");
var thisPageNum = parseInt(thisClass.replace("p",""));
if (!(thisClass == "p-prev" || thisClass == "p-next" ||
thisPageNum == tempPage || thisPageNum == (tempPage+1) ||
thisPageNum == (tempPage-1) || thisPageNum == 1 || thisPageNum == tempNumPages ||
thisClass == "l-ell" || thisClass == "r-ell")){
allowedToRemove.push(thisPageNum);
}
});
if (this.currPage >= this.numPages){
this.$navNextButton.hide();
}
if (this.currPage <= 1){
this.$navPrevButton.hide();
}
this.$ellLeft.hide();
this.$ellRight.hide();
while (allowedToRemove.length > 0 && totalWidth > this.$pagination.width())
{
// hide pages furthest away from current page
// max two ellipsis, at the ends
// do not hide:
// current, adjacent to current, first, last
// if greater/less than current show right/left ellipses
var maxDist = 0;
var maxPage = 0;
for (var i = 0; i < allowedToRemove.length; i++)
{
if (Math.abs(allowedToRemove[i] - this.currPage) > maxDist)
{
maxDist = Math.abs(allowedToRemove[i] - this.currPage);
maxPage = i;
}
}
this.$pagination.children(".p"+allowedToRemove[maxPage]).hide();
allowedToRemove.splice(maxPage, 1);
if (allowedToRemove[maxPage] < this.currPage){
this.$ellLeft.show();
}
if (allowedToRemove[maxPage] > this.currPage){
this.$ellRight.show();
}
totalWidth = 0;
this.$pagination.children(":visible").each(function() {
totalWidth += $(this).outerWidth(true);
});
}
this.$pagination.children(".p"+this.currPage).addClass("current");
}
pGallery.prototype.mobileScreenSize = function(){
if ($(window).width() < 772){ // width in em
return true;
}
else{
return false;
}
}
pGallery.prototype.showOverlay = function(image){
// makes overlay and image appear
// loads in next and previous images
// needs next and prev buttons, close button
// need to dynamically place images to center them
// initialize swiping?
this.$mobileOverlay.show();
$("body").css("overflow", "hidden");
this.changeImage(image, true);
}
pGallery.prototype.loadOverlayImage = function(image, right){
right = typeof right !== 'undefined' ? right : true;
if (this._defaults.mobileSlide){
if (right == true){
this.$mobileThumbs.children(":visible").hide('slide', {direction: 'left'}, 300);
this.$mobileThumbs.children(".m-image"+image).show('slide', {direction: 'right'}, 300);
}
else{
this.$mobileThumbs.children(":visible").hide('slide', {direction: 'right'}, 300);
this.$mobileThumbs.children(".m-image"+image).show('slide', {direction: 'left'}, 300);
}
}
else{
this.$mobileThumbs.children(":visible").hide();
this.$mobileThumbs.children(".m-image"+image).show();
}
this.fixMargins(image);
}
pGallery.prototype.overlayImageHtml = function(image){
var self = this;
var title = this.$list.children(".image" + image).children("a").attr('title');
var medLink = this.$list.children(".image" + image).children("a").attr('href');
var $image = $("<img title='"+(title != null?title:"")+"' src='"+medLink+"'/>");
this.$mobileThumbs.children(".m-image"+image).empty().append($image);
$image.on("load", function(){
self.fixMargins(image);
});
}
pGallery.prototype.fixMargins = function(image){
// good lord fix this
var self = this;
this.$mobileThumbs.find(".m-image"+image+ " > img").each(function(i){
$(this).css("margin-left",self.realWidth($(this), true)/-2).css("margin-top",self.realHeight($(this), true)/-2);
});
}
pGallery.prototype.hideOverlay = function(){
// hide overlay
this.$mobileOverlay.hide();
$("body").css("overflow", "auto");
}
pGallery.prototype.realWidth = function(obj, limitToWindow){
var clone = obj.clone();
clone.show();
clone.css("visibility","hidden");
if (limitToWindow){
clone.css("max-width", "100%");
clone.css("max-height", "100%");
}
$('body').append(clone);
var width = clone.outerWidth();
clone.remove();
return width;
}
pGallery.prototype.realHeight = function(obj, limitToWindow){
var clone = obj.clone();
clone.show();
clone.css("visibility","hidden");
if (limitToWindow){
clone.css("max-width", "100%");
clone.css("max-height", "100%");
}
$('body').append(clone);
var height = clone.outerHeight();
clone.remove();
return height;
}
})(jQuery);
This is html code
<ul id="thumbs">
<li>
<img src="image/01.jpg" title="" />
<div class="caption">
<div class="image-title">
On Canvas 24 x 36in <p style="color:#999">Code:0000</p>
<span>*Sold..</span></div>
<div class="image-title"> <p class="fb-like" data-href="data1/polo_images/p_image_1.jpg" data-width="100" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></p>
</div>
</div>
</li>
<li>
<img src="image/02.jpg" title="" />
<div class="caption">
<div class="image-title">
On Canvas 24 x 36in <p style="color:#999">Code:0000</p>
<span>*Sold..</span></div>
<div class="image-title"> <p class="fb-like" data-href="data1/polo_images/p_image_1.jpg" data-width="100" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></p>
</div>
</div>
</li>
</ul>
</div>
I want to have lightbox open when zoom icon clicked .

Building css properties via javascript events

I'm trying to display an arrow which guides the user to the top of the page on click:
html code
<a id="top" href="#"><img src="/img/arrow.png"></a>
css code
.scroll #top{
opacity: .2;
}
js code
o = $;
// misc junk
o(function(){
var width = window.innerWidth;
var height = window.innerHeight;
var doc = o(document);
// .onload
o('html').addClass('onload');
// top link
o('#top').click(function(e){
o('body').animate({ scrollTop: 0 }, 'fast');
e.preventDefault();
});
// scrolling links
var added;
doc.scroll(function(e){
if (doc.scrollTop() > 5) {
if (added) return;
added = true;
o('body').addClass('scroll');
} else {
o('body').removeClass('scroll');
added = false;
}
})
// highlight code
o('pre.js code').each(function(){
o(this).html(highlight(o(this).text()));
})
})
// active menu junk
o(function(){
var prev;
var n = 0;
var headings = o('h3').map(function(i, el){
return {
top: o(el).offset().top,
id: el.id
}
});
function closest() {
var h;
var top = o(window).scrollTop();
var i = headings.length;
while (i--) {
h = headings[i];
if (top >= h.top - 1) return h;
}
}
o(document).scroll(function(){
var h = closest();
if (!h) return;
if (prev) {
prev.removeClass('active');
prev.parent().parent().removeClass('active');
}
var a = o('a[href="#' + h.id + '"]');
a.addClass('active');
a.parent().parent().addClass('active');
prev = a;
})
})
/**
* Highlight the given `js`.
*/
function highlight(js) {
return js
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
.replace(/('.*?')/gm, '<span class="string">$1</span>')
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
.replace(/(\d+)/gm, '<span class="number">$1</span>')
.replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
}
Setting this in place, wouldn't makes appear the arrow on scroll of page. How to fix this, please ?

How to dynamically add elements via jQuery

The script below creates a slider widget the takes a definition list and turns it into a slide deck. Each dt element is rotated via css to become the "spine", which is used to reveal that dt's sibling dd element.
What I'm trying to do is to enhance it so that I can have the option to remove the spines from the layout and just use forward and back buttons on either side of the slide deck. To do that, I set the dt's to display:none via CSS and use the code under the "Remove spine layout" comment to test for visible.
This works fine to remove the spines, now I need to dynamically create 2 absolutely positioned divs to hold the left and right arrow images, as well as attach a click handler to them.
My first problem is that my attempt to create the divs is not working.
Any help much appreciated.
jQuery.noConflict();
(function(jQuery) {
if (typeof jQuery == 'undefined') return;
jQuery.fn.easyAccordion = function(options) {
var defaults = {
slideNum: true,
autoStart: false,
pauseOnHover: true,
slideInterval: 5000
};
this.each(function() {
var settings = jQuery.extend(defaults, options);
jQuery(this).find('dl').addClass('easy-accordion');
// -------- Set the variables ------------------------------------------------------------------------------
jQuery.fn.setVariables = function() {
dlWidth = jQuery(this).width()-1;
dlHeight = jQuery(this).height();
if (!jQuery(this).find('dt').is(':visible')){
dtWidth = 0;
dtHeight = 0;
slideTotal = 0;
// Add an element to rewind to previous slide
var slidePrev = document.createElement('div');
slidePrev.className = 'slideAdv prev';
jQuery(this).append(slidePrev);
jQuery('.slideAdv.prev').css('background':'red','width':'50px','height':'50px');
// Add an element to advance to the next slide
var slideNext = document.createElement('div');
slideNext.className = 'slideAdv next';
jQuery(this).append(slideNext);
jQuery('.slideAdv.next').css('background':'green','width':'50px','height':'50px');
}
else
{
dtWidth = jQuery(this).find('dt').outerHeight();
if (jQuery.browser.msie){ dtWidth = jQuery(this).find('dt').outerWidth();}
dtHeight = dlHeight - (jQuery(this).find('dt').outerWidth()-jQuery(this).find('dt').width());
slideTotal = jQuery(this).find('dt').size();
}
ddWidth = dlWidth - (dtWidth*slideTotal) - (jQuery(this).find('dd').outerWidth(true)-jQuery(this).find('dd').width());
ddHeight = dlHeight - (jQuery(this).find('dd').outerHeight(true)-jQuery(this).find('dd').height());
};
jQuery(this).setVariables();
// -------- Fix some weird cross-browser issues due to the CSS rotation -------------------------------------
if (jQuery.browser.safari){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; /* Safari and Chrome */ }
if (jQuery.browser.mozilla){ var dtTop = dlHeight - 20; var dtOffset = - 20; /* FF */ }
if (jQuery.browser.msie){ var dtTop = 0; var dtOffset = 0; /* IE */ }
if (jQuery.browser.opera){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; } /* Opera */
// -------- Getting things ready ------------------------------------------------------------------------------
var f = 1;
var paused = false;
jQuery(this).find('dt').each(function(){
jQuery(this).css({'width':dtHeight,'top':dtTop,'margin-left':dtOffset});
// add unique id to each tab
jQuery(this).addClass('spine_' + f);
// add active corner
var corner = document.createElement('div');
corner.className = 'activeCorner spine_' + f;
jQuery(this).append(corner);
if(settings.slideNum == true){
jQuery('<span class="slide-number">'+f+'</span>').appendTo(this);
if(jQuery.browser.msie){
var slideNumLeft = parseInt(jQuery(this).find('.slide-number').css('left'));
if(jQuery.browser.version == 6.0 || jQuery.browser.version == 7.0){
jQuery(this).find('.slide-number').css({'bottom':'auto'});
slideNumLeft = slideNumLeft - 14;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
}
if(jQuery.browser.version == 8.0 || jQuery.browser.version == 9.0){
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top')) - 20;
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
slideNumLeft = slideNumLeft - 10;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
jQuery(this).find('.slide-number').css({'marginTop': 10});
}
} else {
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top'));
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
}
}
f = f + 1;
});
if(jQuery(this).find('.active').size()) {
jQuery(this).find('.active').next('dd').addClass('active');
} else {
jQuery(this).find('dt:first').addClass('active').next('dd').addClass('active');
}
jQuery(this).find('dt:first').css({'left':'0'}).next().css({'left':dtWidth});
jQuery(this).find('dd').css({'width':ddWidth,'height':ddHeight});
// -------- Functions ------------------------------------------------------------------------------
jQuery.fn.findActiveSlide = function() {
var i = 1;
this.find('dt').each(function(){
if(jQuery(this).hasClass('active')){
activeID = i; // Active slide
} else if (jQuery(this).hasClass('no-more-active')){
noMoreActiveID = i; // No more active slide
}
i = i + 1;
});
};
jQuery.fn.calculateSlidePos = function() {
var u = 2;
jQuery(this).find('dt').not(':first').each(function(){
var activeDtPos = dtWidth*activeID;
if(u <= activeID){
var leftDtPos = dtWidth*(u-1);
jQuery(this).animate({'left': leftDtPos});
if(u < activeID){ // If the item sits to the left of the active element
jQuery(this).next().css({'left':leftDtPos+dtWidth});
} else{ // If the item is the active one
jQuery(this).next().animate({'left':activeDtPos});
}
} else {
var rightDtPos = dlWidth-(dtWidth*(slideTotal-u+1));
jQuery(this).animate({'left': rightDtPos});
var rightDdPos = rightDtPos+dtWidth;
jQuery(this).next().animate({'left':rightDdPos});
}
u = u+ 1;
});
setTimeout( function() {
jQuery('.easy-accordion').find('dd').not('.active').each(function(){
jQuery(this).css({'display':'none'});
});
}, 400);
};
jQuery.fn.activateSlide = function() {
this.parent('dl').setVariables();
this.parent('dl').find('dd').css({'display':'block'});
this.parent('dl').find('dd.plus').removeClass('plus');
this.parent('dl').find('.no-more-active').removeClass('no-more-active');
this.parent('dl').find('.active').removeClass('active').addClass('no-more-active');
this.addClass('active').next().addClass('active');
this.parent('dl').findActiveSlide();
if(activeID < noMoreActiveID){
this.parent('dl').find('dd.no-more-active').addClass('plus');
}
this.parent('dl').calculateSlidePos();
};
jQuery.fn.rotateSlides = function(slideInterval, timerInstance) {
var accordianInstance = jQuery(this);
timerInstance.value = setTimeout(function(){accordianInstance.rotateSlides(slideInterval, timerInstance);}, slideInterval);
if (paused == false){
jQuery(this).findActiveSlide();
var totalSlides = jQuery(this).find('dt').size();
var activeSlide = activeID;
var newSlide = activeSlide + 1;
if (newSlide > totalSlides) {newSlide = 1; paused = true;}
jQuery(this).find('dt:eq(' + (newSlide-1) + ')').activateSlide(); // activate the new slide
}
}
// -------- Let's do it! ------------------------------------------------------------------------------
function trackerObject() {this.value = null}
var timerInstance = new trackerObject();
jQuery(this).findActiveSlide();
jQuery(this).calculateSlidePos();
if (settings.autoStart == true){
var accordianInstance = jQuery(this);
var interval = parseInt(settings.slideInterval);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
}
jQuery(this).find('dt').not('active').click(function(){
var accordianInstance = jQuery(this); //JSB to fix bug with IE < 9
jQuery(this).activateSlide();
clearTimeout(timerInstance.value);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
});
if (!(jQuery.browser.msie && jQuery.browser.version == 6.0)){
jQuery('dt').hover(function(){
jQuery(this).addClass('hover');
}, function(){
jQuery(this).removeClass('hover');
});
}
if (settings.pauseOnHover == true){
jQuery('dd').hover(function(){
paused = true;
}, function(){
paused = false;
});
}
});
};
})(jQuery);
Creating elements in jQuery is easy:
$newDiv = $('<div />');
$newDiv.css({
'position': 'absolute',
'top': '10px',
'left': '10px'
});
$newDiv.on('click', function() {
alert('You have clicked me');
});
$('#your_container').append($newDiv);

Categories