Showing multiple sticky header while scroll down the webpage - javascript

I am a beginner in jQuery. As willing to develop a mobile website, I would like to implement sticky header for enhancing the user experiences.
Here are some codes of my work but it seems not work as calculation of the "top".
HTML:
<div class="fixed-header">
<div class="header_item" id="head_a"> A </div>
<div class="header_item" id="head_b"> B </div>
<div class="header_item" id="head_c"> C </div>
<div class="header_item" id="head_d"> D </div>
<div class="header_item" id="head_e"> E </div>
</div>
javascript and jQuery:
var $totalImageHeight;
$(window).on("load", function() { //Fires when DOM is loaded
getImageSizes();
$(window).resize(function() { //Fires when window is resized
getImageSizes();
});
});
function getImageSizes() {
$(".insurance_item img").each(function(count) {
var $this = $(this);
$imageHeight = $this.height();
$totalImageHeight = $imageHeight * (count + 1);
});
}
var stickyHeaders = (function() {
var $window = $(window),
$stickies;
var load = function(stickies) {
if (typeof stickies === "object" && stickies instanceof jQuery && stickies.length > 0) {
$stickies = stickies.each(function() {
var $thisSticky = $(this).wrap('<div class="followWrap" style="height: 0;"/>');
$thisSticky
.data('originalPosition', $thisSticky.offset().top)
.data('originalHeight', $thisSticky.outerHeight( 75 ))
.parent().height($thisSticky.outerHeight( 75 ));
});
$window.off("scroll.stickies").on("scroll.stickies", function() {
_whenScrolling();
});
}
};
var _whenScrolling = function() {
$stickies.each(function(i) {
var $thisSticky = $(this),
$stickyPosition = $thisSticky.data('originalPosition');
if ($stickyPosition <= $window.scrollTop()) {
var $nextSticky = $stickies.eq(i + 1);
$nextStickyPosition = $totalImageHeight - $nextSticky.data('originalPosition') - $thisSticky.data('originalHeight');
$thisSticky.addClass("fixed").css("top", $nextStickyPosition);
if ($nextSticky.length > 0 && $thisSticky.offset().top >= $nextStickyPosition) {
$thisSticky.addClass("absolute").css("top", $nextStickyPosition);
}
}else{ //scroll up and disable the fixed header
var $prevSticky = $stickies.eq(i - 1);
$thisSticky.removeClass("fixed");
if($prevSticky.length>0&&$window.scrollTop()<=
$thisSticky.data('originalPosition') -
$thisSticky.data('originalHeight')){
$prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
};
return {
load: load
};
})();
$(function() {
stickyHeaders.load($(".header_item"));
});

Sorry for the late answer. I create an new javascript for implementing this function.
Code:
var $window = $(window);
var imageArr = [];
var iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
console.log(iOS);
$(window).on("load", function() { //Fires when DOM is loaded
getImageSizes();
window.requestAnimationFrame(tick);
$(window).resize(function() { //Fires when window is resized
getImageSizes();
scrollDetect(imageArr);
});
});
function getImageSizes() { //get the numbers of images and its outerHeight
var $items = $(".insurance_item");
for(var c = 0; c < $items.length; c++){
imageArr[c] = $($items[c]).outerHeight();
}
}
function scrollDetect(imageArr){ //show the title header of image once the image is offscreen.
var $items = $('.header_item');
for(var c = 0; c < imageArr.length; c++){
if($window.scrollTop() >= (imageArr[c] * (c+1)) - $('#fixed-header').outerHeight()){
$items.eq(c).show();
}else{
$items.eq(c).hide();
}
}
window.requestAnimationFrame(tick); //prevent the frame lost and make a incorrect calculation
}
function tick(){
scrollDetect(imageArr);
};
May be some better solution for solving this situation, thanks for everyone.

Related

Wordpress: Homepage js is conflicting with js of plugin of portfolio page

I've downloaded Awesome Filterable Portfolio plugin , It was working fine.. but when I added a js file for scrolling carousel on home page, The js of that plugin stoped working..
I've added my cr-scroll.js file in functions.php as given below:
wp_register_script('java1', get_template_directory_uri() . '/js/cr-scroll.js', array( 'jquery' ));
wp_enqueue_script( 'java1' );
What I've Tried:
$.noConflict();
Replaced $ with jquery
Wrap the code in
(function($){
$(document).ready(function(){
});
})(jQuery);
but nothing worked.
My js file is cr-scroll.js:
(function($){
$(document).ready(function($) {
$.fn.make_carousel = function() {
var speed = 0;
var scroll = 0;
var con = $(this);
var con_w = con.width();
var max_scroll = con[0].scrollWidth - con.outerWidth();
var prev_frame = new Date().getTime();
con.on('mousemove', function(e) {
var mouse_x = e.pageX - con.offset().left;
var mouseperc = 100 * mouse_x / con_w;
speed = mouseperc - 50;
}).on ( 'mouseleave', function() {
speed = 0;});
function updatescroll() {
var cur_frame = new Date().getTime();
var time_elapsed = cur_frame - prev_frame;
prev_frame = cur_frame;
if (speed !== 0) {
scroll += speed * time_elapsed / 50;
if (scroll < 0) scroll = 0;
if (scroll > max_scroll) scroll = max_scroll;
con.scrollLeft(scroll);
}
window.requestAnimationFrame(updatescroll);
}
window.requestAnimationFrame(updatescroll);
}
$("#carousel1").make_carousel();
$("#carousel2").make_carousel();
function reset(){
$('.maincontent').find('*').removeAttr('class');
document.getElementById('step1').setAttribute("class", "visible");
}
function back(){
var previous_class = $('.visible').data('previous');
if(previous_class != ''){
var current_class = $('.visible').attr('id');
document.getElementById(current_class).setAttribute("class","");
document.getElementById(previous_class).setAttribute("class","visible");
}
}
function show_next(current,next) {
document.getElementById(current).setAttribute("class", "hidden");
document.getElementById(next).setAttribute("class", "visible");
}
function show_hide(show_ele,hide_ele) {
document.getElementById(show_ele).style.display = "block";
document.getElementById(hide_ele).style.display = "none";
}
function load_after_sec(id) {
count = 0;
wordsArray = ["5", "4", "3", "2", "1"];
var timerID = setInterval(function () {
count++;
if(count == 5){
$("#"+id).show();
$("#seconds_counter").hide();
clearInterval(timerID);
} else {
$("#num_sec").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}
}, 2000);
}
function showButton(){
document.getElementById("btn_repeat").style.display='block';
}
});
})(jQuery);
In home page go to portfolio section, it is scrolling because of js, and after clicking on visit portfolio button, you'll be redirected to portfolio page and the filters of portfolio is not clickable and changeable because of js confliction.
The console gives an error for that cr-scroll.js file that con[0] is undefined.
If I remove this file then plugin works fine, why it is conflicting?
Any help will be appreciated, Thank you in advance.

Unable to combine functions in to one file

I have two functions, one to show a gallery of images and one for a smooth scroll up icon. The problem is when I use them separately, both of them works. But when I put them in the same file only the first one works. I can t figure out the problem. I am using jquery-2.0.3
Here is my Code:
$(function() {
$('.demo li').picEyes();
// Caching the Scroll Top Element
// console.log("function move to top");
var ScrollButton = $("#scroll");
$(window).scroll(function() {
// console.log($(this).scrollTop());
if ($(this).scrollTop() >= 50) {
ScrollButton.show()
} else {
ScrollButton.hide();
}
});
// Click On Button To Scroll To Top Of The Page
ScrollButton.click(function() {
$("html,body").animate({
scrollTop: 0
}, 800);
});
});
the code of picEyes function:
(function($){
$.fn.picEyes = function(){
var $obj = this;
var num,zg = $obj.length - 1;
var win_w = $(window).width();
var win_h = $(window).height();
var eyeHtml = '<div class="picshade"></div>'
+'<a class="pictures_eyes_close" href="javascript:;"></a>'
+'<div class="pictures_eyes">'
+'<div class="pictures_eyes_in">'
+'<img src="" />'
+'<div class="next"></div>'
+'<div class="prev"></div>'
+'</div>'
+'</div>'
+'<div class="pictures_eyes_indicators"></div>';
$('body').append(eyeHtml);
$obj.click(function() {
$(".picshade").css("height", win_h);
var n = $(this).find("img").attr('src');
$(".pictures_eyes img").attr("src", n);
num = $obj.index(this);
popwin($('.pictures_eyes'));
});
$(".pictures_eyes_close,.picshade,.pictures_eyes").click(function() {
$(".picshade,.pictures_eyes,.pictures_eyes_close,.pictures_eyes_indicators").fadeOut();
$('body').css({'overflow':'auto'});
});
$('.pictures_eyes img').click(function(e){
stopPropagation(e);
});
$(".next").click(function(e){
if(num < zg){
num++;
}else{
num = 0;
}
var xx = $obj.eq(num).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
stopPropagation(e);
popwin($('.pictures_eyes'));
});
$(".prev").click(function(e){
if(num > 0){
num--;
}else{
num = zg;
}
var xx = $obj.eq(num).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
stopPropagation(e);
popwin($('.pictures_eyes'));
});
function popwin(obj){
$('body').css({'overflow':'hidden'});
var Pwidth = obj.width();
var Pheight = obj.height();
obj.css({left:(win_w - Pwidth)/2,top:(win_h - Pheight)/2}).show();
$('.picshade,.pictures_eyes_close').fadeIn();
indicatorsList();
}
function updatePlace(obj){
var Pwidth = obj.width();
var Pheight = obj.height();
obj.css({left:(win_w - Pwidth)/2,top:(win_h - Pheight)/2});
}
function indicatorsList(){
var indHtml = '';
$obj.each(function(){
var img = $(this).find('img').attr('src');
indHtml +='<img src="'+img+'"/>';
});
$('.pictures_eyes_indicators').html(indHtml).fadeIn();
$('.pictures_eyes_indicators a').eq(num).addClass('current').siblings().removeClass('current');
$('.pictures_eyes_indicators a').click(function(){
$(this).addClass('current').siblings().removeClass('current');
var xx = $(this).find('img').attr("src");
$(".pictures_eyes img").attr("src", xx);
updatePlace($('.pictures_eyes'));
});
}
function stopPropagation(e) {
e = e || window.event;
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
}
})(jQuery);
You should add click event handler, when DOM will be ready, do like this:-
$(function () {
$('.demo li').picEyes();
// Caching the Scroll Top Element
// console.log("function move to top");
//var ScrollButton =ScrollButton.click
var ScrollButton = $("#scroll")
$(window).scroll(function () {
// console.log($(this).scrollTop());
if ($(this).scrollTop() >= 50) {
ScrollButton.show()
} else {
ScrollButton.hide();
}
});
// Click On Button To Scroll To Top Of The Page
ScrollButton.click(function () {
$("html,body").animate({
scrollTop: 0
}, 800);
});
});
I bet both scripts have own ScrollButton element, and while gallery is loaded it owerwrites behaviour of other ScrollButton element.
I put the call of picEyes function outside of the main function and somehow worked !

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 .

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);

How to smoothly scroll a browser window using hashes with a fixed element on top?

I have a website that has a fixed navigation bar at the top that contains links to achors in the rest of the content like so:
<header style="position:fixed">
Scroll to Headline Hello
</header>
<article>
<h1><a name="hello" id="hello">Hello</a><h1>
</article>
When someone clicks on the link, the corresponding headline is obscured by the header, because the browser positions it directly at the beginning of the viewport. I tried to use the csstricks' jQuery-script described here http://css-tricks.com/snippets/jquery/smooth-scrolling/ to smootly scroll to a targetOffset + heightOfHeader but that just makes the content jump randomly up and down.
Here is the script:
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
Any help would be appreciated.
I see that you're tagging the question with jquery. I like to use scrollTo plugin to accomplish this.
http://flesler.blogspot.com/2007/10/jqueryscrollto.html

Categories