function is undefined in firefox only - javascript

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/

This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.

Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);

Use setTimeout(xfade, 3500) instead.

Related

js / css flip card game bug in shuffle function

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

clearInterval doesn't work for me

var waveTimes = 0;
var detectInterval = setInterval(function(){
if(parseInt($(".people").css("top")) > 420){
var waveInterval = setInterval(peopleWave,300);
clearInterval(detectInterval);
}
},300);
function peopleWave(){
waveTimes += 1;
if(waveTimes == 6){
clearInterval(waveInterval);
}
var pic1 = "images/index/wave1.png";
var pic2 = "images/index/wave2.png";
if($(".wave img").attr("src") == pic1){
$(".wave img").attr("src",pic2);
} else {
$(".wave img").attr("src",pic1);
}
}
it says waveInterval not found after peopleWave runs 6 times, how can I solve it?
Define waveInterval outside your anonymous function, so that peopleWave has access to it:
var waveTimes = 0,
waveInterval;
...
waveInterval = setTimeout(peopleWave, 300);

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

x.classList.toggle() not working correctly

So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
http://jsfiddle.net/8TVn5/
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
I't just a typo: its should be getElementById.
http://jsfiddle.net/8TVn5/1/
Why are you mixing jQuery and normal selectors?
window.onload = function () {
var currentPercent = 0,
dot1 = $('#dot1');
var showPercent = window.setInterval(function() {
dot1.on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration',
function (e) {
currentPercent= 0;
}
);
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent === 20){
dot1.toggleClass('doton');
}
$('#result').html(currentPercent);
}, 200);
};

How to dynamically add elements via jQuery

