Jquery/Javascript: Button disappears after being clicked - javascript

I've made a JSFiddle of a small mock game I'm making (https://jsfiddle.net/uw2k9ba6/1/).
Here is my Javascript for reference:
$(document).ready(function () {
//charmander
var charmander = {
hp: 140
};
console.log(charmander.hp);
document.getElementById('charnum').innerHTML = (charmander.hp);
//bulbasaur
var bulbasaur = {
hp: 180
}
document.getElementById('bulbnum').innerHTML = (bulbasaur.hp);
//squirtle
var squirtle = {
hp: 160
}
document.getElementById('squirnum').innerHTML = (squirtle.hp);
let found = false;
let charPick = false;
let bulbPick = false;
let squirPick = false;
var startGame = false;
var fighters = [];
var ids = [];
//select pokemon - WORKING
function selector() {
$("#charbut").click(function () {
if (found === false) {
found = true;
bulbPick = true;
squirPick = true;
$('#bulbasaur').animate({ right: '-=600px' });
$("#bulbasaur").css({ backgroundColor: "grey" });
$('#squirtle').animate({ right: '-=600px' });
$("#squirtle").css({ backgroundColor: "grey" });
$('#charmander').animate({ bottom: '-=300px' });
$("#charmander").css({ backgroundColor: "#85C1E9" });
var input = this;
input.disabled = true;
fighters.push(charmander.hp);
ids.push($('#charnum'));
console.log(ids);
}
})
$("#bulbut").click(function () {
if (found === false) {
found = true;
charPick = true;
squirPick = true;
$('#charmander').animate({ right: '-=600px' });
$("#charmander").css({ backgroundColor: "grey" });
$('#squirtle').animate({ right: '-=600px' });
$("#squirtle").css({ backgroundColor: "grey" });
$('#bulbasaur').animate({ bottom: '-=300px', left: '-=160px' });
$("#bulbasaur").css({ backgroundColor: "#85C1E9" });
var input = this;
input.disabled = true;
fighters.push(bulbasaur.hp)
ids.push($('#bulbnum'));
}
})
$("#squirbut").click(function () {
if (found === false) {
found = true;
charPick = true;
bulbPick = true;
$('#charmander').animate({ right: '-=600px' });
$("#charmander").css({ backgroundColor: "grey" });
$('#bulbasaur').animate({ right: '-=600px' });
$("#bulbasaur").css({ backgroundColor: "grey" });
$('#squirtle').animate({ bottom: '-=300px', left: '-=300px' });
$("#squirtle").css({ backgroundColor: "#85C1E9" });
var input = this;
input.disabled = true;
fighters.push(squirtle.hp)
ids.push($('#squirnum'));
};
});
};
console.log(fighters);
selector();
//select enemy - WORKING
function enemy() {
$("#bulbut").click(function () {
if (bulbPick === true) {
$('#bulbasaur').animate({ right: '-=100px', bottom: '-=100px' });
$("#bulbasaur").css({ backgroundColor: "#F1948A" });
var input = this;
input.disabled = true;
startGame = true;
gameStart();
fighters.push(bulbasaur.hp);
ids.push($('#bulbnum'));
}
});
$("#charbut").click(function () {
if (charPick === true) {
$('#charmander').animate({ right: '-=100px', bottom: '-=100px' });
$("#charmander").css({ backgroundColor: "#F1948A" });
var input = this;
input.disabled = true;
startGame = true;
gameStart();
fighters.push(charmander.hp);
ids.push($('#charnum'));
}
});
$("#squirbut").click(function () {
if (squirPick === true) {
$('#squirtle').animate({ right: '-=100px', bottom: '-=100px' });
$("#squirtle").css({ backgroundColor: "#F1948A" });
var input = this;
input.disabled = true;
startGame = true;
gameStart();
fighters.push(squirtle.hp);
ids.push($('#squirnum'));
}
});
console.log(startGame);
}
enemy();
//start game
function gameStart() {
if (startGame === true) {
//attack button
var button = $('<button/>', {
text: 'Attack!',
click: function () {
var pdamage = Math.floor (Math.random() * 8);
var edamage = Math.floor (Math.random() * 10);
var ptotals = parseInt(fighters[0] - pdamage);
var etotals = parseInt(fighters[1] - edamage);
fighters[0] = ptotals;
ids[0].html = ptotals;
//change player hp visually - WORKING
ids[0].text(ptotals);
//change enemy hp - Working
fighters[1] = etotals;
ids[1].html = etotals;
ids[1].text(etotals);
$('#textbox').text("You dealt " + edamage + " damage! " + "You got attacked for " + pdamage + " damage");
//console.log(ids[0]);
//console.log(ids[1]);
//console.log(fighters[1]);
//console.log(ptotals);
//console.log(pdamage);
if (fighters[1] <= 0 || fighters[1]===0){
winneR();
fighters[1].toString;
fighters[1].html = "faint";
this.disabled=true;
}else if (fighters[0] <= 0){
loseR();
this.disabled=true;
}
}
})
$('#atkButton').append(button);
}
}
//win function
function winneR(){
var msg = "Congratulations! You Won!";
$('#end').append(msg);
}
function loseR(){
var texts = "Your Pokemon fainted!, Healing all Pokemon in 10 seconds!"
$('#end').append(texts);
}
});
The problem I am having is that the attack button which appears after 2 characters have been chosen disappears after I've clicked on it once. I want the button to be up there until the HP of either characters = 0. I'm not sure about how to approach this, any help is appreciated!
p.s. please excuse my poor code work, i've only been doing javascript for a few days.
p.p.s you might want to enlarge the window after you run it.

your problem is when you are adding $('#textbox').text("You dealt " + edamage + " damage! " + "You got attacked for " + pdamage + " damage");
Since your html structure is:
<div id = "textbox">
<div id="atbox">
<div id="atkButton" class="active">
</div>
</div>
</div>
Which means that when you use .text() it replaces whats inside the div with the text so in your case it removes the div #atkButton where you added the button.
So a simple solution would be simply change the html structure and remove the button from the textbox div and you'll be fine.
<div id = "textbox">
</div>
<div id="atbox">
<div id="atkButton" class="active">
</div>
</div>
Here is a working example: https://jsfiddle.net/7q35umvb/2/

Related

Creating a message that pops up at the end of a quiz depending on score

I hope someone can help me but I have just started learning javascript and I have been working on a quiz for a page of a learning website that I am helping to create. I have been asked to add a message that pops up at the end of the quiz but I can't seem to get it to work. Please excuse any terrible obvious mistakes as like I said I have only been looking into it for a couple of days.
I have a div in the html called message that I wanted to the message to appear.
This is the js I have so far. Any tips would be massively appreciated.
(function($) {
$.fn.emc = function(options) {
var defaults = {
key: [],
scoring: "normal",
progress: true
},
settings = $.extend(defaults,options),
$quizItems = $('[data-quiz-item]'),
$choices = $('[data-choices]'),
itemCount = $quizItems.length,
chosen = [],
$option = null,
$label = null;
emcInit();
if (settings.progress) {
var $bar = $('#emc-progress'),
$inner = $('<div id="emc-progress_inner"></div>'),
$perc = $('<span id="emc-progress_ind">0/'+itemCount+'</span>');
$bar.append($inner).prepend($perc);
}
function emcInit() {
$quizItems.each( function(index,value) {
var $this = $(this),
$choiceEl = $this.find('.choices'),
choices = $choiceEl.data('choices');
for (var i = 0; i < choices.length; i++) {
$option = $('<input name="'+index+'" id="'+index+'_'+i+'" type="radio">');
$label = $('<label for="'+index+'_'+i+'">'+choices[i]+'</label>');
$choiceEl.append($option).append($label);
$option.on( 'change', function() {
return getChosen();
});
}
});
}
function getChosen() {
chosen = [];
$choices.each( function() {
var $inputs = $(this).find('input[type="radio"]');
$inputs.each( function(index,value) {
if($(this).is(':checked')) {
chosen.push(index + 1);
}
});
});
getProgress();
}
function getProgress() {
var prog = (chosen.length / itemCount) * 100 + "%",
$submit = $('#emc-submit');
if (settings.progress) {
$perc.text(chosen.length+'/'+itemCount);
$inner.css({height: prog});
}
if (chosen.length === itemCount) {
$submit.addClass('ready-show');
$submit.click( function(){
return scoreNormal();
});
}
}
function scoreNormal() {
var wrong = [],
score = null,
$scoreEl = $('#emc-score');
for (var i = 0; i < itemCount; i++) {
if (chosen[i] != settings.key[i]) {
wrong.push(i);
}
}
$quizItems.each( function(index) {
var $this = $(this);
if ($.inArray(index, wrong) !== -1 ) {
$this.removeClass('item-correct').addClass('item-incorrect');
} else {
$this.removeClass('item-incorrect').addClass('item-correct');
}
});
score = ((itemCount - wrong.length) / itemCount).toFixed(2) * 100 + "%";
$scoreEl.text("You scored a "+score).addClass('new-score');
}
function print(message) {
document.write(message);
}
if (score===100){
print('congratulations');
}else if(score<=99){
print('Try Again');
}
}
}(jQuery));
$(document).emc({
key: ["1","2","1","1","1","1"]
});
Popup Message
form controls tags
template literal interpolation
nested ternaries
Event Delegation
CSS transform and transition driven by .class
Demo
Enter a number in the <input>. To close the popup message, click the X in the upper righthand corner.
$('#quiz').on('change', function(e) {
var score = parseInt($('#score').val(), 10);
var msg = `Your score is ${score}<sup>×</sup><br>`;
var remark = (score === 100) ? `Perfect, great job!`: (score < 100 && score >= 90) ? `Well done`: (score < 90 && score >= 80) ? `Not bad`: (score < 80 && score >= 70) ? `You can do better`:(score < 70 && score >= 60) ? `That's bad`: `Did you even try?`;
$('#msg legend').html(`${msg}${remark}`).addClass('newScore');
$('#msg legend').on('click', 'sup', function(e) {
$(this).parent().removeClass('newScore');
});
});
#msg legend {
position: absolute;
z-index: 1;
transform: scale(0);
transition: 0.6s;
}
#msg legend.newScore {
font-size:5vw;
text-align:center;
transform-origin: left bottom;
transform: scale(2) translate(0,70%);
transition: 0.8s;
}
#msg legend.newScore sup {
cursor:pointer
}
<form id='quiz'>
<fieldset id='msg'>
<legend></legend>
<input id='score' type='number' min='0' max='100'> Enter your test score in the range of 0 to 100
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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();
}
`

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

Add Lightbox in my code

I am working with thumnail image slider (jquery).Here i want to add a icon of zoom.when click then the selected image popup.this is current jquery code.
;(function($) {
// TODO:
// make sure we use ids, dont select stuff outside of plugin
var pluginName = 'pGallery',
defaults = {
printableVersionText: "Printable Version",
prevPhotoText: "<",
nextPhotoText: " >",
prevButtonText: "<",
nextButtonText: "Next >",
mobileCloseMarkup: "<i class='icon-remove'/>",
mobilePrevMarkup: "<i class='icon-chevron-left'/>",
mobileNextMarkup: "<i class='icon-chevron-right'/>",
mobileSlide: true
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new pGallery( this, options ));
}
});
};
// Primary Galleriffic initialization function that should be called on the thumbnail container.
function pGallery(element, options) {
// Extend Gallery Object
$.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this._element = element;
this.init();
}
pGallery.prototype.init = function(){
// here should set elements to variables to avoid searching again
// call methods to set up
// break down methods as much as possible
// simplify initial markup - add it all in init
this.addMarkup();
this.addControls();
}
pGallery.prototype.addMarkup = function() {
// is there a way to make the code in this method prettier? :|
this.$list = $(this._element);
this.$list.wrap("<div id='thumbs-container'/>");
this.$thumbsContainer = this.$list.parent();
this.$pagination = $("<div class='pagination1 '/>");
this.$thumbsContainer.append(this.$pagination.clone());
this.$pagination = this.$thumbsContainer.find("div.pagination1 ");
this.$pGalleryContainer = $("<div id='pGalleryContainer'/>");
this.$pGalleryContainer.insertBefore(this.$thumbsContainer);
this.$pGalleryContainer.append(this.$thumbsContainer);
this.$content = $("<div/>").addClass("pgallery-content");
this.$controls = $("<div/>").addClass("controls");
this.$bigSlideshowContainer = $("<div/>").addClass("big-slideshow-container");
this.$loadingSlideshowContainer = $("<div/>").addClass("loading-slideshow-container");
this.$loadingSlideshowContainer.append(this.$loading = $("<div/>").addClass("loading"));
this.$loadingSlideshowContainer.append(this.$loadingCaptionContainer = $("<div/>").addClass("caption-container"));
this.$slideshowContainer = $("<div/>").addClass("slideshow-container");
this.$slideshowContainer.append(this.$slideshow = $("<div/>").addClass("slideshow"));
this.$slideshowContainer.append(this.$captionContainer = $("<div/>").addClass("caption-container"));
this.$bigSlideshowContainer.append(this.$loadingSlideshowContainer);
this.$bigSlideshowContainer.append(this.$slideshowContainer);
this.$content.append(this.$controls);
this.$content.append(this.$bigSlideshowContainer);
$("body").append(this.$mobileOverlay = $("<div id='mobile-overlay'></div>"));
this.$mobileCloseButton = $("<div id='mobile-close-button'/>");
this.$mobileCloseWrap = $("<div id='mobile-close-wrap'/>").append($("<a href='#'/>").append(this.$mobileCloseButton));
this.$mobileCloseButton.append($(this._defaults.mobileCloseMarkup));
this.$mobilePrevButton = $("<div id='mobile-prev-button'/>");
this.$mobilePrevWrap = $("<div id='mobile-prev-wrap'/>").append($("<a href='#'/>").append(this.$mobilePrevButton));
this.$mobilePrevButton.append($(this._defaults.mobilePrevMarkup));
this.$mobileNextButton = $("<div id='mobile-next-button'/>");
this.$mobileNextWrap = $("<div id='mobile-next-wrap'/>").append($("<a href='#'/>").append(this.$mobileNextButton));
this.$mobileNextButton.append($(this._defaults.mobileNextMarkup));
this.$mobileThumbs = $("<ul/>").addClass("mobile-thumbs");
this.$mobileLoader = $("<div id='mobile-loader'/>");
this.$mobileOverlay.append(this.$mobileCloseWrap);
this.$mobileOverlay.append(this.$mobilePrevWrap);
this.$mobileOverlay.append(this.$mobileNextWrap);
this.$mobileOverlay.append(this.$mobileThumbs);
this.$mobileOverlay.append(this.$mobileLoader);
this.$pGalleryContainer.append(this.$content);
//this.$pGalleryContainer.append(this.$mobileOverlayTemp);
var self = this;
this.$list.children().each(function(i){
var $this = $(this);
$image = $this.find("img"),
imageURI = $image.attr("src"),
title = $image.attr("title");
$image.wrap("<a class='thumb' href='"+imageURI+"'/>");
$image.wrap("<div class='thumb-wrap'/>");
var $thumbWrap = $image.parent();
$thumbWrap.css("background-image", "url('"+imageURI+"')");
$image.hide();
var $caption = $("<div/>").addClass("caption"),
$download = $("<div/>").addClass("magnify").appendTo($caption),
$printable = $("<a/>").attr("href", imageURI).text(self._defaults.printableVersionText).appendTo($download),
$title = $("<div/>").addClass("image-title").text(title).appendTo($caption);
$caption.appendTo($this);
$this.addClass("image"+(i+1));
self.$mobileThumbs.append($("<li/>").addClass("m-image"+(i+1)));
self.overlayImageHtml(i+1);
});
self.$mobileThumbs.children().hide();
}
pGallery.prototype.addControls = function() {
var self = this;
// count the thumbs
this.numThumbs = this.$list.children().length;
this.divWidth = this.$thumbsContainer.width();
this.liWidth = this.$list.children().first().outerWidth(true);
this.currImage = 0;
this.currPage = 0;
this.perPage = 12;
this.changingImage = false;
// arrange them
this.cols = Math.floor(this.divWidth/this.liWidth);
// arrange the left controls
this.numPages = Math.ceil(this.numThumbs/this.perPage);
this.$navPrevButton = $("<a/>").addClass("p-prev").text(this._defaults.prevButtonText).appendTo(this.$pagination);
for (var i = 0; i < this.numPages; i++)
{
this.$pagination.append($("<a/>").addClass("p"+(i+1)).text((i+1)));
var $pageButton = this.$pagination.find(".p"+(i+1));
$pageButton.click(function(e) {
e.preventDefault();
self.pageChange($(this).text());
return false;
});
}
this.$navNextButton = $("<a/>").addClass("p-next").text(this._defaults.nextButtonText).appendTo(this.$pagination);
this.$navPrevButton.click(function(e) {
e.preventDefault();
self.pagePrev();
return false;
});
this.$navNextButton.click(function(e) {
e.preventDefault();
self.pageNext();
return false;
});
this.$navPrevButton.hide();
// make ellipses for hiding the page numbers on smaller screens and hide them
this.$ellRight = $("<span class='r-ell'>...</span>").insertBefore(this.$pagination.children(".p"+this.numPages)).hide();
this.$ellLeft = $("<span class='l-ell'>...</span>").insertAfter(this.$pagination.children(".p1")).hide();
// place the right controls
this.$controls.append(this.$prevButton = $("<a/>").addClass("prev").text(this._defaults.prevPhotoText));
this.$controls.append(this.$nextButton = $("<a/>").addClass("next").text(this._defaults.nextPhotoText));
this.$prevButton.click(function(e) {
e.preventDefault();
self.imagePrev();
return false;
});
this.$nextButton.click(function(e) {
e.preventDefault();
self.imageNext();
return false;
});
// setup thumb clicking
this.$list.find("li > a").click(function(e) {
e.preventDefault();
if (self.mobileScreenSize()){
self.showOverlay($(this).parent().attr('class'));
}
else{
self.changeImage($(this).parent().attr('class'));
}
return false;
});
this.$mobileCloseWrap.children("a").click(function(e) {
e.preventDefault();
self.hideOverlay();
return false;
});
this.$mobileNextWrap.children("a").click(function(e) {
e.preventDefault();
self.imageNext();
return false;
});
this.$mobilePrevWrap.children("a").click(function(e) {
e.preventDefault();
self.imagePrev();
return false;
});
this.changeImage('image1');
var image = this.$list.children().first().find("img").attr('src');
var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
self.resize();
}
}
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key
console.log("escape");
self.hideOverlay();
}
if (e.keyCode == 39) { // right arrow
console.log("right");
self.imageNext();
}
if (e.keyCode == 37) { // right arrow
console.log("left");
self.imagePrev();
}
});
this.resize();
}
pGallery.prototype.changeImage = function(liClass, right) {
right = typeof right !== 'undefined' ? right : true;
if (parseInt(liClass.replace("image","")) == this.currImage)
return;
this.currImage = parseInt(liClass.replace("image",""));
this.$list.children().removeClass("current");
this.$list.children("."+liClass).addClass("current");
var title = this.$list.children("."+liClass).find("a").attr('title');
//var imageURI = this.$list.children("."+liClass).find("div").css("background-image").replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
var imageURI = this.$list.children("."+liClass).find("img").attr('src');
var slideshowHtml = "<img title='"+(title != null?title:"")+"' src='"+imageURI+"'/>";
this.$loadingSlideshowContainer.children(".loading").html(this.$slideshow.html());
this.$slideshow.html(slideshowHtml);
this.$loadingCaptionContainer.html(this.$captionContainer.html());
this.$captionContainer.html(this.$list.children("."+liClass).find(".caption").html());
var time = 500;
if (this.$loadingSlideshowContainer.is(':animated') || this.$slideshowContainer.is(':animated')){
time = 0;
}
if (this.$loadingSlideshowContainer.children(".loading").html() != "")
{
this.$loadingSlideshowContainer.fadeTo(0, 1);
this.$slideshowContainer.fadeTo(0, 0);
this.$loadingSlideshowContainer.fadeTo(time, 0);
this.$slideshowContainer.fadeTo(time, 1);
}
// also do this for the mobile overlay, regardless of its showing or not
this.loadOverlayImage(this.currImage, right);
this.checkPageBounds();
}
pGallery.prototype.resize = function() {
var self = this;
this.$list.children().each(function(){
$(this).height($(this).width());
$(this).find(".thumb-wrap").height($(this).height()-2);
});
this.fixMargins(this.currImage);
}
pGallery.prototype.imageNext = function() {
if (this.currImage == this.numThumbs)
this.changeImage("image1");
else
this.changeImage("image"+(this.currImage+1));
}
pGallery.prototype.imagePrev = function() {
if (this.currImage == 1)
this.changeImage("image"+this.numThumbs, false);
else
this.changeImage("image"+(this.currImage-1), false);
}
pGallery.prototype.pageNext = function() {
if (this.currPage < this.numPages)
this.pageChange(parseInt(this.currPage)+1);
}
pGallery.prototype.pagePrev = function() {
if (this.currPage > 1)
this.pageChange(parseInt(this.currPage)-1);
}
pGallery.prototype.pageChange = function(page, changeSlideshow) {
changeSlideshow = typeof changeSlideshow !== 'undefined' ? changeSlideshow : true;
if (page == this.currPage)
return;
this.currPage = page;
this.$pagination.children().removeClass("current");
this.$pagination.children(".p"+this.currPage).addClass("current");
// hide all thumbs, then show thumbs on current page
this.$list.children().hide();
for (var i = (this.currPage-1)*this.perPage + 1; i < Math.min(this.currPage*this.perPage+1, this.numThumbs+1); i++)
{
this.$list.children(".image" + i).show();
}
if (changeSlideshow)
{
this.changeImage("image"+this.getPageLowerBounds(this.currPage));
}
this.adjustPagination();
this.resize();
// TODO: make this all happen at the same time, and add fadein/fadeout effects
}
pGallery.prototype.checkPageBounds = function() {
// TODO: make sure we're one the right page
// (typically after hiting prev/next image)
var correctPage = this.getPageFromIndex(this.currImage);
if (correctPage != this.currPage)
{
this.pageChange(correctPage, false);
}
}
pGallery.prototype.getPageLowerBounds = function(page) {
return ((this.currPage-1)*this.perPage)+1;
}
pGallery.prototype.getPageUpperBounds = function(page) {
return this.page*this.perPage
}
pGallery.prototype.getPageFromIndex = function(index) {
return (((index-1 - ((index-1)%this.perPage))/this.perPage) +1);
}
pGallery.prototype.adjustPagination = function() {
var tempPage = parseInt(this.currPage);
var tempNumPages = this.numPages;
var totalWidth = 0;
var allowedToRemove = new Array();
this.$pagination.children().each(function(index) {
$(this).show();
totalWidth += $(this).outerWidth(true);
$(this).removeClass("current");
var thisClass = $(this).attr("class");
var thisPageNum = parseInt(thisClass.replace("p",""));
if (!(thisClass == "p-prev" || thisClass == "p-next" ||
thisPageNum == tempPage || thisPageNum == (tempPage+1) ||
thisPageNum == (tempPage-1) || thisPageNum == 1 || thisPageNum == tempNumPages ||
thisClass == "l-ell" || thisClass == "r-ell")){
allowedToRemove.push(thisPageNum);
}
});
if (this.currPage >= this.numPages){
this.$navNextButton.hide();
}
if (this.currPage <= 1){
this.$navPrevButton.hide();
}
this.$ellLeft.hide();
this.$ellRight.hide();
while (allowedToRemove.length > 0 && totalWidth > this.$pagination.width())
{
// hide pages furthest away from current page
// max two ellipsis, at the ends
// do not hide:
// current, adjacent to current, first, last
// if greater/less than current show right/left ellipses
var maxDist = 0;
var maxPage = 0;
for (var i = 0; i < allowedToRemove.length; i++)
{
if (Math.abs(allowedToRemove[i] - this.currPage) > maxDist)
{
maxDist = Math.abs(allowedToRemove[i] - this.currPage);
maxPage = i;
}
}
this.$pagination.children(".p"+allowedToRemove[maxPage]).hide();
allowedToRemove.splice(maxPage, 1);
if (allowedToRemove[maxPage] < this.currPage){
this.$ellLeft.show();
}
if (allowedToRemove[maxPage] > this.currPage){
this.$ellRight.show();
}
totalWidth = 0;
this.$pagination.children(":visible").each(function() {
totalWidth += $(this).outerWidth(true);
});
}
this.$pagination.children(".p"+this.currPage).addClass("current");
}
pGallery.prototype.mobileScreenSize = function(){
if ($(window).width() < 772){ // width in em
return true;
}
else{
return false;
}
}
pGallery.prototype.showOverlay = function(image){
// makes overlay and image appear
// loads in next and previous images
// needs next and prev buttons, close button
// need to dynamically place images to center them
// initialize swiping?
this.$mobileOverlay.show();
$("body").css("overflow", "hidden");
this.changeImage(image, true);
}
pGallery.prototype.loadOverlayImage = function(image, right){
right = typeof right !== 'undefined' ? right : true;
if (this._defaults.mobileSlide){
if (right == true){
this.$mobileThumbs.children(":visible").hide('slide', {direction: 'left'}, 300);
this.$mobileThumbs.children(".m-image"+image).show('slide', {direction: 'right'}, 300);
}
else{
this.$mobileThumbs.children(":visible").hide('slide', {direction: 'right'}, 300);
this.$mobileThumbs.children(".m-image"+image).show('slide', {direction: 'left'}, 300);
}
}
else{
this.$mobileThumbs.children(":visible").hide();
this.$mobileThumbs.children(".m-image"+image).show();
}
this.fixMargins(image);
}
pGallery.prototype.overlayImageHtml = function(image){
var self = this;
var title = this.$list.children(".image" + image).children("a").attr('title');
var medLink = this.$list.children(".image" + image).children("a").attr('href');
var $image = $("<img title='"+(title != null?title:"")+"' src='"+medLink+"'/>");
this.$mobileThumbs.children(".m-image"+image).empty().append($image);
$image.on("load", function(){
self.fixMargins(image);
});
}
pGallery.prototype.fixMargins = function(image){
// good lord fix this
var self = this;
this.$mobileThumbs.find(".m-image"+image+ " > img").each(function(i){
$(this).css("margin-left",self.realWidth($(this), true)/-2).css("margin-top",self.realHeight($(this), true)/-2);
});
}
pGallery.prototype.hideOverlay = function(){
// hide overlay
this.$mobileOverlay.hide();
$("body").css("overflow", "auto");
}
pGallery.prototype.realWidth = function(obj, limitToWindow){
var clone = obj.clone();
clone.show();
clone.css("visibility","hidden");
if (limitToWindow){
clone.css("max-width", "100%");
clone.css("max-height", "100%");
}
$('body').append(clone);
var width = clone.outerWidth();
clone.remove();
return width;
}
pGallery.prototype.realHeight = function(obj, limitToWindow){
var clone = obj.clone();
clone.show();
clone.css("visibility","hidden");
if (limitToWindow){
clone.css("max-width", "100%");
clone.css("max-height", "100%");
}
$('body').append(clone);
var height = clone.outerHeight();
clone.remove();
return height;
}
})(jQuery);
This is html code
<ul id="thumbs">
<li>
<img src="image/01.jpg" title="" />
<div class="caption">
<div class="image-title">
On Canvas 24 x 36in <p style="color:#999">Code:0000</p>
<span>*Sold..</span></div>
<div class="image-title"> <p class="fb-like" data-href="data1/polo_images/p_image_1.jpg" data-width="100" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></p>
</div>
</div>
</li>
<li>
<img src="image/02.jpg" title="" />
<div class="caption">
<div class="image-title">
On Canvas 24 x 36in <p style="color:#999">Code:0000</p>
<span>*Sold..</span></div>
<div class="image-title"> <p class="fb-like" data-href="data1/polo_images/p_image_1.jpg" data-width="100" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></p>
</div>
</div>
</li>
</ul>
</div>
I want to have lightbox open when zoom icon clicked .

Fix Popup to lift up smoothly

I create a pop-up dialog box which lift up on left bottom while user scroll page.
You can see it live here- http://uposonghar.com/jobs/odesk/daniel/new/
My problem is it does not smoothly lift up first time, then it is ok. Anyone please suggest any idea to fix it. Need to make smoothly lift up.
My code
<div id="scrolltriggered" style="width: 310px; left: 10px; bottom: 10px;">
<div id="inscroll">
x<a href="http://www.google.com" target="_blank"><img src="images/buyersguide.png" alt="Free Resources" height="235" width="310">
</a>
</div>
</div>
<script type="text/javascript">
var stb = {
hascolsed: false,
cookieLife: 7,
triggerHeight: 30,
stbElement: ""
};
</script>
Javascript Code-
if (typeof stb === "undefined")
var stb = {};
jQuery(document).ready(function () {
jQuery("#closebox").click(function () {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'-210px' }, 700, function () {
jQuery('#scrolltriggered').hide();
stb.hascolsed = true;
jQuery.cookie('nopopup', 'true', { expires: stb.cookieLife, path: '/' });
});
return false;
});
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
stb.boxOffset = '';
if (stb.stbElement != '') {
stb.boxOffset = jQuery(stb.stbElement).offset().top;
}
jQuery(window).resize(function () {
stb.windowheight = jQuery(window).height();
stb.totalheight = jQuery(document).height();
});
jQuery(window).scroll(function () {
stb.y = jQuery(window).scrollTop();
stb.boxHeight = jQuery('#scrolltriggered').outerHeight();
stb.scrolled = parseInt((stb.y + stb.windowheight) / stb.totalheight * 100);
if (stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":hidden") && stb.hascolsed != true) {
jQuery('#scrolltriggered').show();
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':'10px' }, 700, function () {
});
}
else if (!stb.showBox(stb.scrolled, stb.triggerHeight, stb.y) && jQuery('#scrolltriggered').is(":visible") && jQuery('#scrolltriggered:animated').length < 1) {
jQuery('#scrolltriggered').stop(true, true).animate({ 'bottom':-stb.boxHeight }, 700, function () {
jQuery('#scrolltriggered').hide();
});
}
});
jQuery('#stbContactForm').submit(function (e) {
e.preventDefault();
stb.data = jQuery('#stbContactForm').serialize();
jQuery.ajax({
url:stbAjax.ajaxurl,
data:{
action:'stb_form_process',
stbNonce:stbAjax.stbNonce,
data:stb.data
},
dataType:'html',
type:'post'
}).done(function (data) {
jQuery('#stbMsgArea').html(data).show('fast');
});
return false;
});
});
(function(stb_helpers) {
stb_helpers.showBox = function(scrolled, triggerHeight, y) {
if (stb.isMobile()) return false;
if (stb.stbElement == '') {
if (scrolled >= triggerHeight) {
return true;
}
}
else {
if (stb.boxOffset < (stb.windowheight + y)) {
return true;
}
}
return false;
};
stb_helpers.isMobile = function(){
if (navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
) {
return true;
}
else return false;
}
})(stb);
i think you need css changes, copy paste the following in your aspx
<div style="width: 310px; left: 10px; bottom: -225px; display: none;" id="scrolltriggered">
Hope it Helps
All you need to do is add the following line to your document ready as the First line
$("#scrolltriggered").css({bottom: -235});
This will make sure that the popup is scrolled to the bottom by 235px. If you need it to scroll variably add the Elements height by using jquery selector.
See the Fiddle Here

Categories