Can't append to second container - javascript

I have the following script:
(function($) {
$.fn.easyPaginate = function(options){
var defaults = {
step: 4,
delay: 100,
numeric: true,
nextprev: true,
controls: 'pagination',
current: 'current'
};
var options = $.extend(defaults, options);
var step = options.step;
var lower, upper;
var children = $(this).children();
var count = children.length;
var obj, next, prev;
var page = 1;
var timeout;
var clicked = false;
function show(){
clearTimeout(timeout);
lower = ((page-1) * step);
upper = lower+step;
$(children).each(function(i){
var child = $(this);
child.hide();
if(i>=lower && i<upper){ setTimeout(function(){ child.fadeIn('fast') }, ( i-( Math.floor(i/step) * step) )*options.delay ); }
if(options.nextprev){
if(upper >= count) { next.addClass('stop'); } else { next.removeClass('stop'); };
if(lower >= 1) { prev.removeClass('stop'); } else { prev.addClass('stop'); };
};
});
$('li','#'+ options.controls).removeClass(options.current);
$('li[data-index="'+page+'"]','#'+ options.controls).addClass(options.current);
if(options.auto){
if(options.clickstop && clicked){}else{ timeout = setTimeout(auto,options.pause); };
};
};
function auto(){
if(upper <= count){ page++; show(); }
else { page--; show(); }
};
this.each(function(){
obj = this;
if(count>step){
var pages = Math.floor(count/step);
if((count/step) > pages) pages++;
var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>').insertAfter(obj);
if(options.nextprev){
prev = $('<li class="prev">prev</li>')
.appendTo(ol)
.bind('click', function() {
//check to see if there are any more pages in the negative direction
if (page > 1) {
clicked = true;
page--;
show();
}
});
}
if(options.numeric){
for(var i=1;i<=pages;i++){
$('<li data-index="'+ i +'">'+ i +'</li>')
.appendTo(ol)
.click(function(){
clicked = true;
page = $(this).attr('data-index');
show();
});
};
};
if(options.nextprev){
next = $('<li class="next">next</li>')
.appendTo(ol)
.bind('click', function() {
//check to see if there are any pages in the positive direction
if (page < (count / 4)) {
clicked = true;
page++;
show();
}
});
}
show();
};
});
};
})(jQuery);
jQuery(function($){
$('ul.news').easyPaginate({step:4});
});
which is a carousel-like plugin that produces this html structure for the navigation:
<ol id="pagination" class="pagin"><li class="prev">prev</li><li data-index="1" class="">1</li><li data-index="2" class="">2</li><li data-index="3" class="current">3</li><li class="next stop">next</li></ol>
And all I want is to enclose this list in a div. Seems simple, but appendTo doesn't want to cooperate with me, or I'm doing something wrong (I'd appreciate if you would help me understand what that is..)
So I'm modifying as such:
var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>');
var tiv = $('<div id="lala"></div>');
ol.appendTo('#lala');
tiv.insertAfter(obj);
I know how to chain, but I'm in "debugging" mode trying to understand why I don't get the result I imagine I would get:
<div id="lala>
<ol id="pagination><li>...... </li></ol>
</div>
I tried putting some console.log's to see the status of my variables but couldn't find something useful.. I guess there's something with DOM insertion I don't get.

You're appending the <ol> element to #lala before adding the latter to the document. There's nothing wrong with this, but since you're using an id selector, and the target element is not part of the document yet, the selector will not match anything.
To fix this, you can write:
var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>');
var tiv = $('<div id="lala"></div>');
ol.appendTo(tiv);
tiv.insertAfter(obj);
Or:
var ol = $('<ol id="'+ options.controls +'" class="pagin"></ol>');
var tiv = $('<div id="lala"></div>');
tiv.insertAfter(obj);
ol.appendTo('#lala');

Related

jQuery - Multiple expanding galleries in tabs

I'm trying to get this code "Reveal gallery by Roko C. Buljan" - http://jsbin.com/zariku/9/edit?html,css,js,output - to work in multiple tabs here:
http://codepen.io/anon/pen/QjyMwg
JS:
var $prvw = $('#preview'),
$gall = $('.gooGallery'),
$li = $gall.find("li"),
$img = $prvw.find("img"),
$alt1 = $prvw.find("h2"),
$alt2 = $prvw.find("p"),
$full = $("<li />", {"class":"full", html:$prvw});
$li.attr("data-src", function(i, v){
$(this).css({backgroundImage: "url("+v+")"});
}).on("click", function( evt ){
var $el = $(this),
d = $el.data(),
$clone = $full.clone();
$el.toggleClass("active").siblings().removeClass("active");
$prvw.hide();
$full.after($clone);
$clone.find(">div").slideUp(function(){
$clone.remove();
});
if(!$el.hasClass("active")) return;
$img.attr("src", d.src);
$alt1.text(d.alt);
$alt2.text(d.title);
$li.filter(function(i, el){
return el.getBoundingClientRect().top < evt.clientY;
}).last().after($full);
$prvw.slideDown();
});
$(window).on("resize", function(){
$full.remove();
$li.removeClass("active");
});
2nd tab is working fine, but, when I'll try to open the first one the div isn't shown on the right position.
Can anyone please help me with a hint?
You're trying to use the same preview div for both gallerys. Try having 2 previews. Quickest way I could think would be do to something like this (be warned, this is kinda ugly):
var i = 1;
$('.gooGallery').each(function() {
var $gall = $(this);
var $prvw = $('#preview' + i); i = i+1;
var $li = $gall.find("li")
var $img = $prvw.find("img")
var $alt1 = $prvw.find("h2")
var $alt2 = $prvw.find("p")
var $full = $("<li />", {
"class" : "full",
html : $prvw
});
$li.attr("data-src", function (i, v) {
$(this).css({
backgroundImage : "url(" + v + ")"
});
}).on("click", function (evt) {
var $el = $(this),
d = $el.data(),
$clone = $full.clone(true);
$el.toggleClass("active").siblings().removeClass("active");
$prvw.hide();
$full.after($clone);
$clone.find(">div").slideUp(function () {
$clone.remove();
});
if (!$el.hasClass("active"))
return;
$img.attr("src", d.src);
$alt1.text(d.alt);
$alt2.text(d.title);
$li.filter(function (i, el) {
return el.getBoundingClientRect().top < evt.clientY;
}).last().after($full);
$prvw.slideDown();
});
$(window).on("resize", function () {
$full.remove();
$li.removeClass("active");
});
});
And then modify the preview div
<div id="preview1" class='preview'>
<img src="//placehold.it/300x180/369">
<div><h2></h2><p></p></div>
</div>
<div id="preview2" class='preview'>
<img src="//placehold.it/300x180/369">
<div><h2></h2><p></p></div>
</div>
Thought it looked weird so threw in the necessary css changes:
.preview{
display:none;
}
.preview > *{
float:left;
margin:3%;
}
.preview img{
max-width:100%;
}

clicking twice on the same element and then on another element brings the first elment to the "clicked" state

I have an interactive illustration where you can hover over elements and then if you click on them you can see a popover and the clicked element gets black. It works quite good, but there is a problem with the click and hover code. If one clicks on the same element twice in a row and then on another element, the first element gets black. Try for yourself: http://labs.tageswoche.ch/grafik_osze
Here is the code:
var sourceSwap = function () {
var $this = $(this);
if (!$this.hasClass('active')) {
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
};
var makeActive = function() {
var $this = $(this);
// bring the active back (if any) to the first state
if ($('img.active').length) {
var newSource = $('img.active').data('alt-src');
$('img.active').data('alt-src', $('img.active').attr('src'));
$('img.active').attr('src', newSource);
$('img.active').removeClass('active');
}
$this.toggleClass('active');
}
$(function() {
$('img[data-alt-src]')
.each(function() {
new Image().src = $(this).data('alt-src');
})
.hover(sourceSwap, sourceSwap);
$('img[data-alt-src]').on('click', makeActive);
});
To try for yourself: http://jsfiddle.net/8wtvvka5/
i tried this on fiddle:
function swap(e)
{
var src = e.attr('src');
var active = e.hasClass('active');
var dark = src.indexOf('_h.png', src.length - '_h.png'.length) !== -1;
e.attr('data-src-dark', dark);
if (active || e.attr('data-src-dark') == true) return;
e.attr('src', e.attr('data-alt-src'));
e.attr('data-alt-src', src);
return active;
}
var sourceSwap = function ()
{
if (!$(this).hasClass('active'))
{
swap($(this));
}
};
var makeActive = function()
{
var active = $(this).hasClass('active');
$('img.active').each(function()
{
$(this).removeClass('active'); swap($(this));
});
if (active) $(this).removeClass('active');
else $(this).addClass('active');
swap($(this));
}
$(function() {
$('img[data-alt-src]')
.each(function() {
new Image().src = $(this).data('alt-src');
})
.hover(sourceSwap, sourceSwap);
$('img[data-alt-src]').on('click', makeActive);
});
$('img.active') is a complete set of elements so you should use the 'each' function to handle them all
JUST COPY-AND-PASTE to fiddle to check it out yorself :)

get interval ID from else statement when set in IF

I am attempting to create a responsive slider, that will change to a simple set of dot points when in mobile mode (< 940).
The issue I am facing is in my else statement I am unable to clearintervals that were made in the if statement, because t comes up as undefined. I have resorted to using
for (var i = 1; i < 99999; i++) window.clearInterval(i); to clear the interval which works, but I don't like it because it's ugly and cumbersome, is there another way of accomplishing this?
$(document).ready(function() {
function rePosition() {
//get responsive width
var container_width = $('.container').width();
//Slider for desktops only
if(container_width >= 940) {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,6000);
});
var marginSize = i = 1;
//Called in Doc Load
function sliderLoop(trans_speed) {
if (trans_speed) {
var trans_speed = trans_speed;
}
else
{
var trans_speed = 3000;
}
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize }, trans_speed);
}
t = setInterval(sliderLoop,6000);
$('.items li').hover(function() {
$('.slider').stop();
clearInterval(t);
var item_numb = $(this).index();
i = item_numb;
sliderLoop(500);
}, function() {
t = setInterval(sliderLoop,6000);
});
}
else
{
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
$('.slider').stop(true, true);
$('.slider').css('margin-left', '0px');
//rearrange content
if($('.slider .slide .slide_title').length < 1) {
$('.items ul li').each(function() {
var item_numb = $(this).index();
var content = $(this).text();
$('.slider .slide:eq(' + item_numb + ')').prepend('<div class="title slide_title">' + content + '</div>')
});
}
}
}
rePosition();
$(window).resize(function() {
rePosition();
});
});
Teemu's comment is correct. I'll expand on it. Make an array available to all of the relevant code (just remember that globals are bad).
$(document).ready(function() {
var myIntervalArray = [];
Now, whenever you create an interval you will need to reference later, do this:
var t = setInterval();//etc
myIntervalArray.push(t); //or just put the interval directly in.
Then to clear them, just loop the array and clear each interval.
for (var i=0; i<myIntervalArray.length; i++)
clearInterval(myIntervalArray[i]);
}
Umm, wouldn't t only be defined when the if part ran... as far as I can tell, this is going to run and be done... the scope will be destroyed. If you need to maintain the scope across calls, you'll need to move your var statements outside of reposition(), like so:
$(document).ready(function() {
var t = 0;
...
function rePosition() { ... }
});

Custom data-* types, css and javascript

all. I am building a full screen jQuery gallery for a project I am working on, and am running in to a small hiccup.
to see a demo of what is happening, please visit http://www.idealbrandon.com/gallery.html.
Basically, I am loading the bg-image for each slide using a custom attribute, data-background. This works fine the first time through, however whenever a slide is loaded for a second time, it does not load. The HTML for a slide is:
<div class="slide" data-background="/img/gallery/2.jpg">
<div class="location">Magical Aqua Ducks</div>
<div class="verse"></div>
</div>
the Javascript in question is
for(var i = 0; i < totalSlides; i++){
$pagerList
.append('<li class="page" data-target="'+i+'"></li>');
if ($slides.eq(i).attr("data-background") != null){
$slides.eq(i).css("background-image", "url("+$slides.eq(i).attr("data-background")+")");
};
};
and the entire javascript file is
(function($){
function prefix(el){
var prefixes = ["Webkit", "Moz", "O", "ms"];
for (var i = 0; i < prefixes.length; i++){
if (prefixes[i] + "Transition" in el.style){
return '-'+prefixes[i].toLowerCase()+'-';
};
};
return "transition" in el.style ? "" : false;
};
var methods = {
init: function(settings){
return this.each(function(){
var config = {
slideDur: 7000,
fadeDur: 800
};
if(settings){
$.extend(config, settings);
};
this.config = config;
var $container = $(this),
slideSelector = '.slide',
fading = false,
slideTimer,
activeSlide,
newSlide,
$slides = $container.find(slideSelector),
totalSlides = $slides.length,
$pagerList = $container.find('.pager_list');
prefix = prefix($container[0]);
function animateSlides(activeNdx, newNdx){
function cleanUp(){
$slides.eq(activeNdx).removeAttr('style');
activeSlide = newNdx;
fading = false;
waitForNext();
};
if(fading || activeNdx == newNdx){
return false;
};
fading = true;
$pagers.removeClass('active').eq(newSlide).addClass('active');
$slides.eq(activeNdx).css('z-index', 3);
$slides.eq(newNdx).css({
'z-index': 2,
'opacity': 1
});
if(!prefix){
$slides.eq(activeNdx).animate({'opacity': 0}, config.fadeDur,
function(){
cleanUp();
});
} else {
var styles = {};
styles[prefix+'transition'] = 'opacity '+config.fadeDur+'ms';
styles['opacity'] = 0;
$slides.eq(activeNdx).css(styles);
//$slides.eq(activeNdx).css("background-image", "url("+$slides.eq(activeNdx).attr("data-background")+")");
var fadeTimer = setTimeout(function(){
cleanUp();
},config.fadeDur);
};
};
function changeSlides(target){
if(target == 'next'){
newSlide = (activeSlide * 1) + 1;
if(newSlide > totalSlides - 1){
newSlide = 0;
}
} else if(target == 'prev'){
newSlide = activeSlide - 1;
if(newSlide < 0){
newSlide = totalSlides - 1;
};
} else {
newSlide = target;
};
animateSlides(activeSlide, newSlide);
};
function waitForNext(){
slideTimer = setTimeout(function(){
changeSlides('next');
},config.slideDur);
};
for(var i = 0; i < totalSlides; i++){
$pagerList
.append('<li class="page" data-target="'+i+'"></li>');
if ($slides.eq(i).attr("data-background") != null){
$slides.eq(i).css("background-image", "url("+$slides.eq(i).attr("data-background")+")");
//alert($slides.eq(i).attr("data-background"));
};
};
$container.find('.page').bind('click',function(){
var target = $(this).attr('data-target');
clearTimeout(slideTimer);
changeSlides(target);
});
var $pagers = $pagerList.find('.page');
$slides.eq(0).css('opacity', 1);
$pagers.eq(0).addClass('active');
activeSlide = 0;
waitForNext();
});
}
};
$.fn.easyFader = function(settings){
return methods.init.apply(this, arguments);
};
})(jQuery);
Thanks in advance
Having had a look at your gallery.js file you have the following function that is called on your fade transition: cleanUp()
In this function you remove the style attribute from your $slides:
$slides.eq(activeNdx).removeAttr('style');
Which is removing the background-image style too. This is then never set again.
After the above line where you remove the styles you may want to then include:
$slides.eq(activeNdx).css("background-image", "url("+$slides.eq(activeNdx).data("background")+")");

jquery stop image rotation on mouseover, start on mouseout / hover

I have built a jQuery rotator to rotate through 3 divs and loop them. I would like to add the functionality on mouse over to "freeze" the current div and then start again on mouse out.
I've thought about setting a variable to false at the start of the function and setting it true when it's on it's current frame but I've got my self a bit confused.
I've also tried to use the hover function but when using the in and out handlers, I'm confused as to how to stop, restart the animation.
function ImageRotate() {
var CurrentFeature = "#container" + featureNumber;
$(CurrentFeature).stop(false, true).delay(4500).animate({'top' : '330px'}, 3000);
var featureNumber2 = featureNumber+1;
if ( featureNumber == numberOfFeatures) {featureNumber2 = 1}
var NewFeature = "#container" + featureNumber2;
$(NewFeature).stop(false, true).delay(4500).animate({'top' : '0px'}, 3000);
var featureNumber3 = featureNumber-1;
if ( featureNumber == 1) {featureNumber3 = numberOfFeatures};
var OldFeature = "#container" + featureNumber3;
$(OldFeature).stop(false, true).delay(4500).css('top' , '-330px');
setTimeout('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; ImageRotate2()', 7500)};
Any help would be greatly appreciated!!
Thanks, Matt
If you were to add this code:
var timerId = null;
function startRotation() {
if (timerId) {
return;
}
timerId = setInterval('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; ImageRotate2()', 7500);
}
function stopRotation() {
if (!timerId) {
return;
}
clearInterval(timerId);
timerId = null;
}
and replace the last line of your code block with a simple call to startRotation();, then you could call stopRotation and startRotation when the mouse hovers over/leaves your element:
$('your-element-selector').hover(stopRotation, startRotation);
It's not clear what you are trying to do with the three divs without seeing the HTML and more code, so I think a basic example might help you better (demo).
HTML
<div class="test">image: <span></span></div>
Script
$(document).ready(function(){
var indx = 0, loop, numberOfFeatures = 5;
function imageRotate(){
indx++;
if (indx > numberOfFeatures) { indx = 1; }
$('.test span').text(indx);
loop = setTimeout( imageRotate , 1000 );
}
imageRotate();
$('.test').hover(function(){
clearTimeout(loop);
}, function(){
imageRotate();
});
})
changed things up a little bit, here is how I ended up doing it. `
var animRun = false;
var rotateHover = false;
function startRotation() {
rotateHover = false;
ImageRotate();
}
function stopRotation() {
rotateHover = true;
clearTimeout();
}
function ImageRotate() {
if (rotateHover == false){
animRun = true;
var CurrentFeature = "#container" + featureNumber;
$(CurrentFeature).stop(false, true).animate({'top' : '330px'}, featureDuration, function(){animRun = false;});
var featureNumber2 = featureNumber+1;
if ( featureNumber == numberOfFeatures) {featureNumber2 = 1}
var NewFeature = "#container" + featureNumber2;
$(NewFeature).stop(false, true).animate({'top' : '0px'}, featureDuration); /* rotate slide 2 into main frame */
var featureNumber3 = featureNumber-1;
if ( featureNumber == 1) {featureNumber3 = numberOfFeatures};
var OldFeature = "#container" + featureNumber3;
$(OldFeature).stop(false, true).css('top' , '-330px'); /*bring slide 3 to the top*/
//startRotation();
setTimeout('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; if (rotateHover == false){ImageRotate2()};', featureDelay);
};
};

Categories

Resources