The script below creates a slider widget the takes a definition list and turns it into a slide deck. Each dt element is rotated via css to become the "spine", which is used to reveal that dt's sibling dd element.
What I'm trying to do is to enhance it so that I can have the option to remove the spines from the layout and just use forward and back buttons on either side of the slide deck. To do that, I set the dt's to display:none via CSS and use the code under the "Remove spine layout" comment to test for visible.
This works fine to remove the spines, now I need to dynamically create 2 absolutely positioned divs to hold the left and right arrow images, as well as attach a click handler to them.
My first problem is that my attempt to create the divs is not working.
Any help much appreciated.
jQuery.noConflict();
(function(jQuery) {
if (typeof jQuery == 'undefined') return;
jQuery.fn.easyAccordion = function(options) {
var defaults = {
slideNum: true,
autoStart: false,
pauseOnHover: true,
slideInterval: 5000
};
this.each(function() {
var settings = jQuery.extend(defaults, options);
jQuery(this).find('dl').addClass('easy-accordion');
// -------- Set the variables ------------------------------------------------------------------------------
jQuery.fn.setVariables = function() {
dlWidth = jQuery(this).width()-1;
dlHeight = jQuery(this).height();
if (!jQuery(this).find('dt').is(':visible')){
dtWidth = 0;
dtHeight = 0;
slideTotal = 0;
// Add an element to rewind to previous slide
var slidePrev = document.createElement('div');
slidePrev.className = 'slideAdv prev';
jQuery(this).append(slidePrev);
jQuery('.slideAdv.prev').css('background':'red','width':'50px','height':'50px');
// Add an element to advance to the next slide
var slideNext = document.createElement('div');
slideNext.className = 'slideAdv next';
jQuery(this).append(slideNext);
jQuery('.slideAdv.next').css('background':'green','width':'50px','height':'50px');
}
else
{
dtWidth = jQuery(this).find('dt').outerHeight();
if (jQuery.browser.msie){ dtWidth = jQuery(this).find('dt').outerWidth();}
dtHeight = dlHeight - (jQuery(this).find('dt').outerWidth()-jQuery(this).find('dt').width());
slideTotal = jQuery(this).find('dt').size();
}
ddWidth = dlWidth - (dtWidth*slideTotal) - (jQuery(this).find('dd').outerWidth(true)-jQuery(this).find('dd').width());
ddHeight = dlHeight - (jQuery(this).find('dd').outerHeight(true)-jQuery(this).find('dd').height());
};
jQuery(this).setVariables();
// -------- Fix some weird cross-browser issues due to the CSS rotation -------------------------------------
if (jQuery.browser.safari){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; /* Safari and Chrome */ }
if (jQuery.browser.mozilla){ var dtTop = dlHeight - 20; var dtOffset = - 20; /* FF */ }
if (jQuery.browser.msie){ var dtTop = 0; var dtOffset = 0; /* IE */ }
if (jQuery.browser.opera){ var dtTop = (dlHeight-dtWidth)/2; var dtOffset = -dtTop; } /* Opera */
// -------- Getting things ready ------------------------------------------------------------------------------
var f = 1;
var paused = false;
jQuery(this).find('dt').each(function(){
jQuery(this).css({'width':dtHeight,'top':dtTop,'margin-left':dtOffset});
// add unique id to each tab
jQuery(this).addClass('spine_' + f);
// add active corner
var corner = document.createElement('div');
corner.className = 'activeCorner spine_' + f;
jQuery(this).append(corner);
if(settings.slideNum == true){
jQuery('<span class="slide-number">'+f+'</span>').appendTo(this);
if(jQuery.browser.msie){
var slideNumLeft = parseInt(jQuery(this).find('.slide-number').css('left'));
if(jQuery.browser.version == 6.0 || jQuery.browser.version == 7.0){
jQuery(this).find('.slide-number').css({'bottom':'auto'});
slideNumLeft = slideNumLeft - 14;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
}
if(jQuery.browser.version == 8.0 || jQuery.browser.version == 9.0){
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top')) - 20;
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
slideNumLeft = slideNumLeft - 10;
jQuery(this).find('.slide-number').css({'left': slideNumLeft})
jQuery(this).find('.slide-number').css({'marginTop': 10});
}
} else {
var slideNumTop = jQuery(this).find('.slide-number').css('bottom');
var slideNumTopVal = parseInt(slideNumTop) + parseInt(jQuery(this).css('padding-top'));
jQuery(this).find('.slide-number').css({'bottom': slideNumTopVal});
}
}
f = f + 1;
});
if(jQuery(this).find('.active').size()) {
jQuery(this).find('.active').next('dd').addClass('active');
} else {
jQuery(this).find('dt:first').addClass('active').next('dd').addClass('active');
}
jQuery(this).find('dt:first').css({'left':'0'}).next().css({'left':dtWidth});
jQuery(this).find('dd').css({'width':ddWidth,'height':ddHeight});
// -------- Functions ------------------------------------------------------------------------------
jQuery.fn.findActiveSlide = function() {
var i = 1;
this.find('dt').each(function(){
if(jQuery(this).hasClass('active')){
activeID = i; // Active slide
} else if (jQuery(this).hasClass('no-more-active')){
noMoreActiveID = i; // No more active slide
}
i = i + 1;
});
};
jQuery.fn.calculateSlidePos = function() {
var u = 2;
jQuery(this).find('dt').not(':first').each(function(){
var activeDtPos = dtWidth*activeID;
if(u <= activeID){
var leftDtPos = dtWidth*(u-1);
jQuery(this).animate({'left': leftDtPos});
if(u < activeID){ // If the item sits to the left of the active element
jQuery(this).next().css({'left':leftDtPos+dtWidth});
} else{ // If the item is the active one
jQuery(this).next().animate({'left':activeDtPos});
}
} else {
var rightDtPos = dlWidth-(dtWidth*(slideTotal-u+1));
jQuery(this).animate({'left': rightDtPos});
var rightDdPos = rightDtPos+dtWidth;
jQuery(this).next().animate({'left':rightDdPos});
}
u = u+ 1;
});
setTimeout( function() {
jQuery('.easy-accordion').find('dd').not('.active').each(function(){
jQuery(this).css({'display':'none'});
});
}, 400);
};
jQuery.fn.activateSlide = function() {
this.parent('dl').setVariables();
this.parent('dl').find('dd').css({'display':'block'});
this.parent('dl').find('dd.plus').removeClass('plus');
this.parent('dl').find('.no-more-active').removeClass('no-more-active');
this.parent('dl').find('.active').removeClass('active').addClass('no-more-active');
this.addClass('active').next().addClass('active');
this.parent('dl').findActiveSlide();
if(activeID < noMoreActiveID){
this.parent('dl').find('dd.no-more-active').addClass('plus');
}
this.parent('dl').calculateSlidePos();
};
jQuery.fn.rotateSlides = function(slideInterval, timerInstance) {
var accordianInstance = jQuery(this);
timerInstance.value = setTimeout(function(){accordianInstance.rotateSlides(slideInterval, timerInstance);}, slideInterval);
if (paused == false){
jQuery(this).findActiveSlide();
var totalSlides = jQuery(this).find('dt').size();
var activeSlide = activeID;
var newSlide = activeSlide + 1;
if (newSlide > totalSlides) {newSlide = 1; paused = true;}
jQuery(this).find('dt:eq(' + (newSlide-1) + ')').activateSlide(); // activate the new slide
}
}
// -------- Let's do it! ------------------------------------------------------------------------------
function trackerObject() {this.value = null}
var timerInstance = new trackerObject();
jQuery(this).findActiveSlide();
jQuery(this).calculateSlidePos();
if (settings.autoStart == true){
var accordianInstance = jQuery(this);
var interval = parseInt(settings.slideInterval);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
}
jQuery(this).find('dt').not('active').click(function(){
var accordianInstance = jQuery(this); //JSB to fix bug with IE < 9
jQuery(this).activateSlide();
clearTimeout(timerInstance.value);
timerInstance.value = setTimeout(function(){
accordianInstance.rotateSlides(interval, timerInstance);
}, interval);
});
if (!(jQuery.browser.msie && jQuery.browser.version == 6.0)){
jQuery('dt').hover(function(){
jQuery(this).addClass('hover');
}, function(){
jQuery(this).removeClass('hover');
});
}
if (settings.pauseOnHover == true){
jQuery('dd').hover(function(){
paused = true;
}, function(){
paused = false;
});
}
});
};
})(jQuery);
Creating elements in jQuery is easy:
$newDiv = $('<div />');
$newDiv.css({
'position': 'absolute',
'top': '10px',
'left': '10px'
});
$newDiv.on('click', function() {
alert('You have clicked me');
});
$('#your_container').append($newDiv);

Categories