How could I automate a JavaScript function to autoplay a slideshow? - javascript

I have a div box gallery with some pictures on background and 2 lateral buttons prev and next. On click of a button the JavaScript show the next or previous picture, that's ok but I wish also to make this transition automatic using an interval time to show the next picture. How can I proceed?
This is my HTML:
<div id="boxgallery" class="boxgallery" data-effect="effect-1">
<div class="panel"><img src="img/1.jpg" alt="Image 1"/></div>
<div class="panel"><img src="img/2.jpg" alt="Image 2"/></div>
<div class="panel"><img src="img/3.jpg" alt="Image 3"/></div>
<div class="panel"><img src="img/4.jpg" alt="Image 4"/></div>
</div>
This is my JavaScript function:
// goto next or previous slide
BoxesFx.prototype._navigate = function( dir ) {
if( this.isAnimating ) return false;
this.isAnimating = true;
var self = this, currentPanel = this.panels[ this.current ];
if( dir === 'next' ) {
this.current = this.current < this.panelsCount - 1 ? this.current + 1 : 0;
}
else {
this.current = this.current > 0 ? this.current - 1 : this.panelsCount - 1;
}
// next panel to be shown
var nextPanel = this.panels[ this.current ];
// add class active to the next panel to trigger its animation
classie.add( nextPanel, 'active' );
// apply the transforms to the current panel
this._applyTransforms( currentPanel, dir );
// let´s track the number of transitions ended per panel
var cntTransTotal = 0,
// transition end event function
onEndTransitionFn = function( ev ) {
if( ev && !classie.has( ev.target, 'bg-img' ) ) return false;
// return if not all panel transitions ended
++cntTransTotal;
if( cntTransTotal < self.panelsCount ) return false;
if( support.transitions ) {
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
// remove current class from current panel and add it to the next one
classie.remove( currentPanel, 'current' );
classie.add( nextPanel, 'current' );
// reset transforms for the currentPanel
self._resetTransforms( currentPanel );
// remove class active
classie.remove( nextPanel, 'active' );
self.isAnimating = false;
};
if( support.transitions ) {
currentPanel.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}

Ok I looked up BoxesFx. look for this code:
BoxesFx.prototype._initEvents = function() {
var self = this, navctrls = this.nav.children;
// previous action
navctrls[0].addEventListener( 'click', function() { self._navigate('prev') } );
// next action
navctrls[1].addEventListener( 'click', function() { self._navigate('next') } );
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
}
Change it to:
BoxesFx.prototype._initEvents = function() {
var self = this, navctrls = this.nav.children;
// previous action
navctrls[0].addEventListener( 'click', function() { self.automate('prev',3000) } );
// next action
navctrls[1].addEventListener( 'click', function() { self.automate('next',3000) } );
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
window.onload = function () {
self.automate('next',3000);
}
}
Where "3000" is the milliseconds to show a slide, including any animation time of the slide.

just add a couple more methods, make new buttons to call them. the property "auto" will not be zero when it's running, which may be handy later.
BoxesFx.prototype.auto = 0;
BoxesFx.prototype.automate = function(dir,time){
var scope = this;
this.auto = setInterval(function(){
scope._navigate(dir);
},time);
}
BoxesFx.prototype.stopAutomate = function(){
clearInterval(this.auto);
}

You can use javascripts setInterval() function:
http://www.w3schools.com/jsref/met_win_setinterval.asp
Edit:
You will have to call the setInterval() function when your page has loaded. For example you could use the onload-Event of your body tag:
HTML
<body onload="startAutoplay()">
// your slider and content
</body>
Javascript
function startAutoplay(){
setInterval(function(){
// call your next() or previous() function here
}, 3000);
}
This will set the timer to 3 seconds

Related

Trying to hack accordian script so they are closed by default

So, I have a theme with an accordian option in it - however the accordian opens the first item. I would like it to be closed - I know it's controlled with JS which is not my forte.
I can see the JS adds 'open' and 'active' classes into the area but I can't seem to see how it works out the first one.
Here is the code.
function handleAccordionBox(){
$('[data-norebro-accordion]').each(function(){
var accordion = $(this);
var titles = $(this).find('div.title');
var items = $(this).find('.item');
var contents = $(this).find('.content');
var iconOpened = 'ion-minus', iconClosed = 'ion-plus';
var isOutline = $(this).hasClass('outline');
var toggle = function( num ){
var opened = accordion.find('.open');
var content = contents.eq( num );
// If not active
if( !items.eq( num ).hasClass('active') ){
// Activate this item
items.removeClass('active');
items.eq( num ).addClass('active');
setTimeout(function(){
content.css('height', '').addClass('no-transition open'); // Open new content
var height = content.outerHeight() + 'px'; // Save heights
content.removeClass('no-transition open').css( 'height', (isOutline) ? '0px' : '6px' ); // Close new content
setTimeout(function(){
opened.removeClass('open no-transition').css( 'height', (isOutline) ? '0px' : '6px' ); // Close old content
content.addClass('open').css( 'height', height ); // Open new content
// Change titles
titles.find('.control span').removeClass( iconOpened ).addClass( iconClosed );
titles.eq(num).find('.control span').removeClass( iconClosed ).addClass( iconOpened );
}, 30);
}, 30);
}
else {
items.removeClass('active');
opened.removeClass('open no-transition').css( 'height', (isOutline) ? '0px' : '6px' );
titles.find('.control span').removeClass( iconOpened ).addClass( iconClosed );
};
};
titles.each(function(i){
$(this).on('click', function(){
toggle( i );
});
});
toggle( $(this).attr('data-norebro-accordion') || 0 );
this.accordionToggle = toggle;
});
};
function handleAccordionBoxSize(){
$('[data-norebro-accordion]').each(function(){
var content = $(this).find('.content.open');
var wrap = content.find('.wrap');
content.css('height', wrap.outerHeight() + 'px');
});
};`
The key line is this one:
toggle( $(this).attr('data-norebro-accordion') || 0 );
toggle is the function that actually opens and closes the menu. Once everything has been declared, it's called once here, for either the element with the data-norebro-accordion attribute, or, if that's not declared, the first element (0)
If you want everything closed by default, then just comment that line:
// toggle( $(this).attr('data-norebro-accordion') || 0 );

WordPress dynamic paging - url conflict

I have downloaded theme which is static html & css template, now I'm trying to convert into wordpress dynamic template. the issue is that the static template is one page website and have some section within it. Scrolling to these section is done by jquery function that uses url to scroll to that specific section like this:
mysite.com/?page=about
so its conflict with main wordpress dynamic paging the website doesn't scroll to that specific section any more.
I've tried to change jquery code in my template but I couldn't fix it, is there a way to change the default wordpress setting in order to stop this conflict?
here the JS code :
(function(window, undefined) {
"use strict";
var Page = (function() {
var $container = $( '#container' ),
// the scroll container that wraps the articles
$scroller = $container.find( 'div.content-scroller' ),
$menu = $container.find( 'aside' ),
// menu links
$links = $menu.find( 'nav > a' ),
$articles = $container.find( 'div.content-wrapper > article' ).not(".noscroll"),
// button to scroll to the top of the page
// only shown when screen size < 715
$toTop = $container.find( 'a.totop-link' ),
// the browser nhistory object
History = window.History,
// animation options
animation = { speed : 800, easing : 'easeInOutExpo' },
// jScrollPane options
scrollOptions = { verticalGutter : 0, hideFocus : true },
// init function
init = function() {
// initialize the jScrollPane on both the menu and articles
_initCustomScroll();
// initialize some events
_initEvents();
// sets some css properties
_layout();
// jumps to the respective chapter
// according to the url
_goto();
},
_initCustomScroll = function() {
// Only add custom scroll to articles if screen size > 715.
// If not the articles will be expanded
if( $(window).width() > 767 ) {
$articles.jScrollPane( scrollOptions );
}
// add custom scroll to menu
$menu.children( 'nav' ).jScrollPane( scrollOptions );
},
_goto = function( chapter ) {
// get the url from history state (e.g. chapter=3) and extract the chapter number
var chapter = chapter || History.getState().url.queryStringToJSON().page,
isHome = ( chapter === undefined ),
// we will jump to the introduction chapter if theres no chapter
$article = $( chapter ? '#' + 'chapter' + chapter : '#' + 'introduction' );
$('#link_introduction').removeClass('active');
$('#link_about').removeClass('active');
$('#link_skills').removeClass('active');
$('#link_experience').removeClass('active');
$('#link_education').removeClass('active');
$('#link_portfolio').removeClass('active');
$('#link_contact').removeClass('active');
$('#link_'+chapter).addClass('active');
if( $article.length ) {
// left / top of the element
var left = $article.position().left,
top = $article.position().top,
// check if we are scrolling down or left
// is_v will be true when the screen size < 715
is_v = ( $(document).height() - $(window).height() > 0 ),
// animation parameters:
// if vertically scrolling then the body will animate the scrollTop,
// otherwise the scroller (div.content-scroller) will animate the scrollLeft
param = ( is_v ) ? { scrollTop : (isHome) ? top : top + $menu.outerHeight( true ) } : { scrollLeft : left },
$elScroller = ( is_v ) ? $( 'html, body' ) : $scroller;
$elScroller.stop().animate( param, animation.speed, animation.easing, function() {
// active class for selected chapter
//$articles.removeClass( 'content-active' );
//$article.addClass( 'content-active' );
} );
}
},
_saveState = function( chapter ) {
// adds a new state to the history object
// this will trigger the statechange on the window
if( History.getState().url.queryStringToJSON().page !== chapter ) {
History.pushState( null, null, '?page=' + chapter );
$('#link_introduction').removeClass('active');
$('#link_about').removeClass('active');
$('#link_skills').removeClass('active');
$('#link_experience').removeClass('active');
$('#link_education').removeClass('active');
$('#link_portfolio').removeClass('active');
$('#link_contact').removeClass('active');
$('#link_'+chapter).addClass('active');
}
},
_layout = function() {
// control the overflow property of the scroller (div.content-scroller)
var windowWidth = $(window).width();
var isipad = navigator.userAgent.toLowerCase().indexOf("ipad");
if(isipad > -1)
{
//$('.totop-link').hide();
switch( true ) {
case ( windowWidth <= 768 ) : $scroller.scrollLeft( 0 ).css( 'overflow', 'visible' ); break;
case ( windowWidth <= 1024 ): $scroller.css( 'overflow-x', 'hidden' ); break;
case ( windowWidth > 1024 ) : $scroller.css( 'overflow', 'hidden' ); break;
};
}
else
{
switch( true ) {
case ( windowWidth <= 768 ) : $scroller.scrollLeft( 0 ).css( 'overflow', 'visible' ); break;
case ( windowWidth <= 1024 ): $scroller.css( 'overflow-x', 'hidden' ); break;
case ( windowWidth > 1024 ) : $scroller.css( 'overflow', 'hidden' ); break;
};
}
},
_initEvents = function() {
_initWindowEvents();
_initMenuEvents();
_initArticleEvents();
},
_initWindowEvents = function() {
$(window).on({
// when resizing the window we need to reinitialize or destroy the jScrollPanes
// depending on the screen size
'smartresize' : function( event ) {
var isipad = navigator.userAgent.toLowerCase().indexOf("ipad");
var ismobile = navigator.userAgent.toLowerCase().indexOf("mobile");
if(isipad > -1 || ismobile > -1 )
{
}
else
{
_layout();
$('article.content').not(".noscroll").each( function() {
var $article = $(this),
aJSP = $article.data( 'jsp' );
if( $(window).width() > 767 ) {
( aJSP === undefined ) ? $article.jScrollPane( scrollOptions ) : aJSP.reinitialise();
_initArticleEvents();
}
else {
// destroy article's custom scroll if screen size <= 715px
if( aJSP !== undefined )
aJSP.destroy();
$container.off( 'click', 'article.content' );
}
});
var nJSP = $menu.children( 'nav' ).data( 'jsp' );
nJSP.reinitialise();
// jumps to the current chapter
_goto();
}
},
// triggered when the history state changes - jumps to the respective chapter
'statechange' : function( event ) {
_goto();
}
});
},
_initMenuEvents = function() {
// when we click a menu link we check which chapter the link refers to,
// and we save the state on the history obj.
// the statechange of the window is then triggered and the page/scroller scrolls to the
// respective chapter's position
$links.on( 'click', function( event ) {
var href = $(this).attr('href'),
chapter = ( href.search(/chapter/) !== -1 ) ? href.substring(8) : 0;
_saveState( chapter );
if (href.indexOf("#") != -1)
return false;
else
return true;
});
// scrolls to the top of the page.
// this button will only be visible for screen size < 715
$toTop.on( 'click', function( event ) {
$( 'html, body' ).stop().animate( { scrollTop : 0 }, animation.speed, animation.easing );
return false;
});
},
_initArticleEvents = function() {
// when we click on an article we check which chapter the article refers to,
// and we save the state on the history obj.
// the statechange of the window is then triggered and the page/scroller scrolls to the
// respective chapter's position
if($(window).width()>768)
{
$container.on( 'click', 'article.content', function( event ) {
var id = $(this).attr('id'),
chapter = ( id.search(/chapter/) !== -1 ) ? id.substring(7) : 0;
_saveState( chapter );
//return false;
});
}
};
return { init : init };
})();
Page.init();
})(window);

How to reload a page on slider navigation click

I've a problem with this slider: I want to make it slider reload the page after I'm clicking the link "next/prev" in the slider or hte thumbnail.
Can someone help me ?
$(function() {
// ======================= imagesLoaded Plugin ===============================
// https://github.com/desandro/imagesloaded
// $('#my-container').imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
// callback function gets image collection as argument
// this is the container
// original: mit license. paul irish. 2010.
// contributors: Oren Solomianik, David DeSandro, Yiannis Chatzikonstantinou
$.fn.imagesLoaded = function( callback ) {
var $images = this.find('img'),
len = $images.length,
_this = this,
blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
function triggerCallback() {
callback.call( _this, $images );
}
function imgLoaded() {
if ( --len <= 0 && this.src !== blank ){
setTimeout( triggerCallback );
$images.off( 'load error', imgLoaded );
}
}
if ( !len ) {
triggerCallback();
}
$images.on( 'load error', imgLoaded ).each( function() {
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined){
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
this.src = blank;
this.src = src;
}
});
return this;
};
// gallery container
var $rgGallery = $('#rg-gallery'),
// carousel container
$esCarousel = $rgGallery.find('div.es-carousel-wrapper'),
// the carousel items
$items = $esCarousel.find('ul > li'),
// total number of items
itemsCount = $items.length;
Gallery = (function() {
// index of the current item
var current = 0,
// mode : carousel || fullview
mode = 'carousel',
// control if one image is being loaded
anim = false,
init = function() {
// (not necessary) preloading the images here...
$items.add('<img src="images/ajax-loader.gif"/><img src="images/black.png"/>').imagesLoaded( function() {
// add options
_addViewModes();
// add large image wrapper
_addImageWrapper();
// show first image
_showImage( $items.eq( current ) );
});
// initialize the carousel
if( mode === 'carousel' )
_initCarousel();
},
_initCarousel = function() {
// we are using the elastislide plugin:
// http://tympanus.net/codrops/2011/09/12/elastislide-responsive-carousel/
$esCarousel.show().elastislide({
imageW : 65,
onClick : function( $item ) {
if( anim ) return false;
anim = true;
// on click show image
_showImage($item);
// change current
current = $item.index();
}
});
// set elastislide's current to current
$esCarousel.elastislide( 'setCurrent', current );
},
_addViewModes = function() {
// top right buttons: hide / show carousel
var $viewfull = $(''),
$viewthumbs = $('');
$rgGallery.prepend( $('<div class="rg-view"/>').append( $viewfull ).append( $viewthumbs ) );
$viewfull.on('click.rgGallery', function( event ) {
if( mode === 'carousel' )
$esCarousel.elastislide( 'destroy' );
$esCarousel.hide();
$viewfull.addClass('rg-view-selected');
$viewthumbs.removeClass('rg-view-selected');
mode = 'fullview';
return false;
});
$viewthumbs.on('click.rgGallery', function( event ) {
_initCarousel();
$viewthumbs.addClass('rg-view-selected');
$viewfull.removeClass('rg-view-selected');
mode = 'carousel';
return false;
});
if( mode === 'fullview' )
$viewfull.trigger('click');
},
_addImageWrapper= function() {
// adds the structure for the large image and the navigation buttons (if total items > 1)
// also initializes the navigation events
$('#img-wrapper-tmpl').tmpl( {itemsCount : itemsCount} ).prependTo( $rgGallery );
if( itemsCount > 1 ) {
// addNavigation
var $navPrev = $rgGallery.find('a.rg-image-nav-prev'),
$navNext = $rgGallery.find('a.rg-image-nav-next'),
$imgWrapper = $rgGallery.find('div.rg-image');
$navPrev.on('click.rgGallery', function( event ) {
_navigate( 'left' );
return false;
});
$navNext.on('click.rgGallery', function( event ) {
_navigate( 'right' );
return false;
});
// add touchwipe events on the large image wrapper
$imgWrapper.touchwipe({
wipeLeft : function() {
_navigate( 'right' );
},
wipeRight : function() {
_navigate( 'left' );
},
preventDefaultEvents: false
});
$(document).on('keyup.rgGallery', function( event ) {
if (event.keyCode == 39)
_navigate( 'right' );
else if (event.keyCode == 37)
_navigate( 'left' );
});
}
},
_navigate = function( dir ) {
// navigate through the large images
if( anim ) return false;
anim = true;
if( dir === 'right' ) {
if( current + 1 >= itemsCount )
current = 0;
else
++current;
}
else if( dir === 'left' ) {
if( current - 1 < 0 )
current = itemsCount - 1;
else
--current;
}
_showImage( $items.eq( current ) );
},
_showImage = function( $item ) {
// shows the large image that is associated to the $item
var $loader = $rgGallery.find('div.rg-loading').show();
$items.removeClass('selected');
$item.addClass('selected');
var $thumb = $item.find('img'),
largesrc = $thumb.data('large'),
title = $thumb.data('description');
$('<img/>').load( function() {
$rgGallery.find('div.rg-image').empty().append('<img src="' + largesrc + '"/>');
if( title )
$rgGallery.find('div.rg-caption').show().children('p').empty().text( title );
$loader.hide();
if( mode === 'carousel' ) {
$esCarousel.elastislide( 'reload' );
$esCarousel.elastislide( 'setCurrent', current );
}
anim = false;
}).attr( 'src', largesrc );
},
addItems = function( $new ) {
$esCarousel.find('ul').append($new);
$items = $items.add( $($new) );
itemsCount = $items.length;
$esCarousel.elastislide( 'add', $new );
};
return {
init : init,
addItems : addItems
};
})();
Gallery.init();
/*
Example to add more items to the gallery:
var $new = $('<li><img src="images/thumbs/1.jpg" data-large="images/1.jpg" alt="image01" data-description="From off a hill whose concave womb reworded" /></li>');
Gallery.addItems( $new );
*/
});
Here is the code for the view
<noscript>
<style>
.es-carousel ul{
display:block;
}
</style>
</noscript>
<script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">
<div class="rg-image-wrapper">
{{if itemsCount > 1}}
<div class="rg-image-nav">
Previous Image
Next Image
</div>
{{/if}}
<div class="rg-image"></div>
<div class="rg-loading"></div>
<div class="rg-caption-wrapper">
<div class="rg-caption" style="display:none;">
<p></p>
</div>
</div>
</div>
</script>
</head>
<body>
<div class="container">
<div class="header">
<span>« Previous Demo: </span>Elastislide
<span class="right_ab">
Images by Shermeee
CC BY 2.0
<strong>back to the Codrops post</strong>
</span>
<div class="clr"></div>
</div><!-- header -->
<div class="content">
<h1>Responsive Image Gallery <span>A jQuery image gallery with a thumbnail carousel</span></h1>
<div id="rg-gallery" class="rg-gallery">
<div class="rg-thumbs">
<!-- Elastislide Carousel Thumbnail Viewer -->
<div class="es-carousel-wrapper">
<div class="es-nav">
<span class="es-nav-prev">Previous</span>
<span class="es-nav-next">Next</span>
</div>
<div class="es-carousel">
<ul>
<li><img src="images/thumbs/1.jpg" data-large="images/1.jpg" alt="image01" data-description="From off a hill whose concave womb reworded" /></li>
</ul>
</div>
</div>
<!-- End Elastislide Carousel Thumbnail Viewer -->
</div><!-- rg-thumbs -->
</div><!-- rg-gallery -->
</div><!-- content -->
</div><!-- container -->
Sorry if my English is not so good, but I really need to solve this.
Well I have no idea why would you do that, but if you want to reload the page every time you click on the Next and Prev buttons, including the Thumbnail you could do something like this:
$(document).ready(function() {
$('.es-nav span, .es-carousel img').on('click', function() {
location.reload();
});
});
This will reload the page when you click on the nav or an image in the thumbnail area.

javascript forEach - add addEventListener on all buttons

I'm not so skilled with javascript so I'm looking for a little help.
I'm using a script found on Codrops (3D Grid Effect - http://tympanus.net/Development/3DGridEffect/).
All is working fine as expected but I'm trying to "modify" it for my needs.
Basically, I want to trigger the "effect" NOT clicking on the whole container but on a button placed inside it.
The structure I'm using is:
<section class="grid3d vertical" id="grid3d">
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
<div class="content">
<div>
<div class="dummy-img"></div>
<p class="dummy-text">Some text</p>
<p class="dummy-text">Some more text</p>
</div>
<div>
<!-- ... -->
</div>
<!-- ... -->
<span class="loading"></span>
<span class="icon close-content"></span>
</div>
</section>
<script>
new grid3D( document.getElementById( 'grid3d' ) );
</script>
And the script (js) is
/**
* grid3d.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
function grid3D( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
// any options you might want to configure
grid3D.prototype.options = {};
grid3D.prototype._init = function() {
// grid wrapper
this.gridWrap = this.el.querySelector( 'div.grid-wrap' );
// grid element
this.grid = this.gridWrap.querySelector( 'div.grid' );
// main grid items
this.gridItems = [].slice.call( this.grid.children );
// default sizes for grid items
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
// content
this.contentEl = this.el.querySelector( 'div.content' );
// content items
this.contentItems = [].slice.call( this.contentEl.children );
// close content cross
this.close = this.contentEl.querySelector( 'span.close-content' );
// loading indicator
this.loader = this.contentEl.querySelector( 'span.loading' );
// support: support for pointer events, transitions and 3d transforms
this.support = support.pointerevents && support.csstransitions && support.csstransforms3d;
// init events
this._initEvents();
};
grid3D.prototype._initEvents = function() {
var self = this;
// open the content element when clicking on the main grid items
this.gridItems.forEach( function( item, idx ) {
item.addEventListener( 'click', function() {
self._showContent( idx );
} );
} );
// close the content element
this.close.addEventListener( 'click', function() {
self._hideContent();
} );
if( this.support ) {
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
// trick to prevent scrolling when animation is running (opening only)
// this prevents that the back of the placeholder does not stay positioned in a wrong way
window.addEventListener( 'scroll', function() {
if ( self.isAnimating ) {
window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
}
else {
self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
// change the grid perspective origin as we scroll the page
self._scrollHandler();
}
});
}
};
// creates placeholder and animates it to fullscreen
// in the end of the animation the content is shown
// a loading indicator will appear for 1 second to simulate a loading period
grid3D.prototype._showContent = function( pos ) {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
var self = this,
loadContent = function() {
// simulating loading...
setTimeout( function() {
// hide loader
classie.removeClass( self.loader, 'show' );
// in the end of the transition set class "show" to respective content item
classie.addClass( self.contentItems[ pos ], 'show' );
}, 1000 );
// show content area
classie.addClass( self.contentEl, 'show' );
// show loader
classie.addClass( self.loader, 'show' );
classie.addClass( document.body, 'noscroll' );
self.isAnimating = false;
};
// if no support just load the content (simple fallback - no animation at all)
if( !this.support ) {
loadContent();
return false;
}
var currentItem = this.gridItems[ pos ],
itemContent = currentItem.innerHTML;
// create the placeholder
this.placeholder = this._createPlaceholder(itemContent );
// set the top and left of the placeholder to the top and left of the clicked grid item (relative to the grid)
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
// append placeholder to the grid
this.grid.appendChild( this.placeholder );
// and animate it
var animFn = function() {
// give class "active" to current grid item (hides it)
classie.addClass( currentItem, 'active' );
// add class "view-full" to the grid-wrap
classie.addClass( self.gridWrap, 'view-full' );
// set width/height/left/top of placeholder
self._resizePlaceholder();
var onEndTransitionFn = function( ev ) {
if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
this.removeEventListener( transEndEventName, onEndTransitionFn );
loadContent();
};
self.placeholder.addEventListener( transEndEventName, onEndTransitionFn );
};
setTimeout( animFn, 25 );
};
grid3D.prototype._hideContent = function() {
var self = this,
contentItem = this.el.querySelector( 'div.content > .show' ),
currentItem = this.gridItems[ this.contentItems.indexOf( contentItem ) ];
classie.removeClass( contentItem, 'show' );
classie.removeClass( this.contentEl, 'show' );
// without the timeout there seems to be some problem in firefox
setTimeout( function() { classie.removeClass( document.body, 'noscroll' ); }, 25 );
// that's it for no support..
if( !this.support ) return false;
classie.removeClass( this.gridWrap, 'view-full' );
// reset placeholder style values
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
this.placeholder.style.width = this.itemSize.width + 'px';
this.placeholder.style.height = this.itemSize.height + 'px';
var onEndPlaceholderTransFn = function( ev ) {
this.removeEventListener( transEndEventName, onEndPlaceholderTransFn );
// remove placeholder from grid
self.placeholder.parentNode.removeChild( self.placeholder );
// show grid item again
classie.removeClass( currentItem, 'active' );
};
this.placeholder.addEventListener( transEndEventName, onEndPlaceholderTransFn );
}
// function to create the placeholder
/*
<div class="placeholder">
<div class="front">[content]</div>
<div class="back"></div>
</div>
*/
grid3D.prototype._createPlaceholder = function( content ) {
var front = document.createElement( 'div' );
front.className = 'front';
front.innerHTML = content;
var back = document.createElement( 'div' );
back.className = 'back';
back.innerHTML = ' ';
var placeholder = document.createElement( 'div' );
placeholder.className = 'placeholder';
placeholder.appendChild( front );
placeholder.appendChild( back );
return placeholder;
};
grid3D.prototype._scrollHandler = function() {
var self = this;
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { self._scrollPage(); }, 60 );
}
};
// changes the grid perspective origin as we scroll the page
grid3D.prototype._scrollPage = function() {
var perspY = scrollY() + getViewportH() / 2;
this.gridWrap.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.MozPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.perspectiveOrigin = '50% ' + perspY + 'px';
this.didScroll = false;
};
grid3D.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resizePlaceholder();
self._scrollPage();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 50 );
}
grid3D.prototype._resizePlaceholder = function() {
// need to recalculate all these values as the size of the window changes
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
if( this.placeholder ) {
// set the placeholders top to "0 - grid offsetTop" and left to "0 - grid offsetLeft"
this.placeholder.style.left = Number( -1 * ( this.grid.offsetLeft - scrollX() ) ) + 'px';
this.placeholder.style.top = Number( -1 * ( this.grid.offsetTop - scrollY() ) ) + 'px';
// set the placeholders width to windows width and height to windows height
this.placeholder.style.width = getViewportW() + 'px';
this.placeholder.style.height = getViewportH() + 'px';
}
}
// add to global namespace
window.grid3D = grid3D;
})( window );
Now, I'm aware that the "crucial" portion of the code where I have to look is:
// open the content element when clicking on the main grid items
this.gridItems.forEach( function(item, idx ) {
item.addEventListener( 'click', function() {
item._showContent( idx ); } ); } );
So, my question again: how to trigger the event when the div (button) class "click-me" is clicked on every "boxes"?
Thanks to all in advance (i'm struggling with it for hours...)
Have a look at the example here,
http://jsfiddle.net/y0mbn94n/
I have added some intialisation to get your particular classes
// get grid buttons and then make an iterable array out of them
this.gridButtons = this.el.querySelectorAll('button.btn-click-me');
this.gridButtonItems = [].slice.call(this.gridButtons);
and changed the function which iterates and adds a listener.
// open the content element when clicking on the buttonsItems
this.gridButtonItems.forEach(function (item, idx) {
item.addEventListener('click', function () {
self._showContent(idx);
});
});
If you want to call a callback function when the user clicks on a button:
var buttons = document.querySelectorAll('.btn-click-me');
for (var i = 0; i < buttons.length; i++) {
var self = buttons[i];
self.addEventListener('click', function (event) {
// prevent browser's default action
event.preventDefault();
// call your awesome function here
MyAwesomeFunction(this); // 'this' refers to the current button on for loop
}, false);
}
with the structure given
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
you just have to change the line you've said to:
item.children[0].addEventListener( 'click', function() {
as the btn-click-me would be the first child of each item.
If you would like a more generic solution you could use:
item.getElementsByClassName('btn-click-me')[0].addEventListener( 'click', function() {
where bnt-click-me would be the class of the button that you would want to bind the click event. Notice that [0] so you can select the very first item of the array, as getElementsByClassName will return one, even if there's only one element.
But if you say you're just starting with javascript y really recommend you using jQuery, it's selectors are much easier than vanilla javascript.

URL Renaming via JavaScript

I’m developing a website based on this tutorial and would like to rename the URLs from /?chapter=# to their respective navigation names, e.g. /work, /about, /services etc.
index.php:
<aside id="menu">
<div id="scroll">
<nav>
<ul>
<li>Work</li>
<li>About</li>
<li>Services</li>
<li>Blog <!-- Coming Soon... --> </li>
<li>Contact</li>
</ul>
</nav>
</div> <!-- #scroll -->
</aside> <!-- #menu -->
...
...
<div class="content-scroller">
<div class="content-wrapper">
<article class="content" id="introduction">
<div class="inner">
...
...
<article class="content" id="chapter1">
<div class="inner">
...
...
jquery.page.js:
(function(window, undefined) {
var Page = (function() {
var $container = $( '#container' ),
// the scroll container that wraps the articles
$scroller = $container.find( 'div.content-scroller' ),
$menu = $container.find( 'aside' ),
// menu links
$links = $menu.find( 'a' ),
$articles = $container.find( 'div.content-wrapper > article' ),
// button to scroll to the top of the chapter
// only shown when screen size < 960
$toTop = $container.find( 'a.totop-link' ),
// the browser nhistory object
History = window.History,
// animation options
animation = { speed : 800, easing : 'easeInOutExpo' },
// jScrollPane options
scrollOptions = { verticalGutter : 0, hideFocus : true },
// init function
init = function() {
// initialize the jScrollPane on both the menu and articles
_initCustomScroll();
// initialize some events
_initEvents();
// sets some css properties
_layout();
// jumps to the respective chapter
// according to the url
_goto();
},
_initCustomScroll = function() {
// Only add custom scroll to articles if screen size > 960.
// If not the articles will be expanded
if( $(window).width() > 960 ) {
$articles.jScrollPane( scrollOptions );
}
// add custom scroll to menu
$menu.children( '#scroll' ).jScrollPane( scrollOptions );
},
_goto = function( chapter ) {
// get the url from history state (e.g. chapter=3) and extract the chapter number
var chapter = chapter || History.getState().url.queryStringToJSON().chapter,
isHome = ( chapter === undefined ),
// we will jump to the introduction chapter if theres no chapter
$article = $( chapter ? '#' + 'chapter' + chapter : '#' + 'introduction' );
if( $article.length ) {
// left / top of the element
var left = $article.position().left,
top = $article.position().top,
// check if we are scrolling down or left
// is_v will be true when the screen size < 960
is_v = ( $(document).height() - $(window).height() > 0 ),
// animation parameters:
// if vertically scrolling then the body will animate the scrollTop,
// otherwise the scroller (div.content-scroller) will animate the scrollLeft
param = ( is_v ) ? { scrollTop : (isHome) ? top : top + $menu.outerHeight( true ) } : { scrollLeft : left },
$elScroller = ( is_v ) ? $( 'html, body' ) : $scroller;
$elScroller.stop().animate( param, animation.speed, animation.easing, function() {
// active class for selected chapter
$articles.removeClass( 'content-active' );
$article.addClass( 'content-active' );
} );
}
},
_saveState = function( chapter ) {
// adds a new state to the history object
// this will trigger the statechange on the window
if( History.getState().url.queryStringToJSON().chapter !== chapter ) {
History.pushState( null, null, '?chapter=' + chapter );
}
},
_layout = function() {
// control the overflow property of the scroller (div.content-scroller)
var windowWidth = $(window).width();
switch( true ) {
case ( windowWidth <= 960 ) : $scroller.scrollLeft( 0 ).css( 'overflow', 'visible' ); break;
case ( windowWidth <= 1024 ): $scroller.css( 'overflow-x', 'scroll' ); break;
case ( windowWidth > 1024 ) : $scroller.css( 'overflow', 'hidden' ); break;
};
},
_initEvents = function() {
_initWindowEvents();
_initMenuEvents();
_initArticleEvents();
},
_initWindowEvents = function() {
$(window).on({
// when resizing the window we need to reinitialize or destroy the jScrollPanes
// depending on the screen size
'smartresize' : function( event ) {
_layout();
$('article.content').each( function() {
var $article = $(this),
aJSP = $article.data( 'jsp' );
if( $(window).width() > 960 ) {
( aJSP === undefined ) ? $article.jScrollPane( scrollOptions ) : aJSP.reinitialise();
_initArticleEvents();
}
else {
// destroy article's custom scroll if screen size <= 960px
if( aJSP !== undefined )
aJSP.destroy();
$container.off( 'click', 'article.content' );
}
});
var nJSP = $menu.children( '#scroll' ).data( 'jsp' );
nJSP.reinitialise();
// jumps to the current chapter
_goto();
},
// triggered when the history state changes - jumps to the respective chapter
'statechange' : function( event ) {
_goto();
}
});
},
_initMenuEvents = function() {
// when we click a menu link we check which chapter the link refers to,
// and we save the state on the history obj.
// the statechange of the window is then triggered and the page/scroller scrolls to the
// respective chapter's position
$links.on( 'click', function( event ) {
var href = $(this).attr('href'),
chapter = ( href.search(/chapter/) !== -1 ) ? href.substring(8) : 0;
_saveState( chapter );
return false;
});
// scrolls to the top of the page.
// this button will only be visible for screen size < 960
$toTop.on( 'click', function( event ) {
$( 'html, body' ).stop().animate( { scrollTop : 0 }, animation.speed, animation.easing );
return false;
});
},
_initArticleEvents = function() {
// when we click on an article we check which chapter the article refers to,
// and we save the state on the history obj.
// the statechange of the window is then triggered and the page/scroller scrolls to the
// respective chapter's position
$container.on( 'click', 'article.content', function( event ) {
var id = $(this).attr('id'),
chapter = ( id.search(/chapter/) !== -1 ) ? id.substring(7) : 0;
_saveState( chapter );
// return false;
});
};
return { init : init };
})();
Page.init();
})(window);
How would I be able to do this?
Thanks
Well, this line is what's writing your history state:
History.pushState(null, null, '?chapter=' + chapter);
So you would need to modify that function to do what you want. If you have a small site then you could make conditionals to swap the state to whatever you want easily. If you have a large dynamic site you don't want to do this unless you love horrible, tedious maintenance...
_saveState = function(chapter) {
// adds a new state to the history object
// this will trigger the statechange on the window
if (History.getState().url.queryStringToJSON().chapter !== chapter) {
var page;
if(chapter == 1)
page = "/about";
else if(chapter == 2)
page = "/services";
else
page = '?chapter=' + chapter;
History.pushState(null, null, page);
}
},
I may have missed the point of your question though. If so I can update this answer

Categories