Ext JS custom Tooltip class not working - javascript

I went of Ext's QuickTips to make this custom tooltip, that should show a tooltip when over an element with a 'my_tip' attribute.
For example,
<div class="some class" my_tip="This is my tip text">
When the page is loaded, it adds the following markup to the HTML, which is correct:
<div class="x-layer my_tool_tip_layer" id="ext-gen7" style="position: absolute; z-index: 20000; visibility: hidden; left: -10000px; top: -10000px;">
<div class="my_tool_tip" id="ext-gen8"> </div>
</div>
What should happen is when I hover the mouse over the element with the 'my_tip' attribute, it should update the above div's style attribute and replace &nbsp with the contents of the my_tip class.
Like this:
<div class="x-layer my_tool_tip_layer displayed" id="ext-gen7" style="position: absolute; z-index: 20000; visibility: visible; left: 160px; top: 30px;">
<div class="my_tool_tip" id="ext-gen8">This is my tip text</div>
</div>
I have a css file handling the styling of the tooltip, but my problem now is just getting the html to update to the correct events, which it is not doing.
Below is the javascript for the tooltip. Any help would be very much appreciated.
Thank you
myToolTips=function()
{
var mytt_ext_lyr=null;
var mytt_text_el=null;
var mytt_visible=false;
var mytt_hide_proc=null;
var mytt_show_proc=null;
var mytt_tip_text='';
var mytt_hide_delay = 10000;
var mytt_show_delay = 200;
var mytt_started = false;
var mytt_last_xy = null;
var mytt_mouse_y_offset = 20;
var mytt_track_mouse = false;
var mytt_initialized = false;
var mytt_singleton = null;
var mytt_max_search_depth = 5;
var on_over = function(evt) {
var target = evt.target;
var depth = 0;
while (target && target.nodeType == 1 && !target.getAttribute('my_tip') && depth < mytt_max_search_depth) {
++depth;
target = target.parentNode;
}
if (!target || target.nodeType != 1 || !target.getAttribute('my_tip')) {
if (mytt_visible)
hide();
return;
}
var new_tip = target.getAttribute('my_tip');
if (new_tip != mytt_tip_text && mytt_visible)
hide();
if (target.getAttribute('clip_tip') && target.getAttribute('clip_tip') == 'true') {
for (var i = 0; i < target.childNodes.length; ++i) {
var child = target.childNodes[i];
if (child.scrollWidth <= child.offsetWidth) {
return;
} else {
break;
}
}
}
if (target.getAttribute('clip_tip') && target.getAttribute('clip_tip') == 'this_node') {
if (target.scrollWidth <= target.offsetWidth)
return;
}
var mouse_xy = evt.getXY();
var tip = {mouse_xy: mouse_xy, new_tip: new_tip, target: target}
mytt_show_proc = show.defer(mytt_show_delay, mytt_singleton, [tip]);
mytt_started = true;
};
var on_move = function (evt) {
if (mytt_visible) {
if (mytt_track_mouse) {
var mouse_xy = evt.getXY();
mouse_xy[1] += mytt_mouse_y_offset;
mytt_ext_lyr.setXY(mouse_xy);
}
}
else if (mytt_started)
mytt_last_xy = evt.getXY();
};
var on_out=function(evt) {
hide();
};
var on_click = function(evt) {
var target = evt.target;
var depth = 0;
while (target && target.nodeType == 1 && !target.getAttribute('my_tip') && depth < mytt_max_search_depth) {
++depth;
target = target.parentNode;
}
if (!target || target.nodeType != 1 || !target.getAttribute('my_tip'))
hide();
};
var show=function(mytt) {
var tip=mytt.new_tip;
var mouse_xy=mytt.mouse_xy;
if(mytt_last_xy)
mouse_xy=mytt_last_xy;
if(!mytt_visible) {
if(tip) {
mytt_tip_text=tip;
mytt_text_el.update(mytt_tip_text.replace(/\[\[/g,"<").replace(/\]\]/g,">"));
}
mytt_ext_lyr.show();
mytt_ext_lyr.addClass('displayed');
mytt_visible=true;
if(!mytt_hide_proc)
mytt_hide_proc=setTimeout(hide,mytt_hide_delay);
}
var db=Ext.get(document.body);
var dw=db.getWidth();
var dh=db.getHeight();
if (mytt.target.getAttribute('top_tip') === 'true') {
var telm = Ext.get(mytt.target);
var left = telm.getLeft();
var width_diff = db.getWidth() - (left + mytt_ext_lyr.getWidth());
if (width_diff < 5)
left+=width_diff-15;
mytt_ext_lyr.dom.style.right='';
mytt_ext_lyr.dom.style.top='';
mytt_ext_lyr.dom.style.left=left+'px';
mytt_ext_lyr.dom.style.bottom=(dh-telm.getTop())+'px';
mytt_ext_lyr.sync();
}
else {
mouse_xy[1]+=mytt_mouse_y_offset;
var width_diff=db.getWidth()-(mouse_xy[0]+mytt_ext_lyr.getWidth());
if(width_diff<5)
mouse_xy[0]+=width_diff-15;
mytt_ext_lyr.setXY(mouse_xy);
}
if(mytt_show_proc) {
clearTimeout(mytt_show_proc);
mytt_show_proc=null;
}
};
var hide=function() {
mytt_ext_lyr.hide();
mytt_ext_lyr.removeClass('displayed');
mytt_visible=false;
mytt_started=false;
mytt_last_xy=null;
if(mytt_hide_proc) {
clearTimeout(mytt_hide_proc);
mytt_hide_proc=null;
}
if(mytt_show_proc) {
clearTimeout(mytt_show_proc);
mytt_show_proc=null;
}
};
return {
init:function() {
mytt_singleton=myToolTips;
if(!mytt_initialized) {
if(!Ext.isReady) {
Ext.onReady(myToolTips.init,myToolTips);
return;
}
mytt_ext_lyr=new Ext.Layer({cls:'my_tool_tip_layer',shim:true,constrain:true});
mytt_ext_lyr.fxDefaults={stopFx:true};
mytt_ext_lyr.update('<div class="my_tool_tip"> </div>');
mytt_text_el=mytt_ext_lyr.child('div.my_tool_tip');
mytt_text_el.update(' ');
var doc=Ext.get(document);
doc.on('mouseover',on_over);
doc.on('mouseout',on_out);
doc.on('mousemove',on_move);
doc.on('click',on_click);
mytt_initialized=true;
}
},
ready:function() {
return mytt_initialized;
}
};
}();
// make tooltips work
myToolTips.init();

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>

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 .

