I have a scenario where I want to generalize a page scrolling event on button click using dojo. I haven't been able to make a breakthrough for quite sometime. I'm a DOJO beginner, would like some pointers to get a good solution. I have a fiddle:
http://jsfiddle.net/sacnayak/Ej39D/3/
Pasting the code in again for first reference:
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query"],
function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query) {
function asyncProcess() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("success");
}, 500);
return deferred.promise;
}
var currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
console.log(currentActiveDomButton);
on(dom.byId(currentActiveDomButton.id), "click", function () {
var currentActiveDomNode = query("#screens .screen.active")[0];
console.log(currentActiveDomNode);
var screens = query("#screens .screen");
var nextActiveDiv;
for (i = 0; i < screens.length; i++) {
if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
nextActiveDiv = screens[i];
console.log(nextActiveDiv);
break;
}
}
fx.animateProperty({
node: currentActiveDomNode.id,
duration: 500,
properties: {
opacity: {
start: '1',
end: '0.5'
}
}
}).play();
var process = asyncProcess();
process.then(function () {
style.set(nextActiveDiv.id, "display", "block");
//dojo.byId(currentActiveDomButton.id).style.display = 'none';
dojox.fx.smoothScroll({
node: nextActiveDiv.id,
win: window
}).play();
require(["dojo/dom-class"], function (domClass) {
domClass.remove(currentActiveDomNode.id, "active");
domClass.add(currentActiveDomNode.id, "visited");
domClass.add(nextActiveDiv.id, "active");
currentActiveDomButton = query("#screens .screen.active .card-footer-button")[0];
console.log(currentActiveDomButton.id);
});
});
});
});
Was able to fix this. Used a dojo.forEach and set up a event listener for every button.
Here's the fiddle:
http://jsfiddle.net/sacnayak/Ej39D/8/
require(["dojo/fx", "dojox/fx/scroll", "dojo/dom", "dojo/dom-style", "dojo/on", "dojo/domReady!", "dojo/window", "dojo/dom-geometry", "dojo/_base/fx", "dojo/Deferred", "dojo/query", "dojo/dom-class", "dojo/NodeList-traverse"],
function (coreFx, easing, dom, style, on, ready, win, domGeometry, fx, Deferred, query, domClass) {
function asyncProcess() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("success");
}, 500);
return deferred.promise;
}
query(".card-footer-button").forEach(function (buttonNode) {
on(dom.byId(buttonNode.id), "click", function () {
//fetch the current active screen
var currentActiveDomNode = query("#screens .screen.active")[0];
var screens = query("#screens .screen");
var nextActiveDiv;
if (buttonNode.value == "Next") {
for (i = 0; i < screens.length; i++) {
if (dojo.attr(currentActiveDomNode, "id") != dojo.attr(screens[i], "id")) {
if (!domClass.contains(screens[i].id, "visited")) {
nextActiveDiv = screens[i];
break;
}
}
}
} else if (buttonNode.value == "Edit") {
nextActiveDiv = query("#" + buttonNode.id).parent(".screen")[0];
/*fx.animateProperty({
node: nextActiveDiv.id,
duration: 500,
properties: {
opacity: {
start: '0.5',
end: '1'
}
}
}).play();*/
}
fx.animateProperty({
node: currentActiveDomNode.id,
duration: 500,
properties: {
opacity: {
start: '1',
end: '0.5'
}
}
}).play();
var process = asyncProcess();
process.then(function () {
style.set(nextActiveDiv.id, "display", "block");
dojo.byId(buttonNode.id).style.display = 'none';
if(dojo.byId(buttonNode.id + 'Edit') !== null){
dojo.byId(buttonNode.id + 'Edit').style.display = 'block';
}
if (buttonNode.value == "Edit") {
//query(".card-footer-button").forEach(function (buttonArray) {
//if(buttonArray.value == "Next"){
// buttonArray.style.display = "none";
//}
//});
if (buttonNode.id.indexOf("Edit") != -1) {
//console.log('Here');
//console.log('index' + buttonNode.id.indexOf("Edit"));
//console.log('length' + buttonNode.id.length);
var start = 0;
var end = buttonNode.id.indexOf("Edit");
var associatedNextButtonNode = buttonNode.id.substring(start, end);
//console.log(associatedNextButtonNode);
dojo.byId(associatedNextButtonNode).style.display = 'block';
}
}
dojox.fx.smoothScroll({
node: nextActiveDiv.id,
win: window
}).play();
if(nextActiveDiv.style.opacity == '0.5'){
fx.animateProperty({
node: nextActiveDiv.id,
duration: 500,
properties: {
opacity: {
start: '0.5',
end: '1'
}
}
}).play();
}
require(["dojo/dom-class"], function (domClass) {
domClass.remove(currentActiveDomNode.id, "active");
domClass.remove(nextActiveDiv.id, "visited");
if (buttonNode.value == "Next") {
domClass.add(currentActiveDomNode.id, "visited");
}
domClass.add(nextActiveDiv.id, "active");
});
});
});
});
});
Related
This question already has answers here:
Get the size of the screen, current web page and browser window
(20 answers)
Closed 6 days ago.
I see following error for my website (via google Inspect). I need your help to understand the problem and how to fix it?
script.js:137 Uncaught TypeError: window.getWidth is not a function
at Object.check (script.js:137:23)
at Object.initialize (script.js:58:14)
at HTMLDocument.<anonymous> (script.js:442:14)
at n (jquery-1.7.1.min.js:2:14784)
at Object.fireWith (jquery-1.7.1.min.js:2:15553)
at Function.ready (jquery-1.7.1.min.js:2:9773)
at HTMLDocument.B (jquery-1.7.1.min.js:2:14348)
and following is script.js file content:
var TouchMask = {
handlers: [],
isbind: 0,
ontouch: function(){
var result = 1;
TouchMask.handlers.each(function(fn){
result = fn() && result;
});
if(result){
document.removeEvent('touchstart', TouchMask.ontouch);
TouchMask.isbind = 0;
}
},
show: function(){
if(this.isbind){
return false;
}
document.addEvent('touchstart', TouchMask.ontouch);
this.isbind = 1;
},
register: function(handler){
if(typeOf (handler) == 'function' && this.handlers.indexOf(handler) == -1){
this.handlers.push(handler);
}
},
unregister: function(handler){
this.handlers.erase(handler);
}
};
var JawallMenu = {
initialize: function(){
JawallMenu.isAndroidTable = navigator.userAgent.toLowerCase().indexOf('android') > -1 && navigator.userAgent.toLowerCase().indexOf('mobile') == -1;
JawallMenu.isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
JawallMenu.enableTouch();
JawallMenu.check();
window.addEvent('resize', JawallMenu.check);
},
enableTouch: function(){
if (JawallMenu.isTouch){
var jmainnav = $('mainnav');
if(!jmainnav){
return false;
}
var jmenu = jmainnav.getElement('.menu');
if(!jmenu){
return false;
}
var jitems = jmenu.getElements('li.deeper'),
onTouch = function(e){
var i, len, noclick = !this.retrieve('noclick');
e.stopPropagation();
// reset all
for (i = 0, len = jitems.length; i < len; ++i) {
jitems[i].store('noclick', 0);
}
if(noclick){
var jshow = this.addClass('hover').getParents('li.parent').addClass('hover');
jshow = jshow.append([this]);
jitems.each(function (jitem) {
if(!jshow.contains(jitem)){
jitem.removeClass('hover');
}
});
}
this.store('noclick', noclick);
this.focus();
},
onClick = function(e){
e.stopPropagation();
if(this.retrieve('noclick')){
e.preventDefault();
jitems.removeClass('hover');
this.addClass('hover').getParents('li.parent').addClass('hover');
TouchMask.hidetoggle();
TouchMask.show();
} else {
var href = this.getElement('a').get('href');
if(href){
window.location.href = href;
}
}
};
jitems.each(function(jitem){
jitem.addEvent('touchstart', onTouch)
.addEvent('click', onClick)
.store('noclick', 0);
});
JawallMenu.resetmenu = function(){
jitems.store('noclick', 0).removeClass('hover');
return true;
};
TouchMask.register(JawallMenu.resetmenu);
}
},
oldWidth: 0,
check: function(){
var wwidth = window.getWidth();
if(wwidth == JawallMenu.oldWidth){
return;
}
JawallMenu.oldWidth = wwidth;
var jmainnav = $('mainnav');
if(!jmainnav){
return;
}
var jmenuinner = jmainnav.getElement('.menu-inner'),
jmenu = jmainnav.getElement('.menu');
if(!jmenuinner || !jmenu){
return;
}
//check if we have to implement scroll
if (jmenu.offsetWidth > jmenuinner.offsetWidth) {
jmenu.setStyle('float', 'left');
if(!window.menuIScroll){
var jprev = jmainnav.getChildren('.navprev')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navprev'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('prev');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
jnext = jmainnav.getChildren('.navnext')[0] || new Element('a', {
'href': 'javascript:;',
'class': 'navnext'
}).inject(jmainnav).addEvent('click', function(){
if(window.menuIScroll){
window.menuIScroll.scrollToPage('next');
}
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
}),
checkNav = function (){
if(window.menuIScroll){
jprev.setStyle('display', window.menuIScroll.x >= 0 ? 'none' : 'block');
jnext.setStyle('display', (window.menuIScroll.x <= window.menuIScroll.maxScrollX) ? 'none' : 'block');
}
};
window.menuIScroll = new iScroll(jmenuinner, {
snap: '.menu > li',
hScrollbar: false,
vScrollbar: false,
onRefresh: checkNav,
onScrollEnd: checkNav,
useTransform: false,
onScrollStart: function(){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
},
overflow: ''
});
checkNav();
var jactive = jmenu.getChildren('.active')[0];
if(jactive){
window.menuIScroll.scrollToElement(jactive);
}
}
if (window.menuIScroll) {
window.menuIScroll.refresh();
}
} else {
if (window.menuIScroll) {
window.menuIScroll.scrollTo(0, 0, 0);
}
jmenu.setStyle('float', '');
}
//check if the mobile layout, we change html structure
if(wwidth < 720){
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
JawallMenu.jcitem = null;
}
jmenuinner.setStyle('overflow', 'hidden');
jmenu.getChildren('.deeper > ul').each(function(jsub){
var jitem = jsub.getParent(),
sid = null;
jsub.store('parent', jitem).addClass('jsub').inject(jmainnav).setStyle('position', 'absolute');
if(!JawallMenu.isTouch){
//add mouse event to show/hide sub on desktop
jitem.addEvent('mouseenter', function(e){
clearTimeout(sid);
if(jsub.getStyle('display') != 'none'){
return false;
} else {
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
}
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
jsub.addEvent('mouseenter', function(){
clearTimeout(sid);
}).addEvent('mouseleave', function(){
clearTimeout(sid);
sid = setTimeout(function(){
jitem.fireEvent('shide');
}, 100);
});
} else {
//add touch event for touch device
jitem.addEvent('touchstart', function(e){
if(jsub.getStyle('display') == 'none'){
e.stop();
if(JawallMenu.jcitem && JawallMenu.jcitem != jitem){
JawallMenu.jcitem.fireEvent('shide');
}
jsub.setStyles({
display: 'block',
top: jmenuinner.getHeight()
});
jitem.addClass('over');
JawallMenu.jcitem = jitem;
TouchMask.hidetoggle();
TouchMask.show();
}
});
}
jitem.addEvent('shide', function(){
clearTimeout(sid);
jsub.setStyle('display', 'none');
jitem.removeClass('over');
JawallMenu.jcitem = null;
}).fireEvent('shide');
});
//only init once
if(!JawallMenu.initTouch && JawallMenu.isTouch){
jmainnav.addEvent('touchstart', function(){
if(JawallMenu.jcitem){
this.store('touchInside', 1);
}
});
TouchMask.hidesub = function(){
if(jmainnav.retrieve('touchInside')){
jmainnav.store('touchInside', 0);
return false;
} else {
if(JawallMenu.jcitem){
JawallMenu.jcitem.fireEvent('shide');
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidesub);
TouchMask.hidesub();
JawallMenu.initTouch = 1;
}
} else {
JawallMenu.jcitem = null;
jmainnav.getChildren('.jsub').each(function(jsub){
var jitem = jsub.retrieve('parent');
jitem.removeEvents('mouseenter').removeEvents('mouseleave').removeEvents('touchstart').removeEvents('shide');
jsub.removeProperty('style').removeEvents('mouseenter').removeEvents('mouseleave').removeClass('jsub').inject(jitem);
});
jmenuinner.setStyle('overflow', '');
}
}
};
window.addEventListener('load', function(event) {
if(window.menuIScroll){
window.menuIScroll.refresh();
}
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
});
(function($){
var groups = {
},
handler = function (group, value) {
// ignore user setting for page with fixed option
if ($(document.body).hasClass ('fixed-' + group)){
return;
}
if (value) {
if (groups[group]['type'] == 'toggle') {
var cvalue = $.cookie ('ja-'+group);
if (new RegExp ('(^|\\s)' + value+'(?:\\s|$)').test(cvalue)) {
$(document.body).removeClass (group + '-' + value);
cvalue = cvalue.replace (new RegExp ('(^|\\s)' + value+'(?:\\s|$)', 'g'), '$1');
} else {
$(document.body).addClass (group + '-' + value);
cvalue += ' ' + value;
}
groups[group]['val'] = cvalue;
// update cookie
$.cookie ('ja-'+group, cvalue, {duration: 365, path: '/'});
} else {
// update value & cookie
groups[group]['val'] = value;
$.cookie ('ja-'+group, value, {duration: 365, path: '/'});
// remove current
document.body.className = document.body.className.replace (new RegExp ('(^|\\s)' + group+'-[^\\s]*', 'g'), '$1');
$(document.body).addClass (group + '-' + value);
}
}
// Make the UI reload by trigger resize event for window
$(window).trigger('resize');
};
$.fn.toolbar = function(options){
var defaults = {
group: 'basegrid',
type: 'single',
val: 'm'
},
opt = $.extend(defaults, options);
groups[opt.group] = groups[opt.group] || {};
$.extend(groups[opt.group], {type: opt.type, val: opt.val});
if (!$(document.body).hasClass ('fixed-' + opt.group)){
var value = $.cookie('ja-'+opt.group);
if (value) {
groups[opt.group]['val'] = value; // setting exists, replace the default
// add active class
$(document.body).addClass (groups[opt.group]['val'].replace (/(^|\s)([^\s]+)/g, '$1' + opt.group + '-$2'));
} else if(opt.val) {
handler (opt.group, opt.val);
}
}
// bind event for toolbar
return this.bind('click', function () { handler (opt.group, this.id.replace ('toolbar-' + opt.group + '-', '')); return false; });
};
})(window.$wall || window.jQuery);
(window.$wall || window.jQuery)(document).ready(function ($) {
// enable menu responsive check
if(!($.browser.msie && parseFloat($.browser.version) < 9)){
JawallMenu.initialize();
}
var bindevent = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion) ? 'touchstart' : 'click',
jtoggles = $('.btn-toggle'),
jsidebar = $('#sidebar'),
jtoggleactive = null;
// toggle handle
jtoggles.bind(bindevent, function (event) {
var jactive = $(this),
jparent = jactive.parent();
if (jparent.hasClass('active')) {
jparent.removeClass ('active');
// remove btn-toggle-active
jtoggleactive = null
} else {
// remove other active
jtoggles.parent().removeClass ('active');
// add active for this toggle
jparent.addClass ('active');
// store
jtoggleactive = jactive;
}
if(typeOf (TouchMask.hidesub) == 'function'){
TouchMask.hidesub();
}
TouchMask.show();
return false;
});
jtoggles.parent().bind(bindevent, function(){
if(jtoggleactive){
$('body').data('touchInside', 1);
}
});
TouchMask.hidetoggle = function(){
if (jtoggleactive) {
if($('body').data('touchInside')){
$('body').data('touchInside', 0);
return false;
} else {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
return false;
}
}
return true;
};
TouchMask.register(TouchMask.hidetoggle);
var rfpage = $('#josForm').hasClass('wform') && $('#k2Container').hasClass('k2AccountPage'),
wmobile = false, //normal by default
wmeditor = function(){
if(!wmobile){
var jmce = $('.mceLayout:first');
if(jmce.width() > jmce.closest('.wcontrols').width()){
wmobile = true;
$('table.mceToolbar').each(function(){
$(this).find('> tbody > tr').css('white-space', 'normal').find('td').css({
position: '',
float: 'left',
display: 'inline-block'
});
});
$('.toggle-editor a').trigger('click').delay(300).trigger('click');
}
}
},
sidrfp = setTimeout(wmeditor, 350);
// tracking status of btn-toggle
$(window).resize (function() {
JawallMenu.isTablet = JawallMenu.isTouch && (window.innerWidth >= 720);
if (jtoggleactive) {
if (jtoggleactive.css('display') == 'none') {
// remove active
jtoggleactive.parent().removeClass ('active');
jtoggleactive = null;
}
}
if (jsidebar.length) {
if(JawallMenu.isTablet){
jsidebar.css({
position: 'fixed',
top: ''
});
}
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
if(window.sidebarIScroll){
window.sidebarIScroll.refresh();
}
}
if(rfpage){
clearTimeout(sidrfp);
sidrfp = setTimeout(wmeditor, 350);
}
});
// scrollbar for sidebar if exist
if (jsidebar.length) {
jsidebar
.add(jsidebar.find('.sidebar-inner'))
.css('height', Math.max(80,
(window.innerHeight || $(window).height())
- parseInt(jsidebar.css('top'))
- parseInt(jsidebar.css('margin-bottom'))
- parseInt(jsidebar.css('padding-bottom'))));
window.sidebarIScroll = new iScroll(jsidebar.find('.sidebar-inner')[0], {vScrollbar: true, scrollbarClass: 'sidebarTracker', useTransform: false});
if(JawallMenu.isTouch){
var jsbtoggle = jsidebar.find('.btn-toggle:first');
$('<div id="dummy-toggle"></div>').css({
position: 'absolute',
top: 0,
left: 0,
width: jsbtoggle.width(),
height: jsbtoggle.height(),
}).appendTo(document.body).bind(bindevent, function(e){
e.preventDefault();
e.stopPropagation();
jsbtoggle.trigger(bindevent);
});
var lastScroll = 0,
scrollid = null;
$(window).scroll(function(){
lastScroll = $(window).scrollTop();
$('#dummy-toggle').css('top', lastScroll);
if(JawallMenu.isTablet){
clearTimeout(scrollid);
scrollid = setTimeout(function(){
lastScroll = $(window).scrollTop();
scrollid = setTimeout(function(){
if(lastScroll == $(window).scrollTop()){
jsidebar
.css('top', lastScroll + parseFloat(jsidebar.css('top', '').css('top')))
.css('position', 'absolute');
$(document).one('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
}
}, 100);
}, 100);
}
});
}
if(JawallMenu.isTablet && !JawallMenu.isBindTablet){
$(document).on('touchmove', function(){
jsidebar.css({position: 'fixed', top: ''});
});
JawallMenu.isBindTablet = 1;
}
}
// check and load typography assert files if nessesary
window.jtypo = jQuery('.item-pagetypography .item-content');
if(!window.jtypo.length){
window.jtypo = jQuery('.typography .itemBody');
}
if(window.jtypo.length){
var css = document.createElement('link');
css.type = 'text/css';
css.rel= 'stylesheet';
css.href= JADef.tplurl + 'css/jtypo.css';
document.getElementsByTagName('head')[0].appendChild(css);
$.getScript(JADef.tplurl + 'js/jtypo.js');
}
});
to understand it better please see the error directly via google inspect at following page:
http://test6.harfrooz.com/117-more/18376-top-20-ufo-sightings
This error made my menus disabled and more issues. I would appreciate for any help to solve this error.
I am fairly certain this has been answered before here.
For normal javascript you can use:
window.innerHeight - the inner height of the browser window (in
pixels)
window.innerWidth - the inner width of the browser window (in
pixels)
I have a external js file linked to my html and bundle.js file generated by webpack linked to html .
In index.html code is
<script src="js/main.js"></script>
<script type="text/javascript" src="bundle.min.js"></script>`
The issue is functions in main.js are called only once on page load in reactjs after running webpack and code is bundled.
main.js file code is
(function () {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
var mobileMenuOutsideClick = function() {
$(document).click(function (e) {
var container = $("#fh5co-offcanvas, .js-fh5co-nav-toggle");
if (!container.is(e.target) && container.has(e.target).length === 0) {
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
}
});
};
var offcanvasMenu = function() {
$('#page').prepend('<div id="fh5co-offcanvas" />');
$('#page').prepend('<i></i>');
var clone1 = $('.menu-1 > ul').clone();
$('#fh5co-offcanvas').append(clone1);
var clone2 = $('.menu-2 > ul').clone();
$('#fh5co-offcanvas').append(clone2);
$('#fh5co-offcanvas .has-dropdown').addClass('offcanvas-has-dropdown');
$('#fh5co-offcanvas')
.find('li')
.removeClass('has-dropdown');
// Hover dropdown menu on mobile
$('.offcanvas-has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.addClass('active')
.find('ul')
.slideDown(500, 'easeOutExpo');
}).mouseleave(function(){
var $this = $(this);
$this
.removeClass('active')
.find('ul')
.slideUp(500, 'easeOutExpo');
});
$(window).resize(function(){
if ( $('body').hasClass('offcanvas') ) {
$('body').removeClass('offcanvas');
$('.js-fh5co-nav-toggle').removeClass('active');
}
});
};
var burgerMenu = function() {
$('body').on('click', '.js-fh5co-nav-toggle', function(event){
var $this = $(this);
if ( $('body').hasClass('overflow offcanvas') ) {
$('body').removeClass('overflow offcanvas');
} else {
$('body').addClass('overflow offcanvas');
}
$this.toggleClass('active');
event.preventDefault();
});
};
var fullHeight = function() {
if ( !isMobile.any() ) {
$('.js-fullheight').css('height', $(window).height());
$(window).resize(function(){
$('.js-fullheight').css('height', $(window).height());
});
}
};
var contentWayPoint = function() {
var i = 0;
$('.animate-box').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated-fast') ) {
i++;
$(this.element).addClass('item-animate');
setTimeout(function(){
$('body .animate-box.item-animate').each(function(k){
var el = $(this);
setTimeout( function () {
var effect = el.data('animate-effect');
if ( effect === 'fadeIn') {
el.addClass('fadeIn animated-fast');
} else if ( effect === 'fadeInLeft') {
el.addClass('fadeInLeft animated-fast');
} else if ( effect === 'fadeInRight') {
el.addClass('fadeInRight animated-fast');
} else {
el.addClass('fadeInUp animated-fast');
}
el.removeClass('item-animate');
}, k * 200, 'easeInOutExpo' );
});
}, 100);
}
} , { offset: '85%' } );
};
var dropdown = function() {
$('.has-dropdown').mouseenter(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'block')
.addClass('animated-fast fadeInUpMenu');
}).mouseleave(function(){
var $this = $(this);
$this
.find('.dropdown')
.css('display', 'none')
.removeClass('animated-fast fadeInUpMenu');
});
};
var goToTop = function() {
$('.js-gotop').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $('html').offset().top
}, 500, 'easeInOutExpo');
return false;
});
$(window).scroll(function(){
var $win = $(window);
if ($win.scrollTop() > 200) {
$('.js-top').addClass('active');
} else {
$('.js-top').removeClass('active');
}
});
};
// Loading page
var loaderPage = function() {
$(".fh5co-loader").fadeOut("slow");
};
var counter = function() {
$('.js-counter').countTo({
formatter: function (value, options) {
return value.toFixed(options.decimals);
},
});
};
var counterWayPoint = function() {
if ($('#fh5co-counter').length > 0 ) {
$('#fh5co-counter').waypoint( function( direction ) {
if( direction === 'down' && !$(this.element).hasClass('animated') ) {
setTimeout( counter , 400);
$(this.element).addClass('animated');
}
} , { offset: '90%' } );
}
};
var parallax = function() {
if ( !isMobile.any() ) {
$(window).stellar({
horizontalScrolling: false,
hideDistantElements: false,
responsive: true
});
}
};
var testimonialCarousel = function(){
var owl = $('.owl-carousel-fullwidth');
owl.owlCarousel({
items: 1,
loop: true,
margin: 0,
nav: false,
dots: true,
smartSpeed: 800,
autoHeight: true
});
};
var sliderMain = function() {
$('#fh5co-hero .flexslider').flexslider({
animation: "fade",
slideshowSpeed: 5000,
directionNav: true,
start: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
},
before: function(){
setTimeout(function(){
$('.slider-text').removeClass('animated fadeInUp');
$('.flex-active-slide').find('.slider-text').addClass('animated fadeInUp');
}, 500);
}
});
$('#fh5co-hero .flexslider .slides > li').css('height', $(window).height());
$(window).resize(function(){
$('#fh5co-hero .flexslider .slides > li').css('height', $(window).height());
});
};
$(function(){
mobileMenuOutsideClick();
offcanvasMenu();
burgerMenu();
contentWayPoint();
sliderMain();
dropdown();
goToTop();
loaderPage();
counterWayPoint();
counter();
parallax();
testimonialCarousel();
fullHeight();
});
}());
I want my code in main.js called always not only on reload. I am using reactjs and webpack.
Please help me fix this. Thank you.
Please note that you your code in main.js is wrapped in something like this:
(function () {
...
}());
Above construction is called Immediately-Invoked Function Expression (IIFE) - it makes code inside to be called immediately and because everything defined inside any function is visible only in this function (is not visible outside function scope) it also helps to not pollute global context. You can read more about it here.
If you want to have possibility to call it anytime you need you should use normal function (not IIFE):
function mainFunction() {
//your codde
}
and then you can call it anytime you need (also on page load).
This is a simple script for horizontal fortune roulette, created using slick slider. Problem: function rollout() executed twice (and all helpers too) because template rendered twice. I'm using iron:router for routing, code:
Router.configure({
loadingTemplate: "loading",
layoutTemplate: "layout"
});
Router.map(function() {
this.route("hello", {
path: "/",
waitOn: function() {
return Meteor.subscribe("games");
}
});
});
hello.js:
Session.setDefault('currentSlide', 0);
Template.hello.events({
'click .create': function(e) {
e.preventDefault();
var ins = {
gameStartTime: new Date(),
finished: false
}
Games.insert({
gameStartTime: new Date(),
finished: "false"
});
Session.set("gameStatus", "waiting");
}
})
Template.hello.helpers({
currentSlide: function() {
var value = Session.get('currentSlide');
if (value === 25) {
return 0;
}
return value;
},
games: function() {
var game = Games.find();
return game;
},
gameHandler: function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
if (game && game.finished === "false" && gameStatus === "waiting") {
Games.update({_id: game._id}, {
$set: {running: true}
});
} else if (gameStatus === "finished") {
Meteor.call('updateGame', game._id); //remove item from collection after game over; Error here: TypeError: Cannot read property '_id' of undefined;
console.log('game finished');
}
if (game && game.running === true) {
//Set Session variable and launch roulette
Session.set("gameStatus", "running");
rollout(game._id);
}
}
});
var rollout = function(gameid) {
Session.set("gameStatus", "running");
//make div's visible. They are have display:none by default.
document.getElementById("roulette").style.display = "block";
document.getElementById("result").style.display = "block";
document.getElementById("wrapper").style.display = "none";
var speed = 500; //default slider speed
Session.setDefault('speed', speed);
var r = $('#roulette').slick({
centerMode: true,
slidesToShow: 7,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 0,
speed: speed,
draggable: false,
pauseOnHover: false,
cssEase:'linear'
});
var maximum = 14;
var minimum = 0;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var winResult = randomnumber;
var speed = 80;
var currentSlide = Session.get('currentSlide');
function roll(callback) {
Session.set('currentSlide', r.slickCurrentSlide());
if (speed < 800) {
speed += 20;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 500);
} else if (speed >= 600 && speed < 1300) {
speed += 40;
r.slickSetOption("speed", speed, false);
setTimeout(function() {
roll(callback);
}, 300);
} else if (speed >= 1300 && speed < 20000) {
setTimeout(function() {
speed += 3;
r.slickSetOption('speed', speed, false);
if (Session.get('currentSlide') === winResult) {
r.slickPause();
setTimeout(function() {
//hide roulette div's
document.getElementById("roulette").style.display = "none";
document.getElementById("result").style.display = "none";
document.getElementById("wrapper").style.display = "block";
r.unslick();
Session.set('currentSlide', 0);
Session.set("gameStatus", "finished");
callback(true);
return
}, 10000);
} else {
roll(callback);
}
}, 30)
} else {
callback(true);
}
}
roll(function(callback) {
Meteor.call('updateGame', gameid); //remove item from collection
Session.set("gameStatus", "finished");
});
}
In template i'm using spinner by sacha:spin package and it working fine.
The gameHandler function should not be in your template helpers, which are only meant to supply information to the template. Instead, that logic needs to be moved to an autorun function. This autorun statement will re-run anytime a reactive datasource within it changes.
ex:
Template.hello.onCreated(function() {
this.autorun(function() {
var game = Games.findOne();
var gameStatus = Session.get("gameStatus");
// ...etc
});
}
For some reason my gallery isn't working on Mobile devices including iPad, works fine on desktop. Instead of allowing a user to click through, all images appear stacked. The link to my site. The code is
located here
// scroll gallery init
function initCarousel() {
var isTouchDevice = /MSIE 10.*Touch/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
jQuery('div.view-gallery').scrollGallery({
mask: 'div.frame',
slider: '>ul',
slides: '>li',
btnPrev: 'a.btn-prev',
btnNext: 'a.btn-next',
pagerLinks: '.pagination li',
circularRotation: false,
autoRotation: false,
switchTime: 3000,
animSpeed: 500,
onInit: function(obj){
obj.resizeFlag = true;
obj.win = jQuery(window);
//obj.win.unbind('resize orientationchange load', obj.onWindowResize);
obj.resizeSlides = function(){
obj.slideOffset = obj.slides.eq(0).outerWidth(true) - obj.slides.eq(0).width();
if(!obj.resizeFlag) obj.slides.css({width: ''});
else obj.slides.css({width: obj.mask.width()/2 - obj.slideOffset});
obj.calculateOffsets();
obj.refreshPosition();
obj.refreshState();
}
if(isTouchDevice){
ResponsiveHelper.addRange({
'..767': {
on: function(){
setTimeout(function(){
obj.resizeFlag = true;
obj.resizeSlides();
obj.win.bind('resize orientationchange load', obj.resizeSlides);
}, 100);
}
},
'768..': {
on: function(){
obj.resizeFlag = false;
obj.win.unbind('resize orientationchange load', obj.resizeSlides);
obj.resizeSlides();
}
}
});
}
}
});
jQuery('.scrollable-gallery').scrollableGallery();
}
/*
* scrollableGallery
*/
;(function($) {
function ScrollableGallery(options) {
this.options = {
scrollableArea: '.frame',
listItems: '.list-items',
btnPrev: '.btn-prev',
btnNext: '.btn-next',
animSpeed: 500
}
$.extend(this.options, options);
this.init();
}
ScrollableGallery.prototype = {
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
},
findElements: function() {
this.holder = $(this.options.holder);
this.scrollableArea = this.holder.find(this.options.scrollableArea);
this.listItems = this.scrollableArea.find(this.options.listItems);
this.items = this.listItems.children();
this.lastItem = this.items.last();
this.btnPrev = this.holder.find(this.options.btnPrev);
this.btnNext = this.holder.find(this.options.btnNext);
this.scrollAPI = new jcf.modules.customscroll({
replaces: this.scrollableArea[0]
});
},
setStructure: function() {
var that = this;
if (that.listItems.css('position') === 'static') {
that.listItems.css('position', 'relative');
}
setTimeout(function() {
that.refreshState();
}, 50);
},
refreshState: function() {
this.listItems.css('width', 32700);
this.listItems.css('width', this.lastItem.position().left + this.lastItem.outerWidth(true) + 1);
this.scrollableArea.add(this.scrollableArea.parent()).css({
width: '',
height: ''
});
this.scrollAPI.refreshState();
},
addEvents: function() {
var that = this;
that.btnPrev.bind('click', function(e) {
e.preventDefault();
that.prevSlide();
});
that.btnNext.bind('click', function(e) {
e.preventDefault();
that.nextSlide();
});
win.bind('resize orientationchange load', function() {
that.refreshState();
});
},
nextSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = 0; i < that.items.length; i++) {
pos = that.items.eq(i).position().left;
if (pos > curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
prevSlide: function() {
var that = this;
var curPos = this.scrollableArea.scrollLeft();
var pos;
for (var i = that.items.length - 1; i >= 0; i--) {
pos = that.items.eq(i).position().left;
if (pos < curPos) {
that.scrollAnimate(curPos, pos);
break;
}
}
},
scrollAnimate: function(from, to) {
var that = this;
var start = new Date().getTime();
setTimeout(function() {
var now = (new Date().getTime()) - start;
var progress = now / that.options.animSpeed;
var result = (to - from) * progress + from;
that.scrollAPI.hScrollBar.scrollTo(result);
if (progress < 1) {
setTimeout(arguments.callee, 10);
} else {
that.scrollAPI.hScrollBar.scrollTo(to);
}
}, 10);
}
}
var win = $(window);
$.fn.scrollableGallery = function(options) {
return this.each(function() {
if (!$(this).data('ScrollableGallery')) {
$(this).data('ScrollableGallery', new ScrollableGallery($.extend({}, {holder: this}, options)));
}
});
}
}(jQuery));
After looking through your code, there were numerous errors with syntax. I have cleaned them up as best as I could, this should help you out.
http://jsfiddle.net/wvWrY/1/
For example, this area was missing a semicolon (no way to call the findElements function, as JS will simply skip to the next line without a semicolon there.)
init: function() {
this.findElements()
this.setStructure();
this.addEvents();
Run your code through a linter, it will greatly improve your syntax structure and ensure little leave out errors like semicolons and commas and brackets aren't omitted.
EDIT: Ok, having looked at your code it appears this is actually due to the !importants in your allmobile.css file. The width and height are set to max-width: 100% (this breaks it because the way the slider works is to extend the gallery as far off screen as possible) and the height to auto (this breaks it because it allows the images to just keep piling on). Once you remove those for the page, it become much much much better and actually works.
How can I stop the autoplay function of cSlider with an onmouseover event?
HTML:
<div id="da-slider" class="da-slider">
<div class="da-slide">
<p>Text</p>
</div>
<div class="da-slide">
<p>More text</p>
</div>
</div>
What I have tried so far with jQuery:
$(function() {
$('#da-slider').cslider({
autoplay : true,
bgincrement : 450
});
});
$('#da-slider').hover(function() {
if($('#daslider').autoplay('true')){
autoplay: false
}
}, function () {
autoplay: true
});
This is the one I'm using:
http://tympanus.net/codrops/2012/03/15/parallax-content-slider-with-css3-and-jquery/
This feature not implemented by default but this shouldn't stop you from implementing it on your own. Look at modified plugin code below (draw attention on stop and 'start' methods)
(function ($, undefined) {
/*
* Slider object.
*/
$.Slider = function (options, element) {
this.$el = $(element);
this._init(options);
};
$.Slider.defaults = {
current: 0, // index of current slide
bgincrement: 50, // increment the bg position (parallax effect) when sliding
autoplay: false, // slideshow on / off
interval: 4000 // time between transitions
};
$.Slider.prototype = {
_init: function (options) {
this.options = $.extend(true, {}, $.Slider.defaults, options);
this.$slides = this.$el.children('div.da-slide');
this.slidesCount = this.$slides.length;
this.current = this.options.current;
if (this.current < 0 || this.current >= this.slidesCount) {
this.current = 0;
}
this.$slides.eq(this.current).addClass('da-slide-current');
var $navigation = $('<nav class="da-dots"/>');
for (var i = 0; i < this.slidesCount; ++i) {
$navigation.append('<span/>');
}
$navigation.appendTo(this.$el);
this.$pages = this.$el.find('nav.da-dots > span');
this.$navNext = this.$el.find('span.da-arrows-next');
this.$navPrev = this.$el.find('span.da-arrows-prev');
this.isAnimating = false;
this.bgpositer = 0;
this.cssAnimations = Modernizr.cssanimations;
this.cssTransitions = Modernizr.csstransitions;
if (!this.cssAnimations || !this.cssAnimations) {
this.$el.addClass('da-slider-fb');
}
this._updatePage();
// load the events
this._loadEvents();
// slideshow
if (this.options.autoplay) {
this._startSlideshow();
}
},
_navigate: function (page, dir) {
var $current = this.$slides.eq(this.current), $next, _self = this;
if (this.current === page || this.isAnimating) return false;
this.isAnimating = true;
// check dir
var classTo, classFrom, d;
if (!dir) {
(page > this.current) ? d = 'next' : d = 'prev';
}
else {
d = dir;
}
if (this.cssAnimations && this.cssAnimations) {
if (d === 'next') {
classTo = 'da-slide-toleft';
classFrom = 'da-slide-fromright';
++this.bgpositer;
}
else {
classTo = 'da-slide-toright';
classFrom = 'da-slide-fromleft';
--this.bgpositer;
}
this.$el.css('background-position', this.bgpositer * this.options.bgincrement + '% 0%');
}
this.current = page;
$next = this.$slides.eq(this.current);
if (this.cssAnimations && this.cssAnimations) {
var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
$current.removeClass(rmClasses);
$next.removeClass(rmClasses);
$current.addClass(classTo);
$next.addClass(classFrom);
$current.removeClass('da-slide-current');
$next.addClass('da-slide-current');
}
// fallback
if (!this.cssAnimations || !this.cssAnimations) {
$next.css('left', (d === 'next') ? '100%' : '-100%').stop().animate({
left: '0%'
}, 1000, function () {
_self.isAnimating = false;
});
$current.stop().animate({
left: (d === 'next') ? '-100%' : '100%'
}, 1000, function () {
$current.removeClass('da-slide-current');
});
}
this._updatePage();
},
_updatePage: function () {
this.$pages.removeClass('da-dots-current');
this.$pages.eq(this.current).addClass('da-dots-current');
},
_startSlideshow: function () {
var _self = this;
this.slideshow = setTimeout(function () {
var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
_self._navigate(page, 'next');
if (_self.options.autoplay) {
_self._startSlideshow();
}
}, this.options.interval);
},
page: function (idx) {
if (idx >= this.slidesCount || idx < 0) {
return false;
}
if (this.options.autoplay) {
clearTimeout(this.slideshow);
this.options.autoplay = false;
}
this._navigate(idx);
},
stop: function () {
if (this.options.autoplay) {
clearTimeout(this.slideshow);
this.options.autoplay = false;
}
},
start: function () {
this.options.autoplay = true;
this._startSlideshow();
},
_loadEvents: function () {
var _self = this;
this.$pages.on('click.cslider', function (event) {
_self.page($(this).index());
return false;
});
this.$navNext.on('click.cslider', function (event) {
if (_self.options.autoplay) {
clearTimeout(_self.slideshow);
_self.options.autoplay = false;
}
var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
_self._navigate(page, 'next');
return false;
});
this.$navPrev.on('click.cslider', function (event) {
if (_self.options.autoplay) {
clearTimeout(_self.slideshow);
_self.options.autoplay = false;
}
var page = (_self.current > 0) ? page = _self.current - 1 : page = _self.slidesCount - 1;
_self._navigate(page, 'prev');
return false;
});
if (this.cssTransitions) {
if (!this.options.bgincrement) {
this.$el.on('webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function (event) {
if (event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4') {
_self.isAnimating = false;
}
});
}
else {
this.$el.on('webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function (event) {
if (event.target.id === _self.$el.attr('id'))
_self.isAnimating = false;
});
}
}
}
};
var logError = function (message) {
if (this.console) {
console.error(message);
}
};
$.fn.cslider = function (options) {
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
var instance = $.data(this, 'cslider');
if (!instance) {
logError("cannot call methods on cslider prior to initialization; " +
"attempted to call method '" + options + "'");
return;
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("no such method '" + options + "' for cslider instance");
return;
}
instance[options].apply(instance, args);
});
}
else {
this.each(function () {
var instance = $.data(this, 'cslider');
if (!instance) {
$.data(this, 'cslider', new $.Slider(options, this));
}
});
}
return this;
};
})(jQuery);
With updated plugin you can pause and renew autiplaying with this code:
$('#da-slider').hover(
function () {
$(this).cslider("stop");
},
function () {
$(this).cslider("start");
}
);