Here is the jsfiddle demo.
I am trying to animate the tabs in my carousel synchronously, i.e. they all should slide left/right together. However, as you will notice from the demo, sometimes they do, othertimes they don't.
Could someone please point out where I am going wrong? Im not just looking for the correct code but logic & explanation please.
Ive tried to comments the code as much as I can so that its easier to follow & pinpoint the problem. The line that has the 'animate' code has the comment: // ***** NOTE -- THIS IS THE LINE THATS ANIMATING THE TABS TO SCROLL RIGHT *****
Code:
var eLeftScrollButton = document.getElementById("t_l_nav");
var eRightScrollButton = document.getElementById("t_r_nav");
var eArrowForTabs = document.getElementById("arrow");
var iActiveNo = 0; //var. for storing the active tab. no.
var iTabSlideNo = 0;
var iTabWidth = 147; // a tab's width
var eTabsDiv = document.getElementById("tabs");
var iTabsCount = eTabsDiv.childNodes.length; //tabs count
var bClickable = true; // bool whether left & right buttons are clickable or not
var iButtonsPage = 1; // button page no.
var iStonesPage = 1; // stones page no.
var iRibbonsPage = 1; // ribbons page no.
var iLacesPage = 1; // laces page no.
var iPipingPage = 1; // laces page no.
displayTabNo_onstart();
/* ---------- displaying the current tab, hiding the other non-current tabs ---------- */
function displayTabNo_onstart()
{
for ( var i = 0; i < iTabsCount; i++)
{
if (i === iActiveNo)
{
eTabsDiv.children[i].style.color = "black";
eTabsDiv.children[i].style.fontWeight = "bold";
} else
{
eTabsDiv.children[i].style.opacity = "0.2";
eTabsDiv.children[i].style.fontWeight = "normal";
}
}
}
/* ---------- activate the button, ribbons etc based on what tab is active right now, & hide others ---------- */
function activateFeaturesContainer (direction)
{
var eFeaturesContainerDiv = document.getElementById("features");
eFeaturesContainerDiv.children[iActiveNo].style.display = "block";
(direction === "right") ? ((eFeaturesContainerDiv.children[iActiveNo - 1].style.display = "none") & (bClickable = true)) : ((eFeaturesContainerDiv.children[iActiveNo + 1].style.display = "none") & (bClickable = true));
}
/* ---------- called when the right button for tabs is pressed, calls the below two 'right' functions ---------- */
function pressRightButton ()
{
if (bClickable === true)
{
bClickable = false;
pressRightButtonEffect();
activateRightTab();
} else {
return;
}
}
/* ---------- called when the left button for tabs is pressed, calls the below two 'left' functions ---------- */
function pressLeftButton ()
{
if (bClickable === true)
{
bClickable = false;
pressLeftButtonEffect();
activateLeftTab();
} else {
return;
}
}
/* ---------- effect on right button when pressed ---------- */
function pressRightButtonEffect()
{
eRightScrollButton.style.top = "29px";
window.setTimeout(function()
{
var eStyle = window.getComputedStyle(eRightScrollButton);
var pBackgroundColorProperty = eStyle.backgroundColor; // getting the CSS backgroundColor
eRightScrollButton.style.top = "28px";
}, 150);
}
/* ---------- effect on left button when pressed ---------- */
function pressLeftButtonEffect()
{
eLeftScrollButton.style.top = "29px";
window.setTimeout(function()
{
var eStyle = window.getComputedStyle(eLeftScrollButton);
var pBackgroundColorProperty = eStyle.backgroundColor; // getting the CSS backgroundColor
eLeftScrollButton.style.top = "28px";
}, 150);
}
/* ---------- tabs indicator, tabs & other animations on right button when pressed ---------- */
function activateRightTab()
{
var direction = "right";
if (iActiveNo < iTabsCount - 1 && iActiveNo >= 0)
{
iActiveNo = iActiveNo + 1;
(iActiveNo > 0) ? eLeftScrollButton.childNodes[0].setAttribute("src", "Img/WA03_Container_LeftScrollButton_Active.png") : false; //reinstate leftScrollbutton to active
(iTabSlideNo < iTabsCount - 1) ? iTabSlideNo++ : iTabSlideNo;
// ***** NOTE -- THIS IS THE LINE THATS ANIMATING THE TABS TO SCROLL RIGHT *****
$(".c_tabs").animate ({"right": ("+=147px")}, 500, "swing", function()
{
$(eTabsDiv.childNodes[iActiveNo]).animate ({"opacity" : "1"}, 191,"linear");
$(eTabsDiv.childNodes[iActiveNo - 1]).animate ({"opacity" : "0.2"}, 191,"linear");
});
window.setTimeout (function ()
{
eTabsDiv.childNodes[iActiveNo].style.fontWeight = "bold";
eTabsDiv.childNodes[iActiveNo-1].style.fontWeight = "normal";
},500);
$(eArrowForTabs).animate ({"top" : "69px"}, 191, "linear", function()
{
window.setTimeout (function()
{ $(eArrowForTabs).animate ({"top" : "55px"}, 191, "linear"); }, 75);
});
(iTabSlideNo + 1 === iTabsCount) ? eRightScrollButton.childNodes[0].setAttribute ("src", "Img/WA02_Container_RightScrollButton_Passive.png"):false;
window.setTimeout (function() {activateFeaturesContainer(direction);}, 600);
} else {
bClickable = true;
} // close -> first if statement of this function
if (iActiveNo === iTabsCount - 1 && eRightScrollButton.childNodes[0].getAttribute("src") === "Img/WA02_Container_RightScrollButton_Passive.png") //springy effect on last tab
{
$(eTabsDiv.childNodes[iActiveNo]).animate({"right" : (((iTabSlideNo * iTabWidth) + 10) + "px")}, 100).animate({"right" : (((iTabSlideNo * iTabWidth) - 5) + "px")}, 45).animate({"right" : (((iTabSlideNo * iTabWidth) + 0) + "px")}, 10);
} // close -> springy effect if statement
} // close -> activateRightTab function
/* ---------- tabs indicator, tabs & other animations on left button when pressed ---------- */
function activateLeftTab()
{
var direction = "left";
if (iActiveNo <= iTabsCount -1 && iActiveNo > 0) //because length doesn't count 0 & we are substracting 1 below
{
iActiveNo = iActiveNo - 1;
(iActiveNo < iTabsCount - 1) ? eRightScrollButton.childNodes[0].setAttribute("src", "Img/WA01_Container_RightScrollButton_Active.png") : false; (iTabSlideNo > 0) ? iTabSlideNo-- : false;
$(".c_tabs").animate ({"right": ("-=147px")}, 500, "linear", function()
{
$(eTabsDiv.childNodes[iActiveNo]).animate ({"opacity" : "1"}, 250,"linear");
$(eTabsDiv.childNodes[iActiveNo + 1]).animate ({"opacity" : "0.2"}, 250,"linear");
});
window.setTimeout ( function ()
{
eTabsDiv.childNodes[iActiveNo].style.fontWeight = "bold";
eTabsDiv.childNodes[iActiveNo-1].style.fontWeight = "normal";
},500);
$(eArrowForTabs).animate ({"top" : "69px"}, 191, "linear", function()
{
window.setTimeout( function()
{ $(eArrowForTabs).animate ({"top" : "55px"}, 191, "linear"); }, 75);
});
(iTabSlideNo === 0) ? eLeftScrollButton.childNodes[0].setAttribute ("src", "Img/WA04_Container_LeftScrollButton_Passive.png") : false;
window.setTimeout( function() {activateFeaturesContainer(direction)}, 600);
} else { // close -> first if statement of this function
bClickable = true;
}
if (iActiveNo === 0 && eLeftScrollButton.childNodes[0].getAttribute("src") === "Img/WA04_Container_LeftScrollButton_Passive.png") //springy effect on last tab
{
$(eTabsDiv.childNodes[iActiveNo]).animate({"right" : (((iTabSlideNo * iTabWidth) - 10) + "px")}, 100).animate({"right" : (((iTabSlideNo * iTabWidth) + 5) + "px")}, 45).animate({"right" : (((iTabSlideNo * iTabWidth) + 0) + "px")}, 10);
} // close -> springy effect if statement
} // close -> activateRightTab function
Related
Hello I am having errors with my code:
https://jsfiddle.net/wzhm2whj/
<script>
//Initial Global variables
var mainloop_frame_time = 34;
var top = 0;
var rootMenu = document.getElementById('menu');
var rootMenuDivs = rootMenu.getElementsByTagName('div')[0];
var rootListDivs = rootMenuDivs.getElementsByTagName('ul')[0];
var childDivs = rootListDivs.getElementsByTagName('div');
var childDiv = childDivs[0];
var childDiv_counter = 0;
var child_change_flag = true;
var child_index_increment = 0;
var child_index_amount = childDivs.length;
//var child_animation_keyframe = 0;
var frame = 0;
var childDiv_tmp1_position = 0;
//finding the web browsers viewport size.
var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
var client_height = elem.clientHeight;
var process_array = new Array();
//Initial styling
for (var i = 0; i < childDivs.length; i++) {
var childDiv = childDivs[0];
childDiv.style.backgroundColor = "antiquewhite";
}
var childDiv = childDivs[0];
//rotate function variables
var rotate_div;
var rotate_passed_deg;
var rotate_deg_stop;
var rotate_results;
var rotate_current_deg = 0;
var speed_modifier = 1;
var tmp1_speed = 0;
//case flags
case2_flag = -1;
case3_flag = -1;
//This may not be needed >>> If not, put all code in mainloop.
var processes_logic = function() {
switch (frame) {
case 0:
process_array.push(menu_child0);
break;
//this case is when the previous case is 80% done
case 28:
rootMenu.style.transformOrigin = "top left";
process_array.push(menu_slant);
break;
case 35:
//Added the ability for paramaters, all push paramaters here are: function, menu_index, position, speed, tmp as flag for switching to next menu,
//process_index used to give the process index as refrence to delete..
window.alert(process_array.length);
process_array.push(new Array(menu_div_slide_out, child_index_amount - 1, 0, 0, 0, process_array.length-1));
break;
}
}
var initiate_all_processes = function() {
for (var i = 0; i < process_array.length; i++) {
//Added the ability for paramaters, considerer removing as its not used atm, or revising.
if (process_array[i] != undefined && process_array[i] != null && process_array[i] != "") {
if (process_array[i].length < 6) {
process_array[i]();
} else {
process_array[i][0](process_array[i][5]);
}
}
}
}
function menu_div_slide_out(process_index) {
/*process_array[process_index][
0 = function,
1 = current menu item (index length working backwards)
2 = position,
3 = speed,
4 = tmp,
5 = refrence to this process in array] */
//for debuging purposes to see if a ChildDiv is not devined, what process index is being pointed to.
//window.alert('Process index ' + process_index);
//!!!!!!!! You are probably mixing up how you are setting process index! try +1
process_array[process_index][2] += 3.5 + (process_array[process_index][3] * 1.7);
process_array[process_index][3] += (speed_modifier * .3);
childDivs[process_array[process_index][1]].style.left = process_array[process_index][2] + 'px';
if (process_array[process_index][2] > 100 && process_array[process_index][4] && process_array[process_index][1] > 0) {
// window.alert('CCC');
process_array[process_index][4] = true;
//Add another process at ever 100pxs
process_array.push(new Array(menu_div_slide_out, process_array[process_index][1] - 1, 0, 0, false, process_array.length-1));
//debugger;
} else
if (process_array[process_index][2] >= (900 - (process_array[process_index][2] / 20))) {
childDivs[process_array[process_index][1]].remove();
//process_array.splice(process_array[process_index][5], 1);
}
}
function menu_slant() {
rotate_return = rotate(rootMenu, .1 + (tmp1_speed), 27);
tmp1_speed += (speed_modifier * .5);
if (rotate_return === true) {
/////////////This can be unremoved because there is more animation, perhaps. or can be done in another key frame.
tmp1_speed = 0;
rotate_current_deg = 0;
remove_process(menu_slant);
} else {
if (rotate_return / 27 * 100 >= 60 && case3_flag < 0) {
case2_flag = frame;
}
}
}
var menu_child0 = function() {
childDiv_tmp1_position += 3 + (tmp1_speed * 1.7);
childDiv.style.top = childDiv_tmp1_position + 'px';
rotate(childDiv, .2 + (tmp1_speed), 170);
tmp1_speed += (speed_modifier * .7);
if (childDiv_tmp1_position / client_height * 100 >= 80 && case2_flag < 0) {
case2_flag = frame;
}
if (childDiv_tmp1_position >= client_height) {
childDiv.style.visibility = 'hidden';
tmp1_speed = 0;
childDiv_tmp1_position = 0;
rotate_current_deg = 0;
//may be bloated >>
remove_process(menu_child0);
}
}
function remove_process(index) {
var index_tmp = process_array.indexOf(index);
if (index_tmp >= 0) {
process_array.splice(index_tmp, 1);
}
}
function rotate(rotate_div, rotate_passed_deg, rotate_passed_deg_stop) {
rotate_current_deg += rotate_passed_deg;
rotate_deg = rotate_current_deg < rotate_passed_deg_stop ? rotate_current_deg : rotate_passed_deg_stop;
rotate_div.style.webkitTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.mozTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.msTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.oTransform = 'rotate(' + rotate_deg + 'deg)';
rotate_div.style.transform = 'rotate(' + rotate_deg + 'deg)';
if (rotate_current_deg >= rotate_passed_deg_stop) {
return true;
} else {
return rotate_current_deg;
}
}
//main loop for the animation
var mainloop = function() {
processes_logic();
initiate_all_processes();
frame++;
}
var loop_interval = setInterval(mainloop, mainloop_frame_time);
</script>
I am trying to animate my website falling apart but I am having a hard time articulation this into code. I thought of running the animation in a loop, creating events at specific frames and reusing some codes as functions. I have a rotate function which works to rotate several things.
THE PROBLEM:
The problem I am having is sliding my menu items one at a time to the right. I want one to slide a bit and the next to start sliding after. I wrote a function to slide an item and then in that function it adds another process to an array for the next menu item to be called and run the same function (with passed interval of who is calling). I do not know how many menu items there will be, thats why I am trying to make it dynamic.
I can get it so that the first mwnu item falls, the menu falls by rotating it (some times if there is an error in the code then it wont rotate, but when there are no errors it works better).
The issue is sliding each menu item.
my website is here: http://clearlove.ca/89-404-error
Can any one help me with why this isnt working, and if there is a better way to do what I am trying to do?
This is the markup for my navigation:
<div class="navigation navigation-fixed-top">
Home
About
</div>
And I have this jquery script, which is checking if href="#home" has class active to do something and if not to do something else.
This is the code:
var isActive = $('a[href="#home"]').hasClass('active');
$(".navigation")
.toggleClass("navigation-fixed-bottom", isActive)
.toggleClass("navigation-fixed-top", !isActive);
This is partially working because the class="active" is added automatically when I'm going the #about section or I'm clicking on it. It does this without refreshing the page so I need a way to to make this work without refreshing the page.
Any suggestions on how can I do this with jQuery/Javascript ?
UPDATE:
this is the name of the plugin Scrollit.js
THIS IS THE CODE RESPONSIBLE FOR ADDING THE ACTIVE CLASS ON THE NAVIGATION ELEMENTS:
(function($) {
'use strict';
var pluginName = 'ScrollIt',
pluginVersion = '1.0.3';
/*
* OPTIONS
*/
var defaults = {
upKey: 38,
downKey: 40,
easing: 'linear',
scrollTime: 600,
activeClass: 'active',
onPageChange: null,
topOffset : 0
};
$.scrollIt = function(options) {
/*
* DECLARATIONS
*/
var settings = $.extend(defaults, options),
active = 0,
lastIndex = $('[data-scroll-index]:last').attr('data-scroll-index');
/*
* METHODS
*/
/**
* navigate
*
* sets up navigation animation
*/
var navigate = function(ndx) {
if(ndx < 0 || ndx > lastIndex) return;
var targetTop = $('[data-scroll-index=' + ndx + ']').offset().top + settings.topOffset + 1;
$('html,body').animate({
scrollTop: targetTop,
easing: settings.easing
}, settings.scrollTime);
};
/**
* doScroll
*
* runs navigation() when criteria are met
*/
var doScroll = function (e) {
var target = $(e.target).closest("[data-scroll-nav]").attr('data-scroll-nav') ||
$(e.target).closest("[data-scroll-goto]").attr('data-scroll-goto');
navigate(parseInt(target));
};
/**
* keyNavigation
*
* sets up keyboard navigation behavior
*/
var keyNavigation = function (e) {
var key = e.which;
if(key == settings.upKey && active > 0) {
navigate(parseInt(active) - 1);
return false;
} else if(key == settings.downKey && active < lastIndex) {
navigate(parseInt(active) + 1);
return false;
}
return true;
};
/**
* updateActive
*
* sets the currently active item
*/
var updateActive = function(ndx) {
if(settings.onPageChange && ndx && (active != ndx)) settings.onPageChange(ndx);
active = ndx;
$('[data-scroll-nav]').removeClass(settings.activeClass);
$('[data-scroll-nav=' + ndx + ']').addClass(settings.activeClass);
};
/**
* watchActive
*
* watches currently active item and updates accordingly
*/
function navPosition() {
$('[data-scroll-nav]').toggleClass('navigation-fixed-bottom navigation-fixed-top');
}
var updateActive = function(ndx, navPosition) {
var watchActive = function() {
var winTop = $(window).scrollTop();
var visible = $('[data-scroll-index]').filter(function(ndx, div) {
return winTop >= $(div).offset().top + settings.topOffset &&
winTop < $(div).offset().top + (settings.topOffset) + $(div).outerHeight()
});
var newActive = visible.first().attr('data-scroll-index');
updateActive(newActive);
};
/*
* runs methods
*/
$(window).on('scroll',watchActive).on('scroll');
$(window).on('keydown', keyNavigation);
$('body').on('click','[data-scroll-nav], [data-scroll-goto]', function(e){
e.preventDefault();
doScroll(e);
});
};
}(jQuery));
$('[data-scroll-nav]').removeClass(settings.activeClass)
.toggleClass('navigation-fixed-bottom navigation-fixed-top');
and/or
$('[data-scroll-nav=' + ndx + ']').addClass(settings.activeClass)
.toggleClass('navigation-fixed-bottom navigation-fixed-top');
If you wanted to keep the original code cleaner, you could do a callback:
function myCallBackFunction() {
$('[data-scroll-nav]').toggleClass('navigation-fixed-bottom navigation-fixed-top');
}
var updateActive = function(ndx, myCallbackFunction) {..}
use jquery on to bind handlers to events you want to respond
$("a.active").on('click',function(){});
I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.
This is some javascript for a drupal 6.x module called "Views Popup".
https://drupal.org/project/views_popup
I can't seem to set a delay on the popup when the mouse moves off the link that triggers the popup. I have the title, teaser text and a more link in the popup and users need to be able to move the mouse off the link (image) in order to click on the "read more" link. I've tried adjusting all the settings in the code below, but none seem to relate to this. I'm not a coder, but I think something needs to be added to make this work. Any suggestions would be greatly appreciated.
Here's the code:
var popup_time = 0;
var popup_elem = 0;
var popup_show_timer = 0;
var popup_reset_timer = 0;
$(function() {
popup_reset();
$(".views-popup").appendTo("body");
});
Drupal.behaviors.viewsPopup = function(context) {
$(".views-popup-row").mouseover(function() {
popup_show(this);
})
.mouseout(function() {
popup_hide(this);
})
.mousemove(function(e) {
popup_move(this,e);
});
}
function popup_move(me,evt){
var e, top, left;
if (Drupal.settings.views_popup.follow_mouse){
left = evt.pageX + 15;
top = evt.pageY;
$("#views-popup-" + $(me).attr("id")).css({
left: left + 'px',
top: top + 'px'
});
}
}
function popup_show(me) {
var p, e, top, left, pos ;
var x = $(me).attr("id");
e = $("#views-popup-" + $(me).attr("id"));
if (e == popup_elem) {
return ; // already handled
}
if (! Drupal.settings.views_popup.follow_mouse){
pos = $(me).offset();
left = 20 + pos.left - $(document).scrollLeft();
top = 2 + pos.top + $(me).outerHeight() - $(document).scrollTop();
$(e).css({
left: left + 'px',
top: top + 'px'
});
}
popup_clear_show_timer();
if (popup_elem) {
popup_elem.hide();
popup_time = 500 ;
}
popup_elem = e;
if ( popup_time == 0 ) {
popup_show_now();
} else {
popup_show_timer = setTimeout("popup_show_now();",popup_time);
}
}
function popup_show_now() {
popup_show_timer = 0 ;
if(popup_elem) {
popup_elem.show();
clearTimeout(popup_reset_timer);
popup_time = 0;
}
}
function popup_clear_show_timer(){
if (popup_show_timer) {
clearTimeout(popup_show_timer);
popup_show_timer = 0;
}
}
function popup_hide(me) {
e = $("#views-popup-" + $(me).attr("id"));
popup_clear_show_timer();
clearTimeout(popup_reset_timer);
e.hide();
if(e == popup_elem) {
popup_elem = 2;
}
popup_reset_timer = setTimeout('popup_reset()',Drupal.settings.views_popup.reset_time);
}
function popup_reset(){
popup_time = Drupal.settings.views_popup.popup_delay;
}
So, assuming the above code works how you want -- and that you want to set a delay for the popup to hide, what you can do is call javascript's setTimeout(function, delay) function, which initiates a callback after delay milliseconds.
function popup_hide(me) {
e = $("#views-popup-" + $(me).attr("id"));
popup_clear_show_timer();
clearTimeout(popup_reset_timer);
var delay = 1000; // ms
setTimeout(e.hide, delay); // <------- here
if(e == popup_elem) {
popup_elem = 2;
}
popup_reset_timer = setTimeout('popup_reset()',Drupal.settings.views_popup.reset_time);
}
This will call e.hide (the function) after 1 second has passed.
The code (from an old plugin that I am trying to make responsive) slides a set of images across every n seconds. It uses setInterval code as below, and works well on Firefox. On Chrome it runs once only, and debugging indicates that the second setInteral function is just not called. Please help as its diving me mad. Running example at http://lelal.com/test/site10/index.html (sorry about the load time)
play = setInterval(function() {
if (!busy) {
busy = true;
updateCurrent(settings.direction);
slide();
}
}, settings.speed);
The complete plugin code is below (sorry its long)
/*
* jQuery Queue Slider v1.0
* http://danielkorte.com
*
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function($){
var QueueSlider = function(element, options) {
var play = false,
busy = false,
current = 2,
previous = 2,
widths = [],
slider = $(element),
queue = $('ul.queue', slider),
numImages = $('img', queue).size(),
viewportWidth = slider.width(),
settings = $.extend({}, $.fn.queueSlider.defaults, options);
$(window).resize(function(){
if(busy !== false)
clearTimeout(busy);
busy = setTimeout(resizewindow, 200); //200 is time in miliseconds
});
function resizewindow() {
viewportWidth = slider.width();
if (settings.scale > 0) {
slider.css('height',viewportWidth * settings.scale);
computeQueueWidth();
}
queue.css('left', -getQueuePosition());
busy = false;
}
function requeue() {
$('li', queue).each(function(key, value) {
$(this).attr('class', 'slide-' + (key+1));
});
}
function updateCurrent(dir) {
current += dir;
if (current < 1) {
current = numImages;
} else if (current > numImages) {
current = 1;
}
}
function getQueuePosition() {
var i = 0, index = current-1,
queuePosition = (viewportWidth - widths[index]) / -2;
for (i = 0; i < index; i++) { queuePosition += widths[i]; }
return queuePosition;
}
function computeQueueWidth() {
var queueWidth = 0;
// factor = slider.height() / settings.imageheight;
// settings.imageheight = settings.imageheight * factor;
// Get the image widths and set the queue width to their combined value.
$('li', queue).each(function(key, value) {
var slideimg = $("img", this),
slide = $(this),
// width = slide.width() * factor,
width = slideimg.width();
slide.css('width', width+'px');
queueWidth += widths[key] = width;
});
queue.css('width', queueWidth + 500);
}
function slide() {
var animationSettings = {
duration: settings.transitionSpeed,
queue: false
};
// Emulate an infinte loop:
// Bring the first image to the end.
if (current === numImages) {
var firstImage = $('li.slide-1', queue);
widths.push(widths.shift());
queue.css('left', queue.position().left + firstImage.width()).append(firstImage);
requeue();
current--; previous--;
}
// Bring the last image to the beginning.
else if (current === 1) {
var lastImage = $('li:last-child', queue);
widths.unshift(widths.pop());
queue.css('left', queue.position().left + -lastImage.width()).prepend(lastImage);
requeue();
current = 2; previous = 3;
}
// Fade in the current and out the previous images.
if (settings.fade !== -1) {
$('li.slide-'+current, queue).animate({opacity: 1}, animationSettings);
$('li.slide-'+previous, queue).animate({opacity: settings.fade}, animationSettings);
}
// Animate the queue.
animationSettings.complete = function() { busy = false; };
queue.animate({ left: -getQueuePosition() }, animationSettings);
previous = current;
}
//
// Setup the QueueSlider!
//
if (numImages > 2) {
// Move the last slide to the beginning of the queue so there is an image
// on both sides of the current image.
if (settings.scale > 0) {
slider.css('height',viewportWidth * settings.scale);
}
computeQueueWidth();
widths.unshift(widths.pop());
queue.css('left', -getQueuePosition()).prepend($('li:last-child', queue));
requeue();
// Fade out the images we aren't viewing.
if (settings.fade !== -1) { $('li', queue).not('.slide-2').css('opacity', settings.fade); }
// Include the buttons if enabled and assign a click event to them.
if (settings.buttons) {
slider.append('<button class="previous" rel="-1">' + settings.previous + '</button><button class="next" rel="1">' + settings.next + '</button>');
$('button', slider).click(function() {
if (!busy) {
busy = true;
updateCurrent(parseInt($(this).attr('rel'), 10));
clearInterval(play);
slide();
}
return false;
});
}
// Start the slideshow if it is enabled.
if (settings.speed !== 0) {
play = setInterval(function() {
if (!busy) {
busy = true;
updateCurrent(settings.direction);
slide();
}
}, settings.speed);
}
}
else {
// There isn't enough images for the QueueSlider!
// Let's disable the required CSS and show all one or two images ;)
slider.removeClass('queueslider');
}
};
$.fn.queueSlider = function(options) {
return this.each(function(key, value) {
var element = $(this);
// Return early if this element already has a plugin instance.
if (element.data('queueslider')) { return element.data('queueslider'); }
// Pass options to plugin constructor.
var queueslider = new QueueSlider(this, options);
// Store plugin object in this element's data.
element.data('queueslider', queueslider);
});
};
$.fn.queueSlider.defaults = {
scale: 0,
imageheight: 500,
fade: 0.3, // Opacity of images not being viewed, use -1 to disable
transitionSpeed: 700, // in milliseconds, speed for fade and slide motion
speed: 7000, // in milliseconds, use 0 to disable slideshow
direction: 1, // 1 for images to slide to the left, -1 to silde to the right during slideshow
buttons: true, // Display Previous/Next buttons
previous: 'Previous', // Previous button text
next: 'Next' // Next button text
};
}(jQuery));
Have a look here:
http://www.w3schools.com/jsref/met_win_setinterval.asp
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
Looks like you're calling clearInterval after the first usage of play, which makes it stop working.