Why isn't it possible to change max-height with % in javascript?

I'm trying to build a responsive menu, with a hamburger icon. I want the menu list to slide in and out, no jquery - pure javascript only.
HTML :
<div id="animation">
</div>
<button id="toggle">Toggle</button>
CSS :
div {
width: 300px;
height: 300px;
background-color: blue;
}
Javascript :
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback){
var inter = -1, start = 100, end = 0;
if(type==true){
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function(){
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if(start == end){
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function(){
animate(hidden, function(){
hidden = (hidden == false) ? true : false;
});
}
div.style.maxHeight = "50%";
The problem is that proportional height in an element needs a fixed height on the parent, and you didn't provided any parent with a fixed height because for the maxHeight property too the % Defines the maximum height in % of the parent element.
You have to put your div in a parent container with a fixed height, this is your working code:
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback) {
var inter = -1,
start = 100,
end = 0;
if (type) {
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function() {
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function() {
animate(hidden, function() {
hidden = !hidden ;
});
}
div.style.maxHeight = "50%";
#animation {
width: 300px;
height: 300px;
background-color: blue;
}
#parent {
width: 500px;
height: 500px;
}
<div id="parent">
<div id="animation">
</div>
<button id="toggle">Toggle</button>
</div>
Note:
As stated in comments there are some statements in your JavaScript code that need to be adjusted:
if(type==true) can be written as if(type).
hidden = (hidden == false) ? true : false; can be shortened to hidden = !hidden
There seems to be a few errors with your code. I have fixed the js and added comments to what I have changed
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function (type, callback) {
var start = 100,
end = 0;
if (type) {
start = 0;
end = 100;
}
var si = setInterval(function () {
if (type) { // check whether to open or close animation
start++;
} else {
start--
}
div.style.maxHeight = start + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
callback.call(this); // do the callback function
}
var hidden = false;
but.onclick = function () {
animate(hidden, function () {
hidden = !hidden; // set hidden to opposite
});
}
/*make sure parent container has a height set or max height won't work*/
html, body {
height:100%;
margin:0;
padding:0;
}
div {
width: 300px;
height: 300px;
background-color: blue;
}
<div id="animation"></div>
<button id="toggle">Toggle</button>
Example Fiddle

How to make expand all/collapse all button in this certain script?

i would like to ask for help in a simple task i really need to do at my work (I am a javascript newbie). I made a simple collapsible list with script provided by this guy http://code.stephenmorley.org/javascript/collapsible-lists/ but what i need right now are two simple buttons as stated in the title: expand all and collapse whole list. Do you guys know if something like that can be implemented in this certain script? Please help :)
var CollapsibleLists = new function () {
this.apply = function (_1) {
var _2 = document.getElementsByTagName("ul");
for (var _3 = 0; _3 < _2.length; _3++) {
if (_2[_3].className.match(/(^| )collapsibleList( |$)/)) {
this.applyTo(_2[_3], true);
if (!_1) {
var _4 = _2[_3].getElementsByTagName("ul");
for (var _5 = 0; _5 < _4.length; _5++) {
_4[_5].className += " collapsibleList";
}
}
}
}
};
this.applyTo = function (_6, _7) {
var _8 = _6.getElementsByTagName("li");
for (var _9 = 0; _9 < _8.length; _9++) {
if (!_7 || _6 == _8[_9].parentNode) {
if (_8[_9].addEventListener) {
_8[_9].addEventListener("mousedown", function (e) {
e.preventDefault();
}, false);
} else {
_8[_9].attachEvent("onselectstart", function () {
event.returnValue = false;
});
}
if (_8[_9].addEventListener) {
_8[_9].addEventListener("click", _a(_8[_9]), false);
} else {
_8[_9].attachEvent("onclick", _a(_8[_9]));
}
_b(_8[_9]);
}
}
};
function _a(_c) {
return function (e) {
if (!e) {
e = window.event;
}
var _d = (e.target ? e.target : e.srcElement);
while (_d.nodeName != "LI") {
_d = _d.parentNode;
}
if (_d == _c) {
_b(_c);
}
};
};
function _b(_e) {
var _f = _e.className.match(/(^| )collapsibleListClosed( |$)/);
var uls = _e.getElementsByTagName("ul");
for (var _10 = 0; _10 < uls.length; _10++) {
var li = uls[_10];
while (li.nodeName != "LI") {
li = li.parentNode;
}
if (li == _e) {
uls[_10].style.display = (_f ? "block" : "none");
}
}
_e.className = _e.className.replace(/(^| )collapsibleList(Open|Closed)( |$)/, "");
if (uls.length > 0) {
_e.className += " collapsibleList" + (_f ? "Open" : "Closed");
}
};
}();
It is important to understand why a post-order traversal is used. If you were to just iterate through from the first collapsible list li, it's 'children' may (will) change when expanded/collapsed, causing them to be undefined when you go to click() them.
In your .html
<head>
...
<script>
function listExpansion() {
var element = document.getElementById('listHeader');
if (element.innerText == 'Expand All') {
element.innerHTML = 'Collapse All';
CollapsibleLists.collapse(false);
} else {
element.innerHTML = 'Expand All';
CollapsibleLists.collapse(true);
}
}
</script>
...
</head>
<body>
<div class="header" id="listHeader" onClick="listExpansion()">Expand All</div>
<div class="content">
<ul class="collapsibleList" id="hubList"></ul>
</div>
</body>
In your collapsibleLists.js
var CollapsibleLists =
new function(){
...
// Post-order traversal of the collapsible list(s)
// if collapse is true, then all list items implode, else they explode.
this.collapse = function(collapse){
// find all elements with class collapsibleList(Open|Closed) and click them
var elements = document.getElementsByClassName('collapsibleList' + (collapse ? 'Open' : 'Closed'));
for (var i = elements.length; i--;) {
elements[i].click();
}
};
...
}();

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