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).
Related
I am having trouble with my website's navigation bar.
It is supposed to detect and highlight the navigation link when the user has reached the Section ID. However, it seems to be detecting the section well above their target.
How would I get the navigation bar to accurately detect the sections?
Just in case, here's the jQuery smooth-scrolling code:
;(function($, window, document, undefined){
// our plugin constructor
var OnePageNav = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
navItems: 'a',
currentClass: 'current',
changeHash: false,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function() {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.$nav = this.$elem.find(this.config.navItems);
//Filter any links out of the nav
if(this.config.filter !== '') {
this.$nav = this.$nav.filter(this.config.filter);
}
//Handle clicks on the nav
this.$nav.on('click.onePageNav', $.proxy(this.handleClick, this));
//Get the section positions
this.getPositions();
//Handle scroll changes
this.bindInterval();
//Update the positions on resize too
this.$win.on('resize.onePageNav', $.proxy(this.getPositions, this));
return this;
},
adjustNav: function(self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function() {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function() {
self.didScroll = true;
});
self.t = setInterval(function() {
docHeight = self.$doc.height();
//If it was scrolled
if(self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if(docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function() {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function() {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos);
}
});
},
getSection: function(windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for(var section in this.sections) {
if((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function(e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if(!$parent.hasClass(self.config.currentClass)) {
//Start callback
if(self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
self.scrollTo(newLoc, function() {
//Do we need to change the hash?
if(self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if(self.config.end) {
self.config.end();
}
});
}
e.preventDefault();
},
scrollChange: function() {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if(position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if(!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if(this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
scrollTo: function(target, callback) {
var offset = $(target).offset().top;
$('html, body').animate({
scrollTop: offset
}, this.config.scrollSpeed, this.config.easing, callback);
},
unbindInterval: function() {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function(options) {
return this.each(function() {
new OnePageNav(this, options).init();
});
};
})( jQuery, window , document );
Hi I had some Java scripts specific to a view. However, the script doesnt execute when angularjs loads the view. First time script run but script didnt execute when changed scope .The main index.html dont include this javascript code. This code in home.html . Index.html loads home.html but only one time working this javascript code.
$('#layerslider').layerSlider({
skin : 'fullwidth',
hoverPrevNext : true,
navStartStop : false,
navButtons : false,
autoPlayVideos : false,
animateFirstLayer : false
});
var $carousel = $('.recent-blog-jc, .recent-work-jc');
var scrollCount;
function adjustScrollCount() {
if( $(window).width() < 768 ) {
scrollCount = 1;
} else {
scrollCount = 3;
}
}
function adjustCarouselHeight() {
$carousel.each(function() {
var $this = $(this);
var maxHeight = -1;
$this.find('li').each(function() {
maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
});
$this.height(maxHeight);
});
}
function initCarousel() {
adjustCarouselHeight();
adjustScrollCount();
var i = 0;
var g = {};
$carousel.each(function() {
i++;
var $this = $(this);
g[i] = $this.jcarousel({
animation : 600,
scroll : scrollCount
});
$this.jcarousel('scroll', 0);
$this.prev().find('.jcarousel-prev').bind('active.jcarouselcontrol', function() {
$(this).addClass('active');
}).bind('inactive.jcarouselcontrol', function() {
$(this).removeClass('active');
}).jcarouselControl({
target: '-='+scrollCount,
carousel: g[i]
});
$this.prev().find('.jcarousel-next').bind('active.jcarouselcontrol', function() {
$(this).addClass('active');
}).bind('inactive.jcarouselcontrol', function() {
$(this).removeClass('active');
}).jcarouselControl({
target: '+='+scrollCount,
carousel: g[i]
});
$this.touchwipe({
wipeLeft: function() {
$this.jcarousel('scroll','+='+scrollCount);
},
wipeRight: function() {
$this.jcarousel('scroll','-='+scrollCount);
}
});
});
}
$(function(){
$(window).load(function(){
initCarousel();
});
});
$(window).resize(function () {
$carousel.each(function() {
var $this = $(this);
$this.jcarousel('destroy');
});
initCarousel();
});
Just add $scope.$apply() as close to the async event as possible, though keep in mind this is not best practice (you should try to do everything you can "the Angular way").
I fix this problem with angular directive. I get element with angular.element(document.querySelector('....')). I used ng-repeat in the directive template.
directive('carousel', function () {
return {
restrict: 'A',
replace: true,
transclude: false,
template: ' <div class="blank floated"><div class="four columns carousel-intro"><section class="entire"><h3>{{homepage.header4}}</h3><p>{{homepage.text4}}</p></section><div class="carousel-navi"><div id="work-prev" class="arl active jcarousel-prev"><i class="icon-chevron-left"></i></div><div id="work-next" class="arr active jcarousel-next"><i class="icon-chevron-right"></i></div></div><div class="clearfix"></div></div><section class="jcarousel recent-work-jc"><ul><li class="four columns" ng-repeat="work in works"><h5>{{work.title}}</h5><span>{{work.type}}</span></figcaption></figure></li></ul></section></div>',
link: function link(scope, element, attrs) {
var container = $(element);
var carousel = container.children('.jcarousel')
carousel.jcarousel({
wrap: 'circular'
});
scope.$watch(attrs.images, function (value) {
carousel.jcarousel('reload');
});
angular.element(document.querySelector('#work-prev')).children('.jcarousel-control-prev')
.jcarouselControl({
target: '-=1'
});
angular.element(document.querySelector('#work-next')).children('.jcarousel-control-next')
.jcarouselControl({
target: '-=1'
});
}
}
});
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");
});
});
});
});
});
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.
I'm trying to call an external JS function from flash using the ExternalInterface.call() method in action script. The function should open a modal window that has been written in jQuery. My problem is two fold:
How do I open this modal window without attaching the action to a link? I just want the window open and to pass in the URL.
Is there a better way to do this?
(Code below - I only included the relevent functions. If more if needed, let me know)
ActionScript:
import flash.external.ExternalInterface;
function openMapWindowLink(thingName):Void {
ExternalInterface.call("openMapWindow",locationURL);
}
jQuery:
// Add the action to a link (this works)
function initAjaxPopups() {
$('.ajax-popup').simpleLightbox({
closeLink:'a.btn-close, a.close-popup',
faderOpacity: 0.7,
faderBackground: '#000',
href:true,
onClick: null
});
}
// Open the lightbox from flash with url (not working correctly)
function openMapWindow(locationURL) {
//alert('Clicked '+locationURL);
$simpleLightbox({
closeLink:'a.btn-close, a.close-popup',
faderOpacity: 0.7,
faderBackground: '#000',
href:locationURL,
onClick: null
});
}
/* ajax lightbox plugin */
jQuery.fn.simpleLightbox = function(_options){
var _options = jQuery.extend({
lightboxContentBlock: '.lightbox',
faderOpacity: 0.8,
faderBackground: '#ffffff',
closeLink:'a.close-btn, a.cancel',
href:true,
onClick: null
},_options);
var _popupCounter = 1;
return this.each(function(i, _this){
var _this = jQuery(_this);
if (!_options.href)
_this.lightboxContentBlock = _options.lightboxContentBlock;
else _this.lightboxContentBlock = _this.attr('href');
if (_this.lightboxContentBlock != '' && _this.lightboxContentBlock.length > 1) {
_this.faderOpacity = _options.faderOpacity;
_this.faderBackground = _options.faderBackground;
_this.closeLink = _options.closeLink;
var _fader;
var _lightbox = $(_this.lightboxContentBlock);
if (!jQuery('div.lightbox-fader').length)
_fader = $('body').append('<div class="lightbox-fader"></div>');
_fader = jQuery('div.lightbox-fader');
_lightbox.css({
'zIndex':999
});
_fader.css({
opacity:_this.faderOpacity,
backgroundColor:_this.faderBackground,
display:'none',
position:'absolute',
top:0,
left:0,
zIndex:998,
textIndent: -9999
}).text(' ');
_lightbox.shownFlag = false;
_this.click(function(){
if (jQuery.isFunction(_options.onClick)) {
_options.onClick.apply(_this);
}
var _popupURL = _this.attr('href');
if(jQuery('div[rel*="'+_popupURL+'"]').length == 0) {
$.ajax({
url: _popupURL,
global: false,
type: "GET",
dataType: "html",
success: function(msg){
// append loaded popup
_lightbox = $(msg);
_lightbox.attr('rel',_popupURL).css({
zIndex:999,
position:'absolute',
display:'block',
top: -9999,
left: -9999
});
_lightbox.attr('id','ajaxpopup'+_popupCounter);
jQuery('body').append(_lightbox);
// init js for lightbox
if(typeof initPopupJS == "function"){
initPopupJS(_lightbox);
}
_popupCounter++;
// attach close event
jQuery(_this.closeLink, _lightbox).click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
_scroll = false;
});
return false;
});
// show lightbox
_lightbox.hide();
_lightbox.shownFlag = true;
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
_fader.fadeIn(300, function(){
_lightbox.fadeIn(400);
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
if(typeof VSA_handleResize === 'function') {
VSA_handleResize();
}
});
},
error: function(msg){
alert('ajax error');
return false;
}
});
} else {
_lightbox = jQuery('div[rel*="'+_popupURL+'"]');
_lightbox.hide();
_lightbox.shownFlag = true;
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
_fader.fadeIn(300, function(){
_lightbox.fadeIn(400);
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
if(typeof VSA_handleResize === 'function') {
VSA_handleResize();
}
});
}
return false;
});
jQuery(_this.closeLink).click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
_scroll = false;
});
return false;
});
_fader.click(function(){
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
});
return false;
});
var _scroll = false;
jQuery.fn.simpleLightbox.positionLightbox = function (_lbox) {
if(!_lbox.shownFlag) return false;
var _height = 0;
var _width = 0;
var _minWidth = $('body > div:eq(0)').outerWidth();
if (window.innerHeight) {
_height = window.innerHeight;
_width = window.innerWidth;
} else {
_height = document.documentElement.clientHeight;
_width = document.documentElement.clientWidth;
}
var _thisHeight = _lbox.outerHeight();
var _page = $('body');
if (_lbox.length) {
if (_width < _minWidth) {_fader.css('width',_minWidth);} else {_fader.css('width','100%');}
if (_height > _page.innerHeight()) _fader.css('height',_height); else _fader.css('height',_page.innerHeight());
if (_height > _thisHeight) {
if ($.browser.msie && $.browser.version < 7) {
_lbox.css({
position:'absolute',
top: (document.documentElement.scrollTop + (_height - _thisHeight) / 2)+"px"
});
} else {
_lbox.css({
position:'fixed',
top: ((_height - _lbox.outerHeight()) / 2)+"px"
});
}
}
else {
var _fh = parseInt(_fader.css('height'));
if (!_scroll) {
if (_fh - _thisHeight > parseInt($(document).scrollTop())) {
_fh = parseInt($(document).scrollTop())
_scroll = _fh;
} else {
_scroll = _fh - _thisHeight;
}
}
_lbox.css({
position:'absolute',
top: _scroll
});
}
if (_width > _lbox.outerWidth()) _lbox.css({left:((_width - _lbox.outerWidth()) / 2 + 10) + "px"});
else _lbox.css({position:'absolute',left: 0});
}
}
jQuery(window).resize(function(){
if (_lightbox.is(':visible'))
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
});
jQuery(window).scroll(function(){
if (_lightbox.is(':visible'))
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
});
jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
$(document).keydown(function (e) {
if (!e) evt = window.event;
if (e.keyCode == 27) {
_lightbox.fadeOut(400, function(){
_fader.fadeOut(300);
});
}
});
}
});
}
If attaching lightBox to something which isn't a link it should be
$.simpleLightbox({...}) // with the "." after $
IF that doesnt work you could alter the lightBox plugin source, but this could be troublesome if you wish to update to a newer versions later.
This is a workaround that should work:
<a class="hidden" id="dummylink" href="#"> </a>
//on ready
$('#dummylink').simpleLightbox({...});
function openMapWindow(locationURL) {
$("#dummylink").attr("href", locationURL).trigger('click');
}