Stuck while Implementing complex jQuery Image Slider - javascript

I have stuck some where while modifying THIS slider.
Here Thumbnail & main display Image have one to one relationship i.e by clicking on 1 thumbnail, It shows a single Image & then it slides to the next thumbnail & displays its associated image & so on.
Now, I want to modify this slider in such a way that one thumbnail should be assiciated / linked with multiple Images i.e one thumbnail to many main display images relationship (one –to-many)
i.e by clicking on “Bedroom thumbnail” (As shown in attached image .. SCREENSHOT ) , It should only display & slide 5 (or n) number of Images related to this particular thumbnail, then in the same way if I am clicking on “Bathroom thumbnail” , It should display & slide 5 (or n) number of images related to this particular section & so on. So this is how I wanna modify the code from ONE-to-ONE [one thumbnail-to-one main display image] to ONE-to-MANY [one thumbnail-to- 5 or n number of images related to that particular thumbnail]
My Modified Thumbnail Section’s HTML code is same.
I have modified the Main Image section as shown ..
<div id="lofslidecontent45" class="lof-slidecontent" style="width:670px;height:236px;">
<div class="preload"><div></div></div>
<div class="lof-main-outer" style="width:670px; height:236px;">
<ul class="lof-main-wapper">
<li>
<ul class=”lof-main-subwapper”>
<li>
<img src="images/slider1.jpg" title="Newsflash 2" >
<div class="lof-main-item-desc">
<h3>Innovation</h3>
<h2>lorem ipsum is simply dummy text</h2>
</div>
</li>
<li>
..
</li>
</ul>
</li>
<li>
<ul class=”lof-main-subwapper”>
<li>
…
</li>
<li>
…
</li>
</ul>
</li>
</ul>
</div>
</div>
I am modifying the slider’s Script code, so far I have adder another wrappersub class & I am stuck while linking the group of images to one thumbnail i.e linking main image section’s ul with thumbnail’s li...
(function($) {
$.fn.lofJSidernews = function( settings ) {
return this.each(function() {
// get instance of the lofSiderNew.
new $.lofSidernews( this, settings );
});
}
$.lofSidernews = function( obj, settings ){
this.settings = {
direction : '',
mainItemSelector : 'li',
mainInnerItemSelector : 'li',
navInnerSelector : 'ul',
navSelector : 'li' ,
navigatorEvent : 'click',
subWrapperSelector :'.lof-main-subwrapper',
wapperSelector: '.lof-main-wapper',
interval : 4000,
innerinterval :20000,
auto : true, // whether to automatic play the slideshow
maxItemDisplay : 5,
startItem : 0,
navPosition : 'vertical',
navigatorHeight : 100,
navigatorWidth : 310,
duration : 600,
navItemsSelector : '.lof-navigator li',
navOuterSelector : '.lof-navigator-outer' ,
isPreloaded : true,
easing : 'easeInOutQuad'
}
$.extend( this.settings, settings ||{} );
this.nextNo = null;
this.previousNo = null;
this.maxWidth = this.settings.mainWidth || 600;
this.wrapper = $( obj ).find( this.settings.wapperSelector );
this.subSlides = this.wrapper.find( this.settings.mainItemSelector );
this.subwrapper = this.subslides.find(this.settings.subWrapperSelector)
this.slides = this.subwrapper.find(this.settings.mainInnerItemSelector)
if( !this.wrapper.length || !this.subslides.length ) return ;
if( !this.subwrapper.length || !this.slides.length ) return ;
if( this.settings.maxItemDisplay > this.slides.length ){
this.settings.maxItemDisplay = this.slides.length;
}
this.currentNo = isNaN(this.settings.startItem)
)||this.settings.startItem > this.slides.length?0:this.settings.startItem;
this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector );
this.navigatorItems = $( obj ).find( this.settings.navItemsSelector );
this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector );
if( this.settings.navPosition == 'horizontal' ){
this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth );
this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth );
this.navigatorOuter.height( this.settings.navigatorHeight );
} else {
this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight );
this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight );
this.navigatorOuter.width( this.settings.navigatorWidth );
}
this.navigratorStep = this.__getPositionMode( this.settings.navPosition );
this.directionMode = this.__getDirectionMode();
if( this.settings.direction == 'opacity') {
this.subwrapper.addClass( 'lof-opacity' );
$(this.slides).css('opacity',0).eq(this.currentNo).css('opacity',1);
} else {
this.subwrapper.css
({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } );
}
if( this.settings.isPreloaded ) {
this.preLoadImage( this.onComplete );
} else {
this.onComplete();
}
}
$.lofSidernews.fn = $.lofSidernews.prototype;
$.lofSidernews.fn.extend = $.lofSidernews.extend = $.extend;
$.lofSidernews.fn.extend({
startUp:function( obj, subwrapper ) {
seft = this;
this.navigatorItems.each( function(index, item ){
$(item).click( function(){
seft.jumping( index, true );
seft.setNavActive( index, item );
} );
$(item).css( {'height': seft.settings.navigatorHeight, 'width': seft.settings.navigatorWidth} );
})
this.registerWheelHandler( this.navigatorOuter, this );
this.setNavActive(this.currentNo );
if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){
this.registerButtonsControl( 'click', this.settings.buttons, this );
}
if( this.settings.auto )
this.play( this.settings.innerinterval,'next', true );
return this;
},
onComplete:function(){
setTimeout( function(){ $('.preload').fadeOut( 900 ); }, 400 ); this.startUp( );
},
preLoadImage:function( callback ){
var self = this;
var images = this.subwrapper.find( 'img' );
var count = 0;
images.each( function(index,image){
if( !image.complete ){
image.onload =function(){
count++;
if( count >= images.length ){
self.onComplete();
}
}
image.onerror =function(){
count++;
if( count >= images.length ){
self.onComplete();
}
}
}else {
count++;
if( count >= images.length ){
self.onComplete();
}
}
} );
},
navivationAnimate:function( currentIndex ) {
if (currentIndex <= this.settings.startItem
|| currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) {
this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2;
if (this.settings.startItem < 0) this.settings.startItem = 0;
if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) {
this.settings.startItem = this.slides.length-this.settings.maxItemDisplay;
}
}
Any HELP would be appreciated.
Thank you

Maybe you could try adding a slide show inside of another slider that will support more content like the Anything Slider. I've used it on projects and had some luck with adding my own custom stuff in the slides.

try adding "var" to line 238, it becomes: var seft = this;

Related

I want to disable button if any image greater then one mb using javascript

I am beginner with javascript and I am using this plugin for uploading multiple image https://www.cssscript.com/demo/multiple-image-uploader/ and just i want to disable button if any image is greater then one mb the button should be disabled Does anyone khow where i need to put this code $('#btnSubmit').prop('disabled', true); please help me ? thank u.
html view
<div class="multiple-uploader" id="multiple-uploader">
<div class="mup-msg">
<span class="mup-main-msg">click to upload images.</span>
<span class="mup-msg" id="max-upload-number">Upload up to 10 images</span>
<span class="mup-msg">Only images, pdf and psd files are allowed for upload</span>
</div>
</div>
<button type="submit" id="btnSubmit" class="btn btn-primary w-100">Save</button>
javascript
class MultipleUploader {
#multipleUploader;
#$imagesUploadInput;
constructor( multiUploaderSelector )
{
this.#multipleUploader = document.querySelector(multiUploaderSelector);
this.#$imagesUploadInput = document.createElement('input')
}
init( { maxUpload = 3 , maxSize = 1 , formSelector = 'form' , filesInpName = 'images' } = {} )
{
const form = document.querySelector(formSelector);
if (! this.#multipleUploader ) // check if the end user didnt write the multiple uploader div
throw new Error('The multiple uploader element doesnt exist');
if (! form ) // check if there is no form with this selector
throw new Error('We couldn\'t find a form with this selector: ' + formSelector);
// ensure that the form has enctype attribute with the value multipart/form-data
form.enctype = 'multipart/form-data'
if ( document.getElementById('max-upload-number') )
document.getElementById('max-upload-number').innerHTML = `Upload up to ${ maxUpload } files`;
// create multiple file input and make it hidden
this.#$imagesUploadInput.type = 'file';
this.#$imagesUploadInput.name = `${filesInpName}[]`;
this.#$imagesUploadInput.multiple = true;
this.#$imagesUploadInput.accept = "image";
this.#$imagesUploadInput.class = "image";
this.#$imagesUploadInput.style.setProperty('display','none','important');
// create multiple file input and make it hidden
// append the newly created input to the form with the help of the formSelector provided by the user
document.querySelector(formSelector).append( this.#$imagesUploadInput );
this.#multipleUploader.addEventListener("click", (e) => {
if ( e.target.className === 'multiple-uploader' || e.target.className === 'mup-msg' || e.target.className === 'mup-main-msg' )
this.#$imagesUploadInput.click() // trigger the input file to upload images
});
const self = this;
// preview the uploaded images
this.#$imagesUploadInput.addEventListener("change",function () {
if (this.files.length > 0)
{
self.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() ); // clear the previous rendered images
self.#multipleUploader.querySelector('.mup-msg').style.setProperty('display', 'none'); // hide the hint texts inside drop zone
// if the length of uploaded images greater than the images uploaded by the user, the maximum uploaded will be considered
const uploadedImagesCount = this.files.length > maxUpload ? maxUpload : this.files.length;
const unAcceptableImagesIndices = [];
for (let index = 0; index < uploadedImagesCount; index++) {
const imageSize = self.#bytesToSize( this.files[ index ].size );
const isImageSizeAcceptable = self.#checkImageSize( index , imageSize , maxSize , 'MB' );
// appended the newly created image to the multiple uploader
self.#multipleUploader.innerHTML += `
<div class="image-container" data-image-index="${ index }" id="mup-image-${ index }" data-acceptable-image="${ +isImageSizeAcceptable }" >
<div class="image-size"> ${ imageSize['size'] + ' ' + imageSize['unit'] } </div>
${ !isImageSizeAcceptable ? `<div class="exceeded-size"> greater than ${ maxSize } MB </div>` : '' }
<img src="${ URL.createObjectURL( this.files[ index ]) }" class="image-preview" alt="" />
</div>`;
if ( ! isImageSizeAcceptable )
unAcceptableImagesIndices.push( index )
}
unAcceptableImagesIndices.forEach( (index ) => self.#removeFileFromInput(index, false ))
}
});
// event for deleting uploaded images
document.addEventListener('click',function(e){
if( e.target.className === 'image-container' ) // clicked on remove pseudo element
{
const imageIndex = e.target.getAttribute(`data-image-index`)
const imageIsAcceptable = e.target.getAttribute(`data-acceptable-image`)
e.target.remove() // remove the html element from the dom
if ( +imageIsAcceptable )
self.#removeFileFromInput(imageIndex)
if ( document.querySelectorAll('.image-container').length === 0 ) // if there are no images
self.clear();
self.#reorderFilesIndices(); // reorder images indices
}
});
return this;
}
clear()
{
this.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() );
this.#multipleUploader.querySelectorAll('.mup-msg').forEach( msg => msg.style.setProperty('display', 'flex') );
this.#$imagesUploadInput.value = [];
}
#removeFileFromInput( deletedIndex )
{
// remove the delete file from input
const dt = new DataTransfer()
for (const [ index, file] of Object.entries( this.#$imagesUploadInput.files ))
{
if ( index != deletedIndex )
dt.items.add( file )
}
this.#$imagesUploadInput.files = dt.files
// remove the delete file from input
}
#reorderFilesIndices()
{
document.querySelectorAll('.image-container').forEach( ( element, index) => {
element.setAttribute('data-image-index', index.toString() );
element.setAttribute('id',`mup-image-${ index }`)
});
}
#checkImageSize( imageIndex, imageSize , maxSize )
{
return imageSize['unit'] !== 'MB' || ( imageSize['unit'] === 'MB' && ( imageSize['size'] <= maxSize ) ) ; // return true if acceptable
}
#bytesToSize(bytes)
{
const sizes = ['Bytes', 'KB', 'MB']
const i = parseInt( Math.floor(Math.log(bytes) / Math.log(1024) ), 10)
if (i === 0)
return {size: bytes , unit: sizes[i] }
else
return {size: (bytes / (1024 ** i)).toFixed(1) , unit: sizes[i] }
}
}
Your code already has all the information needed. You have unAcceptableImagesIndices that contains a list of unaccepted images.
So, all you need is just check if unAcceptableImagesIndices length is not zero and disable the button if so.
For example with something like this:
if (this.files.length > 0)
{
// your current code
document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
}

Make a slider responsive (jQuery)

I have a slider, I want to make them responsive the problem is the size of slider is into the jQuery file
sow how I can edit the code ?
code of jQuery
(function( window, $, undefined ) {
var $event = $.event, resizeTimeout;
$event.special.smartresize = {
setup: function() {
$(this).bind( "resize", $event.special.smartresize.handler );
},
teardown: function() {
$(this).unbind( "resize", $event.special.smartresize.handler );
},
handler: function( event, execAsap ) {
// Save the context
var context = this,
args = arguments;
// set correct event type
event.type = "smartresize";
if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
resizeTimeout = setTimeout(function() {
jQuery.event.handle.apply( context, args );
}, execAsap === "execAsap"? 0 : 100 );
}
};
$.fn.smartresize = function( fn ) {
return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
};
$.Slideshow = function( options, element ) {
this.$el = $( element );
/***** images ****/
// list of image items
this.$list = this.$el.find('ul.ei-slider-large');
// image items
this.$imgItems = this.$list.children('li');
// total number of items
this.itemsCount = this.$imgItems.length;
// images
this.$images = this.$imgItems.find('img:first');
/***** thumbs ****/
// thumbs wrapper
this.$sliderthumbs = this.$el.find('ul.ei-slider-thumbs').hide();
// slider elements
this.$sliderElems = this.$sliderthumbs.children('li');
// sliding div
this.$sliderElem = this.$sliderthumbs.children('li.ei-slider-element');
// thumbs
this.$thumbs = this.$sliderElems.not('.ei-slider-element');
// initialize slideshow
this._init( options );
};
$.Slideshow.defaults = {
// animation types:
// "sides" : new slides will slide in from left / right
// "center": new slides will appear in the center
animation : 'center', // sides || center
// if true the slider will automatically slide, and it will only stop if the user clicks on a thumb
autoplay : false,
// interval for the slideshow
slideshow_interval : 3000,
// speed for the sliding animation
speed : 800,
// easing for the sliding animation
easing : '',
// percentage of speed for the titles animation. Speed will be speed * titlesFactor
titlesFactor : 0.60,
// titles animation speed
titlespeed : 800,
// titles animation easing
titleeasing : '',
};
$.Slideshow.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Slideshow.defaults, options );
// set the opacity of the title elements and the image items
this.$imgItems.css( 'opacity', 0 );
this.$imgItems.find('div.ei-title > *').css( 'opacity', 0 );
// index of current visible slider
this.current = 0;
var _self = this;
// preload images
// add loading status
this.$loading = $('<div class="ei-slider-loading">Loading</div>').prependTo( _self.$el );
$.when( this._preloadImages() ).done( function() {
// hide loading status
_self.$loading.hide();
// calculate size and position for each image
_self._setImagesSize();
// configure thumbs container
_self._initThumbs();
// show first
_self.$imgItems.eq( _self.current ).css({
'opacity' : 1,
'z-index' : 10
}).show().find('div.ei-title > *').css( 'opacity', 1 );
// if autoplay is true
if( _self.options.autoplay ) {
_self._startSlideshow();
}
// initialize the events
_self._initEvents();
});
},
_preloadImages : function() {
// preloads all the large images
var _self = this,
loaded = 0;
return $.Deferred(
function(dfd) {
_self.$images.each( function( i ) {
$('<img/>').load( function() {
if( ++loaded === _self.itemsCount ) {
dfd.resolve();
}
}).attr( 'src', $(this).attr('src') );
});
}
).promise();
},
_setImagesSize : function() {
// save ei-slider's width
this.elWidth = this.$el.width();
var _self = this;
this.$images.each( function( i ) {
var $img = $(this);
imgDim = _self._getImageDim( $img.attr('src') );
$img.css({
width : imgDim.width,
height : imgDim.height,
marginLeft : imgDim.left,
marginTop : imgDim.top
});
});
},
_getImageDim : function( src ) {
var $img = new Image();
$img.src = src;
var c_w = this.elWidth,
c_h = this.$el.height(),
r_w = c_h / c_w,
i_w = $img.width,
i_h = $img.height,
r_i = i_h / i_w,
new_w, new_h, new_left, new_top;
if( r_w > r_i ) {
new_h = c_h;
new_w = c_h / r_i;
}
else {
new_h = c_w * r_i;
new_w = c_w;
}
return {
width : new_w,
height : new_h,
left : ( c_w - new_w ) / 2,
top : ( c_h - new_h ) / 2
};
},
_initThumbs : function() {
// set the max-width of the slider elements to the one set in the plugin's options
// also, the width of each slider element will be 100% / total number of elements
this.$sliderElems.css({
'width' : 100 / this.itemsCount + '%'
});
// set the max-width of the slider and show it
this.$sliderthumbs.css( 'width', this.options.thumbMaxWidth * this.itemsCount + 'px' ).show();
},
_startSlideshow : function() {
var _self = this;
this.slideshow = setTimeout( function() {
var pos;
( _self.current === _self.itemsCount - 1 ) ? pos = 0 : pos = _self.current + 1;
_self._slideTo( pos );
if( _self.options.autoplay ) {
_self._startSlideshow();
}
}, this.options.slideshow_interval);
},
// shows the clicked thumb's slide
_slideTo : function( pos ) {
// return if clicking the same element or if currently animating
if( pos === this.current || this.isAnimating )
return false;
this.isAnimating = true;
var $currentSlide = this.$imgItems.eq( this.current ),
$nextSlide = this.$imgItems.eq( pos ),
_self = this,
preCSS = {zIndex : 10},
animCSS = {opacity : 1};
// new slide will slide in from left or right side
if( this.options.animation === 'sides' ) {
preCSS.left = ( pos > this.current ) ? -1 * this.elWidth : this.elWidth;
animCSS.left = 0;
}
// titles animation
$nextSlide.find('div.ei-title > h2')
.css( 'margin-right', 50 + 'px' )
.stop()
.delay( this.options.speed * this.options.titlesFactor )
.animate({ marginRight : 0 + 'px', opacity : 1 }, this.options.titlespeed, this.options.titleeasing )
.end()
.find('div.ei-title > h3')
.css( 'margin-right', -50 + 'px' )
.stop()
.delay( this.options.speed * this.options.titlesFactor )
.animate({ marginRight : 0 + 'px', opacity : 1 }, this.options.titlespeed, this.options.titleeasing )
$.when(
// fade out current titles
$currentSlide.css( 'z-index' , 1 ).find('div.ei-title > *').stop().fadeOut( this.options.speed / 2, function() {
// reset style
$(this).show().css( 'opacity', 0 );
}),
// animate next slide in
$nextSlide.css( preCSS ).stop().animate( animCSS, this.options.speed, this.options.easing ),
// "sliding div" moves to new position
this.$sliderElem.stop().animate({
left : this.$thumbs.eq( pos ).position().left
}, this.options.speed )
).done( function() {
// reset values
$currentSlide.css( 'opacity' , 0 ).find('div.ei-title > *').css( 'opacity', 0 );
_self.current = pos;
_self.isAnimating = false;
});
},
_initEvents : function() {
var _self = this;
// window resize
$(window).on( 'smartresize.eislideshow', function( event ) {
// resize the images
_self._setImagesSize();
// reset position of thumbs sliding div
_self.$sliderElem.css( 'left', _self.$thumbs.eq( _self.current ).position().left );
});
// click the thumbs
this.$thumbs.on( 'click.eislideshow', function( event ) {
if( _self.options.autoplay ) {
clearTimeout( _self.slideshow );
_self.options.autoplay = false;
}
var $thumb = $(this),
idx = $thumb.index() - 1; // exclude sliding div
_self._slideTo( idx );
return false;
});
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.eislideshow = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'eislideshow' );
if ( !instance ) {
logError( "cannot call methods on eislideshow prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for eislideshow instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'eislideshow' );
if ( !instance ) {
$.data( this, 'eislideshow', new $.Slideshow( options, this ) );
}
});
}
return this;
};
})( window, jQuery );
How I can edit that to make them responsive ? can you give an example ?
I suggest you use something more simple (only 3 steps) instead of review this code.
Code:
Step 1: Link required files
First and most important, the jQuery library needs to be included (no need to download - link directly from Google). Next, download the package from this site and link the bxSlider CSS file (for the theme) and the bxSlider Javascript file.
<!-- jQuery library (served from Google) -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!-- bxSlider Javascript file -->
<script src="/js/jquery.bxslider.min.js"></script>
<!-- bxSlider CSS file -->
<link href="/lib/jquery.bxslider.css" rel="stylesheet" />
Step 2: Create HTML markup
Create a <ul class="bxslider"> element, with a <li> for each slide. Slides can contain images, video, or any other HTML content!
<ul class="bxslider">
<li><img src="/images/pic1.jpg" /></li>
<li><img src="/images/pic2.jpg" /></li>
<li><img src="/images/pic3.jpg" /></li>
<li><img src="/images/pic4.jpg" /></li>
</ul>
Step 3: Call the bxSlider
Call .bxslider() on <ul class="bxslider">. Note that the call must be made inside of a $(document).ready() call, or the plugin will not work!
$(document).ready(function(){
$('.bxslider').bxSlider();
});
I really believe, this will be more helpful and simple.
Credits: http://bxslider.com
Different configurations
$('.bxslider').bxSlider({
mode: 'fade',
captions: true,
pagerCustom: '#bx-pager',
adaptiveHeight: true,
slideWidth: 150
});
Don't forget to read this: http://bxslider.com/options

Using a lot of if statements, can't I just use a loop?

I am learning some javascript. At the moment I have created a working script of which I think the code can be a lot smaller/smarter then what I have created.
What I have:
I have 5 divs with 5 different ID's. The div with the ID: foundationPile has a couple of playing cards stacked. The HTML looks like this:
<div id="foundationPile">
Card pile
</div>
<div id="discardPile">
Foundation 1
</div>
<div id="discardPile2">
Foundation 2
</div>
<div id="discardPile3">
Foundation 3<
</div>
<div id="discardPile4">
Foundation 4
</div>
The code I've written does the following: when clicked on the card in the foundationPile div, there is a check if discardPile1 is empty or (if there is a card) check if the card is lower then the current card. If so, push the card to that pile, if not, check the second Pile etc etc.
To do this I have created code with a lot of if statements:
function play( card ){
if( discardPile.length ){
var lastDiscard = discardPile[discardPile.length-1];
if( card.val == lastDiscard.val+1 )
discard( card );
else if( discardPile2.length ){ //NEW START2
var lastDiscard = discardPile2[discardPile2.length-1];
if( card.val == lastDiscard.val+1 )
discard2( card );
else if( discardPile3.length ){ //NEW START3
var lastDiscard = discardPile3[discardPile3.length-1];
if( card.val == lastDiscard.val+1 )
discard3( card );
else if( discardPile4.length ){ //NEW START4
var lastDiscard = discardPile4[discardPile4.length-1];
if( card.val == lastDiscard.val+1 )
discard4( card );
}
else if( card.val == 1) {
discard4( card );
} //NEW END4
}
else if( card.val == 1) {
discard3( card );
} //NEW END 3
}
else if( card.val == 1) {
discard2( card );
} //NEW END2
}
else if( card.val == 1) { //NEW if empty ACE is allowd
discard( card );
}
}
Now isn't it possible to make my life easier by looping through the div's somehowe instead of checking each one with if statements? And if so, how to do this?
This isn't all the code, I also have the discard function. At the moment I have written 4 discard functions. These are basicly the same, the only difference is the ID's where to push the card to. I think this can be done easier too. Perhaps with just 1 discard function and replacing the nr with this or so? Also, how to do this?
These are my current discard functions:
function discard( card ){
var el = getHtml( card );
var card = cols[card.col].pop();
var col = cols[card.col]; //NEW flip kaart eronder
var flipCard = col[col.length-1]; //NEW flip de kaart eronder
if( (col.length-1) > -1 ){ //NEW
flipUp( flipCard ); //NEW
}
discardPile.push( card );
card.location = 'discardPile';
zindex( el, discardPile.length );
if( discardPile.length > 3 )
el.find('.back').removeClass('shadow');
else
el.find('.back').addClass('shadow');
el.css("transform","translate("+discardPos.left+"px, "+discardPos.top+"px)");
}
function discard2( card ){ //NEW
var el = getHtml( card );
var card = cols[card.col].pop();
var col = cols[card.col]; //NEW flip kaart eronder
var flipCard = col[col.length-1]; //NEW flip de kaart eronder
if( (col.length-1) > -1 ){ //NEW
flipUp( flipCard ); //NEW
}
discardPile2.push( card );
card.location = 'discardPile2';
zindex( el, discardPile2.length );
if( discardPile2.length > 3 )
el.find('.back').removeClass('shadow');
else
el.find('.back').addClass('shadow');
el.css("transform","translate("+discardPos2.left+"px, "+discardPos2.top+"px)");
}
function discard3( card ){ //NEW
var el = getHtml( card );
var card = cols[card.col].pop();
var col = cols[card.col]; //NEW flip kaart eronder
var flipCard = col[col.length-1]; //NEW flip de kaart eronder
if( (col.length-1) > -1 ){ //NEW
flipUp( flipCard ); //NEW
}
discardPile3.push( card );
card.location = 'discardPile3';
zindex( el, discardPile3.length );
if( discardPile3.length > 3 )
el.find('.back').removeClass('shadow');
else
el.find('.back').addClass('shadow');
el.css("transform","translate("+discardPos3.left+"px, "+discardPos3.top+"px)");
}
function discard4( card ){ //NEW
var el = getHtml( card );
var card = cols[card.col].pop();
var col = cols[card.col]; //NEW flip kaart eronder
var flipCard = col[col.length-1]; //NEW flip de kaart eronder
if( (col.length-1) > -1 ){ //NEW
flipUp( flipCard ); //NEW
}
discardPile4.push( card );
card.location = 'discardPile4';
zindex( el, discardPile4.length );
if( discardPile4.length > 3 )
el.find('.back').removeClass('shadow');
else
el.find('.back').addClass('shadow');
el.css("transform","translate("+discardPos4.left+"px, "+discardPos4.top+"px)");
}
Again, I think it is possible to simplify the code, I only have no idea how to do this. If you provide working code, please explain what you did and why so I can learn from it
Thanks a lot
UPDATE:
The divs are postioned using variable"s:
var wastePos = {
'left': x_offset * (NUM_COLS-6), //NEW
'top': 0
};
var discardPos = {
'left': x_offset * (NUM_COLS-4), //NEW
'top': 0
};
var discardPos2 = {
'left': x_offset * (NUM_COLS-3), //NEW
'top': 0
};
var discardPos3 = {
'left': x_offset * (NUM_COLS-2), //NEW
'top': 0
};
var discardPos4 = {
'left': x_offset * (NUM_COLS-1), //NEW
'top': 0
};
I am not sure how you would simplify all the if statements. However, there is definitely room for optimization in your discard function. One would suffise and pass the discardPile, discardPileName and discardPos as additional parameters.
function discard( card, myDiscardPile, discardPileName, myDiscardPos ){
var el = getHtml( card );
var card = cols[card.col].pop();
var col = cols[card.col]; //NEW flip kaart eronder
var flipCard = col[col.length-1]; //NEW flip de kaart eronder
if( (col.length-1) > -1 ){ //NEW
flipUp( flipCard ); //NEW
}
myDiscardPile.push( card );
card.location = discardPileName;
zindex( el, discardPile.length );
if( myDiscardPile.length > 3 )
el.find('.back').removeClass('shadow');
else
el.find('.back').addClass('shadow');
el.css("transform","translate("+myDiscardPos.left+"px, "+myDiscardPos.top+"px)");
}
and then you can call it as such:
discard( card, discardPile2, 'discardPile2', discardPos2);

Make JavaScript/jQuery tabs return to position on mouse out

This post is about the 3 green tabs at the top of the page (link is below). I have almost got these moving tabs how I want them, but I am not able to get the tabs to return to original position on mouse out or on a click elsewhere. Instead they move back to position after a set amount of time. How difficult is it to have them move back on mouse out?
Site is here http://theveganproject.ca/wp/
Thanks!
var sliding = 0;
var slideTime = '';
// Set is sliding value
function setSliding(a_ISliding){
sliding = a_ISliding;
}
// Get is sliding value
function getSliding(){
return sliding;
}
// Carry out accordian styled effect
function accordion(evt) {
el = Event.element(evt);
var eldown = getNextSibling(el);
// If element is visible do nothing
if ($('visible') == el) {
return;
}
if ($('visible')) {
if( getSliding() == 1 ){
return false;
}
var elup = getNextSibling($('visible'));
setSliding( 1 );
parellelSlide( elup, eldown );
$('visible').id = '';
}
else{
setSliding( 1 );
singleSlide( eldown );
}
el.id = 'visible';
}
// Setup accordian initial state
function init() {
var bodyPanels = document.getElementsByClassName('panel_body');
var panels = document.getElementsByClassName('panel');
var noPanels = panels.length;
var percentageWidth = 100 / noPanels;
var position = 0;
// Loop through body panels and panels applying required styles and adding event listeners
for (i = 0; i < bodyPanels.length; i++) {
bodyPanels[i].hide();
panels[i].style.width = percentageWidth + '%';
panels[i].style.position = 'absolute';
panels[i].style.left = position + '%';
Event.observe(panels[i].getElementsByTagName('h3')[0], 'mouseover', accordion, false);
Event.observe(panels[i].getElementsByTagName('h3')[0], 'mousemove', accordion, false);
Event.observe(document.body, 'mousemove', resetIdle, false);
position += percentageWidth;
}
if( $('visible') ){
// Set panel with id of visible to be initial displayed
var vis = $('visible').parentNode.id+'-body';
$(vis).show();
}
setIdle();
}
// Next sibling method to work around firefox issues
function getNextSibling(startBrother){
var endBrother=startBrother.nextSibling;
while(endBrother.nodeType!=1){
endBrother = endBrother.nextSibling;
}
return endBrother;
}
function parellelSlide( elup, eldown ){
new Effect.Parallel(
[
new Effect.SlideUp(elup),
new Effect.SlideDown(eldown)
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
}
function singleSlide( eldown ){
new Effect.Parallel(
[
new Effect.SlideDown(eldown)
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
}
function resetTabs(){
var resetEl = getNextSibling( $('visible') );
setSliding( 1 );
new Effect.Parallel(
[
new Effect.SlideUp( resetEl )
], {
duration: 0.3,
afterFinish: function() { setSliding( 0 );}
});
$('visible').id = '';
}
function resetIdle(){
if( $('visible') ){
window.clearTimeout( slideTime );
slideTime = window.setTimeout( "resetTabs()", 1000 );
}
}
function setIdle(){
if( $('visible') ){
slideTime = window.setTimeout( "resetTabs()", 1000 );
}
}
Event.observe(window, 'load', init, false);

Autoscrolling slide javascript

I have This javascript code for a slider that I downloaded , and can't figure out how to make it auto scrolling !!
I actually downloaded this code from http://tympanus.net/Tutorials/FullscreenSlitSlider/index2.html
It actually don't contain a next button so i can add an interval like the other sliders :(
$(function() {
var Page = (function() {
var $nav = $( '#nav-dots > span' ),
slitslider = $( '#slider' ).slitslider( {
onBeforeChange : function( slide, pos ) {
$nav.removeClass( 'nav-dot-current' );
$nav.eq( pos ).addClass( 'nav-dot-current' );
}
} ),
init = function() {
initEvents();
setInterval(initEvents,1000);
},
initEvents = function() {
$nav.each( function( i ) {
$( this ).on( 'click', function( event ) {
var $dot = $( this );
if( !slitslider.isActive() ) {
$nav.removeClass( 'nav-dot-current' );
$dot.addClass( 'nav-dot-current' );
}
slitslider.jump( i + 1 );
return false;
} );
} );
};
return { init : init };
})();
Page.init();
});
Like it says in the docs (Google is helpful):
slitslider = $( '#slider' ).slitslider({
autoplay : true
});
should do it.
If you don't want to read the whole thing, here's a short list of common config options:
$.Slitslider.defaults = {
// transitions speed
speed : 800,
// if true the item's slices will also animate the opacity value
optOpacity : false,
// amount (%) to translate both slices - adjust as necessary
translateFactor : 230,
// maximum possible angle
maxAngle : 25,
// maximum possible scale
maxScale : 2,
// slideshow on / off
autoplay : false,
// keyboard navigation
keyboard : true,
// time between transitions
interval : 4000,
// callbacks
onBeforeChange : function( slide, idx ) { return false; },
onAfterChange : function( slide, idx ) { return false; }
};

Categories

Resources