There is a piece of code inside of a magento view.phtml file that was put there to control an out of stock functionality. It only displays on the page when the product is not saleable.
It works as intended, to a point. However on mobile devices such as an iPad or when the user resizes the viewport (even when inspecting for example) it causes a duplication of the div in question and eventually causes the browser to 'crash' the page.
The code is here:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('.sharing-links').appendTo(jQuery('.current_configuration_bottom'));
jQuery('.configured-bundles-wrap').appendTo(jQuery('.current_configuration_bottom'));
function isElementOutViewport(el) {
el = document.getElementById(el);
var rect = el.getBoundingClientRect();
return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;
}
function setBuyBox() {
var width = jQuery(window).width();
var right_description = jQuery('.right_description');
var is_iPad = navigator.userAgent.match(/iPad/i) != null;
if (( width >= 998 || is_iPad )) {
right_description.appendTo('.product-sidebar');
right_description.addClass('stick-right');
right_description.css('top', '250px');
var rightContent = jQuery('.current_configuration');
var stick_right = jQuery('#header .container').offset().left
var stick_width = (22 / width) * jQuery('#header .container').outerWidth();
var rightCol_offset_top = right_description.offset().top - 205;
jQuery(window).scroll(function () {
var stop_offset_top = jQuery('#bottom').offset().top - right_description.outerHeight() - 250;
if (jQuery(window).scrollTop() > rightCol_offset_top && jQuery(window).scrollTop() < stop_offset_top) {
if (is_iPad) {
// console.log('case 1');
rightContent.css('top', '200px');
rightContent.css({
'position': 'fixed',
'width': '223px',
'max-width': '100%',
'right': 'auto',
'bottom': 'auto'
});
rightContent.removeClass("stick-right-bottom");
rightContent.removeClass("stick-right");
var footerOutView = isElementOutViewport('footer-container');
var headerOutView = isElementOutViewport('header');
if (!headerOutView) {
rightContent.css({
'position': 'static',
'top': '0',
'bottom': 'auto',
'right': 'auto'
});
}
if (!footerOutView) {
rightContent.css({
'position': 'absolute',
'bottom': '0',
'top': 'auto',
'right': '0'
});
}
} else {
// console.log('case 2');
right_description.css('top', '200px');
right_description.addClass("stick-right");
right_description.removeClass("stick-right-bottom");
rightContent.css('top', '200px');
rightContent.addClass("stick-right");
rightContent.removeClass("stick-right-bottom");
var footerOutView = isElementOutViewport('footer-container');
//console.log(footerInView);
if (!footerOutView) {
rightContent.css('top', 'auto');
rightContent.removeClass('stick-right');
rightContent.addClass('stick-right-bottom');
}
if (is_iPad) {
rightContent.css('top', 'auto');
rightContent.css({
'position': 'absolute',
'bottom': '0',
'top': 'auto',
'right': '0'
});
}
}
} else if (jQuery(window).scrollTop() > stop_offset_top) {
// console.log('case 3');
right_description.css('top', 'auto');
right_description.removeClass("stick-right");
right_description.addClass("stick-right-bottom");
if (is_iPad) {
// console.log('ipad 3');
rightContent.css({
'position': 'absolute',
'bottom': '0',
'top': 'auto',
'right': '0'
});
}
var footerOutView = isElementOutViewport('footer-container');
//console.log(footerInView);
if (!footerOutView) {
rightContent.css('top', 'auto');
rightContent.removeClass('stick-right');
rightContent.addClass('stick-right-bottom');
}
//rightContent.css({'width':'auto', 'position': 'static'});
} else {
// console.log('case 4');
right_description.css('top', 'auto');
right_description.removeClass("stick-right");
right_description.removeClass("stick-right-bottom");
rightContent.css('top', '200px');
var footerOutView = isElementOutViewport('footer-container');
//console.log(footerInView);
if (!footerOutView) {
rightContent.css('top', 'auto');
rightContent.removeClass('stick-right');
rightContent.addClass('stick-right-bottom');
}
if (is_iPad) {
var headerOutView = isElementOutViewport('header');
//console.log(headerOutView);
if (!footerOutView || !headerOutView) {
rightContent.css({'position': 'static', 'top': 'auto', 'width': 'auto'});
}
}
}
});
} else {
// console.log('case 5');
//right_description.appendTo('.product_details');
//right_description.css('top', 'auto');
//right_description.removeClass('stick-right');
}
}
jQuery(window).resize(function () {
setBuyBox();
});
window.onorientationchange = function () {
setBuyBox();
};
setBuyBox();
});
</script>
I have tried a couple of things to get this to stop happening, changing right_description.appendTo('product-sidebar'); to .after however it is still happening.
Im not entirely sure this whole code is necessary to achieve what was originally needed.
Im brushing up on my js/jquery implementation and any pointers on how to clean this code up and fix the issue would be appreciated.
We had a developer code this javascript map that has pop-ups when you hover over certain points.
http://www.cadenceaerospace.com/products/aeros/centers_of_excellence/index_test.html
I'm trying to add a new point (B&E) and it should open up the same way that Tell Tool opens up but I can't get it to work. I don't know much javascript so would someone be able to take a look and see what I'm doing wrong?
This is the code on the page that controls the map:
<script language="javascript">
$(document).ready(function() {
$('#loc_map > DIV').css({'display': 'none', 'position': 'absolute'});
$('#loc_map > DIV > DIV').each(function(i,e) {
var close_button = document.createElement('span');
close_button.className = 'close_button';
var button_x = document.createElement('a');
button_x.innerHTML = 'X';
button_x.href = '#';
$(button_x).on('click', function(x) {
//console.log(e.parentNode.id);
$('#loc_map > DIV').css({'display': 'none'});
x.preventDefault();
});
$(close_button).prepend(button_x);
$(e).prepend( close_button );
});
$('#loc_map AREA')
.on('mouseover', function(e) {
e.preventDefault();
var div_id = e.currentTarget.alt,
div = $(document.getElementById(div_id)),
left = (div_id == 'tell_tool_operations')? e.pageX-5 - div.outerWidth() : e.pageX+5,
top = (RegExp(/^(giddens|pmw|tell|be)/).test(div_id))? e.pageY+5 : e.pageY-5 - div.outerHeight();
$('#loc_map > DIV').css({'display': 'none'});
div.css({'display': 'block', 'left': left, 'top': top});
});
$('#loc_map AREA')
.on('click', function(e) {
e.preventDefault();
var div_id = e.currentTarget.alt,
div = $(document.getElementById(div_id)),
left = (div_id == 'tell_tool_operations')? e.pageX-5 - div.outerWidth() : e.pageX+5,
top = (RegExp(/^(giddens|pmw|tell|be)/).test(div_id))? e.pageY+5 : e.pageY-5 - div.outerHeight();
$('#loc_map > DIV').css({'display': 'none'});
div.css({'display': 'block', 'left': left, 'top': top});
});
});
</script>
Let me know if you need anything else from me. Thanks!
The line that calculates the left position needs to be modified from
left = (div_id == 'tell_tool_operations')? e.pageX-5 - div.outerWidth() : e.pageX + 5
...to...
left = (div_id == 'tell_tool_operations' || div_id == 'be_oem')? e.pageX-5 - div.outerWidth() : e.pageX + 5
The added part is || div_id == 'be_oem'.
Modified code
<script language="javascript">
$(document).ready(function() {
$('#loc_map > DIV').css({'display': 'none', 'position': 'absolute'});
$('#loc_map > DIV > DIV').each(function(i,e) {
var close_button = document.createElement('span');
close_button.className = 'close_button';
var button_x = document.createElement('a');
button_x.innerHTML = 'X';
button_x.href = '#';
$(button_x).on('click', function(x) {
//console.log(e.parentNode.id);
$('#loc_map > DIV').css({'display': 'none'});
x.preventDefault();
});
$(close_button).prepend(button_x);
$(e).prepend( close_button );
});
$('#loc_map AREA')
.on('mouseover', function(e) {
e.preventDefault();
var div_id = e.currentTarget.alt,
div = $(document.getElementById(div_id)),
left = (div_id == 'tell_tool_operations' || div_id == 'be_oem')? e.pageX-5 - div.outerWidth() : e.pageX+5,
top = (RegExp(/^(giddens|pmw|tell|be)/).test(div_id))? e.pageY+5 : e.pageY-5 - div.outerHeight();
$('#loc_map > DIV').css({'display': 'none'});
div.css({'display': 'block', 'left': left, 'top': top});
});
$('#loc_map AREA')
.on('click', function(e) {
e.preventDefault();
var div_id = e.currentTarget.alt,
div = $(document.getElementById(div_id)),
left = (div_id == 'tell_tool_operations' || div_id == 'be_oem')? e.pageX-5 - div.outerWidth() : e.pageX+5,
top = (RegExp(/^(giddens|pmw|tell|be)/).test(div_id))? e.pageY+5 : e.pageY-5 - div.outerHeight();
$('#loc_map > DIV').css({'display': 'none'});
div.css({'display': 'block', 'left': left, 'top': top});
});
});
</script>
I'm stuck with my page scroll effects.
This is what I've got so far - https://codepen.io/DCRSLG/pen/jzYJeY
$(document).ready(function($) {
//variables
var hijacking = $('body').data('hijacking'),
animationType = $('body').data('animation'),
delta = 0,
scrollThreshold = 5,
actual = 1,
animating = false;
//DOM elements
var sectionsAvailable = $('.cd-section'),
verticalNav = $('.cd-vertical-nav'),
prevArrow = verticalNav.find('a.cd-prev'),
nextArrow = verticalNav.find('a.cd-next');
//check the media query and bind corresponding events
var MQ = deviceType(),
bindToggle = false;
bindEvents(MQ, true);
$(window).on('resize', function() {
MQ = deviceType();
bindEvents(MQ, bindToggle);
if (MQ == 'mobile') bindToggle = true;
if (MQ == 'desktop') bindToggle = false;
});
function bindEvents(MQ, bool) {
if (MQ == 'desktop' && bool) {
//bind the animation to the window scroll event, arrows click and keyboard
if (hijacking == 'on') {
initHijacking();
$(window).on('DOMMouseScroll mousewheel', scrollHijacking);
} else {
scrollAnimation();
$(window).on('scroll', scrollAnimation);
}
prevArrow.on('click', prevSection);
nextArrow.on('click', nextSection);
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
$(document).on('keydown', function(event) {
if (event.which == '40' && !nextArrow.hasClass('inactive')) {
event.preventDefault();
nextSection();
} else if (event.which == '38' && (!prevArrow.hasClass('inactive') || (prevArrow.hasClass('inactive') && $(window).scrollTop() != sectionsAvailable.eq(0).offset().top))) {
event.preventDefault();
prevSection();
}
});
//set navigation arrows visibility
checkNavigation();
} else if (MQ == 'mobile') {
//reset and unbind
resetSectionStyle();
$(window).off('DOMMouseScroll mousewheel', scrollHijacking);
$(window).off('scroll', scrollAnimation);
prevArrow.off('click', prevSection);
nextArrow.off('click', nextSection);
$(document).off('keydown');
}
}
function scrollAnimation() {
//normal scroll - use requestAnimationFrame (if defined) to optimize performance
(!window.requestAnimationFrame) ? animateSection(): window.requestAnimationFrame(animateSection);
}
function animateSection() {
var scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
windowWidth = $(window).width();
sectionsAvailable.each(function() {
var actualBlock = $(this),
offset = scrollTop - actualBlock.offset().top;
//according to animation type and window scroll, define animation parameters
var animationValues = setSectionAnimation(offset, windowHeight, animationType);
transformSection(actualBlock.children('div'), animationValues[0], animationValues[1], animationValues[2], animationValues[3], animationValues[4]);
(offset >= 0 && offset < windowHeight) ? actualBlock.addClass('visible'): actualBlock.removeClass('visible');
});
checkNavigation();
}
function transformSection(element, translateY, scaleValue, rotateXValue, opacityValue, boxShadow) {
//transform sections - normal scroll
element.velocity({
translateY: translateY + 'vh',
scale: scaleValue,
rotateX: rotateXValue,
opacity: opacityValue,
boxShadowBlur: boxShadow + 'px',
translateZ: 0,
}, 0);
}
function initHijacking() {
// initialize section style - scrollhijacking
var visibleSection = sectionsAvailable.filter('.visible'),
topSection = visibleSection.prevAll('.cd-section'),
bottomSection = visibleSection.nextAll('.cd-section'),
animationParams = selectAnimation(animationType, false),
animationVisible = animationParams[0],
animationTop = animationParams[1],
animationBottom = animationParams[2];
visibleSection.children('div').velocity(animationVisible, 1, function() {
visibleSection.css('opacity', 1);
topSection.css('opacity', 1);
bottomSection.css('opacity', 1);
});
topSection.children('div').velocity(animationTop, 0);
bottomSection.children('div').velocity(animationBottom, 0);
}
function scrollHijacking(event) {
// on mouse scroll - check if animate section
if (event.originalEvent.detail < 0 || event.originalEvent.wheelDelta > 0) {
delta--;
(Math.abs(delta) >= scrollThreshold) && prevSection();
} else {
delta++;
(delta >= scrollThreshold) && nextSection();
}
return false;
}
function prevSection(event) {
//go to previous section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
visibleSection = middleScroll ? visibleSection.next('.cd-section') : visibleSection;
var animationParams = selectAnimation(animationType, middleScroll, 'prev');
unbindScroll(visibleSection.prev('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":first-child")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[2], animationParams[3], animationParams[4])
.end().prev('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual - 1;
}
resetScroll();
}
function nextSection(event) {
//go to next section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
var animationParams = selectAnimation(animationType, middleScroll, 'next');
unbindScroll(visibleSection.next('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":last-of-type")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[1], animationParams[3], animationParams[4])
.end().next('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual + 1;
}
resetScroll();
}
function unbindScroll(section, time) {
//if clicking on navigation - unbind scroll and animate using custom velocity animation
if (hijacking == 'off') {
$(window).off('scroll', scrollAnimation);
(animationType == 'catch') ? $('body, html').scrollTop(section.offset().top): section.velocity("scroll", {
duration: time
});
}
}
function resetScroll() {
delta = 0;
checkNavigation();
}
function checkNavigation() {
//update navigation arrows visibility
(sectionsAvailable.filter('.visible').is(':first-of-type')) ? prevArrow.addClass('inactive'): prevArrow.removeClass('inactive');
(sectionsAvailable.filter('.visible').is(':last-of-type')) ? nextArrow.addClass('inactive'): nextArrow.removeClass('inactive');
}
function resetSectionStyle() {
//on mobile - remove style applied with jQuery
sectionsAvailable.children('div').each(function() {
$(this).attr('style', '');
});
}
function deviceType() {
//detect if desktop/mobile
return window.getComputedStyle(document.querySelector('body'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, "");
}
function selectAnimation(animationName, middleScroll, direction) {
// select section animation - scrollhijacking
var animationVisible = 'translateNone',
animationTop = 'translateUp',
animationBottom = 'translateDown',
easing = 'ease',
animDuration = 800;
switch (animationName) {
case 'gallery':
animDuration = 1500;
if (middleScroll) {
animationTop = 'scaleDown.moveUp.scroll';
animationVisible = 'scaleUp.moveUp.scroll';
animationBottom = 'scaleDown.moveDown.scroll';
} else {
animationVisible = (direction == 'next') ? 'scaleUp.moveUp' : 'scaleUp.moveDown';
animationTop = 'scaleDown.moveUp';
animationBottom = 'scaleDown.moveDown';
}
break;
}
return [animationVisible, animationTop, animationBottom, animDuration, easing];
}
function setSectionAnimation(sectionOffset, windowHeight, animationName) {
// select section animation - normal scroll
var scale = 1,
translateY = 100,
rotateX = '0deg',
opacity = 1,
boxShadowBlur = 0;
if (sectionOffset >= -windowHeight && sectionOffset <= 0) {
// section entering the viewport
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= -windowHeight && sectionOffset < -0.9 * windowHeight) {
scale = -sectionOffset / windowHeight;
translateY = (-sectionOffset) * 100 / windowHeight;
boxShadowBlur = 400 * (1 + sectionOffset / windowHeight);
} else if (sectionOffset >= -0.9 * windowHeight && sectionOffset < -0.1 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset + 0.1 * windowHeight) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = 1 + sectionOffset / windowHeight;
translateY = 0;
boxShadowBlur = -400 * sectionOffset / windowHeight;
}
break;
}
} else if (sectionOffset > 0 && sectionOffset <= windowHeight) {
//section leaving the viewport - still has the '.visible' class
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= 0 && sectionOffset < 0.1 * windowHeight) {
scale = (windowHeight - sectionOffset) / windowHeight;
translateY = -(sectionOffset / windowHeight) * 100;
boxShadowBlur = 400 * sectionOffset / windowHeight;
} else if (sectionOffset >= 0.1 * windowHeight && sectionOffset < 0.9 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset - 0.1 * windowHeight / 9) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = sectionOffset / windowHeight;
translateY = -100;
boxShadowBlur = 400 * (1 - sectionOffset / windowHeight);
}
break;
}
} else if (sectionOffset < -windowHeight) {
translateY = 100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
} else {
//section not visible anymore
translateY = -100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
}
return [translateY, scale, rotateX, opacity, boxShadowBlur];
}
});
/* Custom effects registration - feature available in the Velocity UI pack */
//gallery
$.Velocity
.RegisterEffect("scaleDown.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '-10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '-100%'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '-100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '0%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '100%'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '-90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
I'm trying to get it so the Dots on the right hand side can be a reference to scroll down to each section like this:
https://codyhouse.co/demo/vertical-fixed-navigation/index.html
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
I can get it to work using the above code providing I disable data-hijacking on the scroll, does anyone know of a way to get this to work while keep data-hijacking enabled?
I'm trying to change the header size (which I named #headwrapper) and its background color when scrolling down. As you can see I need it to trigger the class .small when scrolling is > 145.
It is working only when I minimize the screen's width to 600px or less.
I have this problem since I had to change the very last line from height: '130px' to height: 'auto'; max-height: '1000px'. This in order to fully see the drop down menu triggered when the screens width is 600px. It was cutting in half with height 130px.
This is the script:
$(window).scroll(function () {
var sc = $(window).scrollTop()
if (sc > 145) {
$("#pageheader, #headwrapper, #main-nav, .logos, #social, #main- logo").addClass("small");
}
else {
$("#pageheader, #headwrapper, #main-nav, .logos, #social, #main- logo").removeClass("small")
}
});
$(function(){
$('#headwrapper').data('size', 'big');
});
$(window).scroll(function(){
if ($(document).scrollTop() > 200) {
if ($('#headwrapper').data('size') == 'big') {
$('#headwrapper').data('size', 'small');
$('#headwrapper').stop().animate({
height:'75px'
}, 400);
}
} else {
if ($('#headwrapper').data('size') == 'small') {
$('#headwrapper').data('size', 'big');
$('#headwrapper').stop().animate({
height: 'auto';
max-height: '1000px'
}, 400);
}
}
});
You have an error in the animate object syntax. Replace the ; with , and quote them:
$('#headwrapper').stop().animate({
"height": 'auto', // Change ; to , as this is an object.
"max-height": '1000px'
}, 400);
And move everything inside the document's ready function:
$(function() {
$('#headwrapper').data('size','big');
$(window).scroll(function () {
var sc = $(window).scrollTop();
if (sc > 145) {
$("#pageheader,#headwrapper,#main-nav,.logos,#social,#main- logo").addClass("small");
}
else {
$("#pageheader,#headwrapper,#main-nav,.logos,#social,#main- logo").removeClass("small");
}
});
$(window).scroll(function() {
if($(document).scrollTop() > 200) {
if($('#headwrapper').data('size') == 'big') {
$('#headwrapper').data('size','small');
$('#headwrapper').stop().animate({
height:'75px'
},400);
}
}
else
{
if($('#headwrapper').data('size') == 'small') {
$('#headwrapper').data('size','big');
$('#headwrapper').stop().animate({
"height": 'auto',
"max-height": '1000px'
},400);
}
}
});
});
I am using the following javascript which uses some jQuery, neither of which I know much about. This is for a simple image slider:
/*!
* jQuery wmuSlider v2.1
*
* Copyright (c) 2011 Brice Lechatellier
* http://brice.lechatellier.com/
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
;(function($) {
$.fn.wmuSlider = function(options) {
/* Default Options
================================================== */
var defaults = {
animation: 'fade',
animationDuration: 600,
slideshow: true,
slideshowSpeed: 7000,
slideToStart: 0,
navigationControl: true,
paginationControl: true,
previousText: 'Previous',
nextText: 'Next',
touch: false,
slide: 'article',
items: 1
};
var options = $.extend(defaults, options);
return this.each(function() {
/* Variables
================================================== */
var $this = $(this);
var currentIndex = options.slideToStart;
var wrapper = $this.find('.wmuSliderWrapper');
var slides = $this.find(options.slide);
var slidesCount = slides.length;
var slideshowTimeout;
var paginationControl;
var isAnimating;
/* Load Slide
================================================== */
var loadSlide = function(index, infinite, touch) {
if (isAnimating) {
return false;
}
isAnimating = true;
currentIndex = index;
var slide = $(slides[index]);
$this.animate({ height: slide.innerHeight() });
if (options.animation == 'fade') {
slides.css({
position: 'absolute',
opacity: 0
});
slide.css('position', 'relative');
slide.animate({ opacity:1 }, options.animationDuration, function() {
isAnimating = false;
});
} else if (options.animation == 'slide') {
if (!infinite) {
wrapper.animate({ marginLeft: -$this.width() / options.items * index }, options.animationDuration, function() {
isAnimating = false;
});
} else {
if (index == 0) {
wrapper.animate({ marginLeft: -$this.width() / options.items * slidesCount }, options.animationDuration, function() {
wrapper.css('marginLeft', 0);
isAnimating = false;
});
} else {
if (!touch) {
wrapper.css('marginLeft', -$this.width() / options.items * slidesCount);
}
wrapper.animate({ marginLeft: -$this.width() / options.items * index }, options.animationDuration, function() {
isAnimating = false;
});
}
}
}
if (paginationControl) {
paginationControl.find('a').each(function(i) {
if(i == index) {
$(this).addClass('wmuActive');
} else {
$(this).removeClass('wmuActive');
}
});
}
// Trigger Event
$this.trigger('slideLoaded', index);
};
/* Navigation Control
================================================== */
if (options.navigationControl) {
var prev = $('<a class="wmuSliderPrev">' + options.previousText + '</a>');
prev.click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
if (currentIndex == 0) {
loadSlide(slidesCount - 1, true);
} else {
loadSlide(currentIndex - 1);
}
});
$this.append(prev);
var next = $('<a class="wmuSliderNext">' + options.nextText + '</a>');
next.click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
if (currentIndex + 1 == slidesCount) {
loadSlide(0, true);
} else {
loadSlide(currentIndex + 1);
}
});
$this.append(next);
}
/* Pagination Control
================================================== */
if (options.paginationControl) {
paginationControl = $('<ul class="wmuSliderPagination"></ul>');
$.each(slides, function(i) {
paginationControl.append('<li>' + i + '</li>');
paginationControl.find('a:eq(' + i + ')').click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
loadSlide(i);
});
});
$this.append(paginationControl);
}
/* Slideshow
================================================== */
if (options.slideshow) {
var slideshow = function() {
if (currentIndex + 1 < slidesCount) {
loadSlide(currentIndex + 1);
} else {
loadSlide(0, true);
}
slideshowTimeout = setTimeout(slideshow, options.slideshowSpeed);
}
slideshowTimeout = setTimeout(slideshow, options.slideshowSpeed);
}
/* Resize Slider
================================================== */
var resize = function() {
var slide = $(slides[currentIndex]);
$this.animate({ height: slide.innerHeight() });
if (options.animation == 'slide') {
slides.css({
width: $this.width() / options.items
});
wrapper.css({
marginLeft: -$this.width() / options.items * currentIndex,
width: $this.width() * slides.length
});
}
};
/* Touch
================================================== */
var touchSwipe = function(event, phase, direction, distance) {
clearTimeout(slideshowTimeout);
if(phase == 'move' && (direction == 'left' || direction == 'right')) {
if (direction == 'right') {
if (currentIndex == 0) {
wrapper.css('marginLeft', (-slidesCount * $this.width() / options.items) + distance);
} else {
wrapper.css('marginLeft', (-currentIndex * $this.width() / options.items) + distance);
}
} else if (direction == 'left') {
wrapper.css('marginLeft', (-currentIndex * $this.width() / options.items) - distance);
}
} else if (phase == 'cancel' ) {
if (direction == 'right' && currentIndex == 0) {
wrapper.animate({ marginLeft: -slidesCount * $this.width() / options.items }, options.animationDuration);
} else {
wrapper.animate({ marginLeft: -currentIndex * $this.width() / options.items }, options.animationDuration);
}
} else if (phase == 'end' ) {
if (direction == 'right') {
if (currentIndex == 0) {
loadSlide(slidesCount - 1, true, true);
} else {
loadSlide(currentIndex - 1);
}
} else if (direction == 'left') {
if (currentIndex + 1 == slidesCount) {
loadSlide(0, true);
} else {
loadSlide(currentIndex + 1);
}
} else {
wrapper.animate({ marginLeft: -currentIndex * $this.width() / options.items }, options.animationDuration);
}
}
};
if (options.touch && options.animation == 'slide') {
if (!$.isFunction($.fn.swipe)) {
$.ajax({
url: 'jquery.touchSwipe.min.js',
async: false
});
}
if ($.isFunction($.fn.swipe)) {
$this.swipe({ triggerOnTouchEnd:false, swipeStatus:touchSwipe, allowPageScroll:'vertical' });
}
}
/* Init Slider
================================================== */
var init = function() {
var slide = $(slides[currentIndex]);
var img = slide.find('img');
img.load(function() {
wrapper.show();
$this.animate({ height: slide.innerHeight() });
});
if (options.animation == 'fade') {
slides.css({
position: 'absolute',
width: '100%',
opacity: 0
});
$(slides[currentIndex]).css('position', 'relative');
} else if (options.animation == 'slide') {
if (options.items > slidesCount) {
options.items = slidesCount;
}
slides.css('float', 'left');
slides.each(function(i){
var slide = $(this);
slide.attr('data-index', i);
});
for(var i = 0; i < options.items; i++) {
wrapper.append($(slides[i]).clone());
}
slides = $this.find(options.slide);
}
resize();
$this.trigger('hasLoaded');
loadSlide(currentIndex);
}
init();
/* Bind Events
================================================== */
// Resize
$(window).resize(resize);
// Load Slide
$this.bind('loadSlide', function(e, i) {
clearTimeout(slideshowTimeout);
loadSlide(i);
});
});
}
})(jQuery);
what I want to be able to do is change the slider image index with some sort of 'onclick' event. for example:
<img src="images/IMG_5137_s.jpg" width="100%" />
this however does not call the 'loadslide' function in the javascript file, probably because I don't know what I'm doing.... any help with this would be appreciated.
You can inspect this answer for jQuery plugin-authoring:
How to create simple jQuery plugin?
And here is the simple jsFiddle example with explanation on it.