jquery fadeIn fadeOut some problems - javascript

i wanted to create some fadeIn FadeOut effects. When pressed button the main id should be removed and hidden content should be appered and wise versa. (sorry for my poor english knowledge) Jsfiddle
<div class='button'>Click me</div>
<div id='main'></div>
<div class='hidden'></div>
css
#main {
width:80%;
height:300px;
background:#95a5a6;
float:right;
overflow:hidden;
position: relative;
}
.button {
width: 90px;
height:90px;
border-radius: 50%;
background:#e74c3c;
top:70px;
text-align:center;
line-height:90px;
position:absolute;
cursor: pointer;
color:#fff;
}
.hidden {
position:relative;
width:80%;
float:right;
height:250px;
background:#ddd;
margin: 0 auto;
display:none;
}
jquery
$('.button').on('click', function(){
var main = $('#main');
var hidden = $('.hidden');
if(main){
$(main).fadeOut();
$(hidden).fadeIn();
}else{
$(hidden).fadeOut();
$(main).fadeIn();
}
})

You need to call the fadeIn method in the fadeOut callback
http://jsfiddle.net/jgTh2/12/
$('.button').on('click', function () {
var main = $('#main');
var hidden = $('.hidden');
if (main.is(':visible')) {
main.fadeOut(function () {
hidden.fadeIn();
});
} else {
hidden.fadeOut(function () {
main.fadeIn();
});
}
});

var show = true;
$('.button').on('click', function(){
var main = $('#main');
var hidden = $('.hidden');
if(show){
$(main).fadeOut();
$(hidden).fadeIn();
show = false;
}else{
$(hidden).fadeOut();
$(main).fadeIn();
show = true;
}
})
in the css set .hidden to opacity:0 and remove display:none;

You have to use 1 more variable — flag.
Try this:
var flag = 0;
$('.button').on('click', function(){
var main = $('#main');
var hidden = $('.hidden');
if(flag == 0){
$(main).fadeOut('fast', function() {
$(hidden).fadeIn();
flag = 1;
});
}else{
$(hidden).fadeOut('fast', function() {
$(main).fadeIn();
flag = 0;
});
}
})
Fiddle
As #cgatian suggested, you can use boolean variable, instead of integer:
var flag = false;
$('.button').on('click', function(){
var main = $('#main');
var hidden = $('.hidden');
if(flag == false){
$(main).fadeOut('fast', function() {
$(hidden).fadeIn();
flag = true;
});
}else{
$(hidden).fadeOut('fast', function() {
$(main).fadeIn();
flag = false;
});
}
})

No need to maintain two fadeIn/fadeOut blocks
$('.button').on('click', function(){
var visible = $('#main');
var hidden = $('.hidden');
hidden = hidden.is(':visible') ? [visible, visible = hidden][0] :hidden;
visible.fadeOut(function()
{
hidden.fadeIn();
});
})
http://jsfiddle.net/eN6bg/

Related

How could I make this active onclick?

var span = document.getElementById('loading_dots');
var int = setInterval(function() {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400);
(function(){
var loading_dots = document.getElementById("loading_dots"),
show = function(){
loading_dots.style.display = "block";
setTimeout(hide, 5000); // 5 seconds
},
hide = function(){
loading_dots.style.display = "none";
};
show();
})();
How can I make it so loading_dots start on the click of a button, and re-activates everytime I click the button? the bottom function is to stop it after 5 seconds, maybe could merge it into one function?
Needs to work for 3 seperate buttons and relaunch on click of each, also needs to display inside of <span class="loading_dots" id="loading_dots"></span> any method is fine, css, jquery, or javascript
here is a jQuery version:
(function ( $ ) {
$.fn.loader = function( options ) {
var settings = $.extend({
text:"●",
spn: undefined
}, options );
$.each(this, function(){
var btn = this;
var int;
var spn;
if (settings.spn === undefined) {
spn = $("<span/>" , { "class":"loading_dots" });
$(btn).append(spn);
} else {
spn= $(settings.spn);
}
var show = function(){
btn.setAttribute("disabled", "disabled")
clearInterval(int);
spn.show();
int = setInterval(function() {
if ((spn[0].innerHTML += settings.text).length == 4)
spn.html("");
}, 400);
setTimeout(hide, 5000); // 5 seconds
}
var hide = function (){
spn.hide();
btn.removeAttribute("disabled", "disabled")
clearInterval(int);
}
btn.addEventListener("click", show);
});
};
}( jQuery ));
// now bind it by its class, this only need to be run once every time new button is added to the html
$(".btn").loader({spn:".loading_dots"});
// and you could also specify the text by
// $(".btn").loader({text: "*"});
.loading_dots {
color:red;
display:none;
width:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="loading_dots"></span>
<button class="btn" type="button" >
submit
</button>
<button class="btn" type="button" >
submit
</button>
</div>
If you want to add an event listener for a button click, just select the buttons, and add the listeners in a loop:
document.querySelectorAll("button").forEach(e => e.addEventListener("click", myFunc));
Alternatively, listen for any click, then check if the event's target is a button:
document.addEventListener("click", (e) => if (e.target.tagName == "BUTTON") myFunc());
You could use CSS for the most part of your code, and than simply toggle a show class on the parent #loading element:
const Loading = () => {
let tOut = null;
const el = document.querySelector("#loading");
const show = () => {
el.classList.add('show');
tOut = setTimeout(hide, 5000);
};
const hide = () => {
el.classList.remove('show');
clearTimeout(tOut);
};
return {
show,
hide
};
};
const loadingDots = Loading();
const loadBtns = document.querySelectorAll('.load');
[...loadBtns].forEach(el => el.addEventListener('click', loadingDots.show));
// you can always use loadingDots.hide() to hide when needed (before the 5sec ticks out)
#loading {
position: fixed;
z-index: 100;
top:0;
left: 0;
width:100vw;
height:100vh;
display:flex;
background: rgba(0,0,0,0.5);
color: #fff;
font-size: 3em;
align-items: center;
justify-content:center;
visibility: hidden;
opacity: 0;
transition: 0.4s;
}
#loading.show {
opacity: 1;
visibility: visible;
}
#keyframes blink {
50% {opacity: 1;}
}
#loading i:after {content: "\25cf";}
#loading i { opacity: 0; animation: blink 1.2s infinite; }
#loading i:nth-child(2) { animation-delay: .2s; }
#loading i:nth-child(3) { animation-delay: .4s; }
<div id="loading"><i></i><i></i><i></i></div>
<button class="load">LOAD</button>
<button class="load">LOAD</button>
<button class="load">LOAD</button>
A plain javascript version with the option to programmatically/manually stop displaying the loading dots. Just pass the id of the parent element you want the loading to be attached to. By default the loading will be appended to the parent but you can optionally pass an object as the last parameter with a position property.
function removeLoading(id) {
var parent = document.getElementById(id);
var spans = parent.getElementsByClassName("loading_dots");
while (spans.length > 0) {
var span = spans[0];
if (span.dataset.timerId) {
clearTimeout(span.dataset.timerId);
}
span.remove();
}
}
function addLoading(id, options) {
options = options || {};
var parent = document.getElementById(id);
var existingSpans = parent.getElementsByClassName("loading_dots");
if (existingSpans.length > 0) {
removeLoading(id);
}
var span = document.createElement("span");
span.setAttribute("class", "loading_dots");
if (options.timerId) {
span.dataset.timerId = options.timerId;
}
parent.insertAdjacentElement(options.position || "beforeend", span);
setInterval(function () {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400)
}
function addLoadingWithTimeout(id, ms, options) {
options = options || {};
var timerId = setTimeout(function () { removeLoading(id) }, ms);
options.timerId = timerId;
addLoading(id, options);
}
<p id="load1">Load 1 - Will stop automatically in 3 seconds after starting. </p>
<button onclick="addLoadingWithTimeout('load1', 3000)">Start Load 1</button>
<button onclick="removeLoading('load1')">Stop Load 1</button>
<p id="load2">Load 2 - Only manual Stop </p>
<button onclick="addLoading('load2')">Start Load 2</button>
<button onclick="removeLoading('load2')">Stop Load 2</button>
Here you go. on the HTML side, you just pass the event to the button that you want and then the id, as a string, of the span/div where you want the load icons to appear.
HTML:
<button id="btn" onclick="load(event, 'loadDiv')">Load</button>
<div>
<span id="loadDiv"></span>
</div>
Below, we are getting the btn id from event so you don't have to manually pass it everytime. Then we are defining function for the innerhtml icons. Lastly, we are running the showIcon function every .4s and then clearing the interval after 5 seconds.
JS:
function load(e, location) {
var btn = document.getElementById(e.srcElement.id)
var loadDiv = document.getElementById(location)
function showLoad() {
if (loadDiv.innerHTML.length < 3) {
return loadDiv.innerHTML += '●'
}
loadDiv.innerHTML = ''
}
(function() {
var loadIcons = setInterval(function() {
showLoad()
}, 400)
var clear = setTimeout(function() {
clearInterval(loadIcons)
}, 5000)
})()
}
Hope this helps!
You can define your code in a function and add click handler to the button.
function myFunc() {
var span = document.getElementById('loading_dots');
var int = setInterval(function() {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400);
(function(){
var loading_dots = document.getElementById("loading_dots"),
show = function(){
loading_dots.style.display = "block";
setTimeout(hide, 5000); // 5 seconds
},
hide = function(){
loading_dots.style.display = "none";
};
show();
})();
}
document.getElementById("myBtn1").addEventListener("click", myFunc);
document.getElementById("myBtn2").addEventListener("click", myFunc);

JS/CSS accordion sliding transition problems

I'm trying to do JS module for slidingup/slidingdown HTML blocks.
JS module is calculating block max-height.
The problem is, that CSS transition works only for sliding down.
I can't find the right solution.
Here is jsFiddle
var Accordion = {
'vars': {
'attrItem': 'data-accordion-item',
'attrToggle': 'data-accordion-toggle',
'classOpened': '_active',
'classPrepare': '_preparing',
'timer': null
},
'accObject': {},
'accData': function(accID, key, value) {
var module = this;
if (typeof value != 'undefined') {
if (typeof module.accObject[accID] == 'undefined') {
module.accObject[accID] = {};
}
module.accObject[accID][key] = value;
} else {
return module.accObject[accID][key];
}
},
'init': function() {
var module = this;
// Loop accToggles
$('*[' + module.vars.attrToggle + ']').each(function() {
var accToggle = $(this);
var accID = accToggle.attr(module.vars.attrToggle);
// Store data of ID
module.accData(accID, 'accID', accID);
// Store data of toggle
if (!module.accData(accID, 'accToggle')) {
module.accData(accID, 'accToggle', accToggle);
} else {
module.accData(accID, 'accToggle', module.accData(accID, 'accToggle').add(accToggle));
}
// Attach click to accToggle
accToggle.click(function(e) {
e.preventDefault();
// Toggle between open/close state
module.accData(accID, 'accOpened') ? module.toggle(accID, false) : module.toggle(accID, true);
});
});
// Loop accItems
$('*[' + module.vars.attrItem + ']').each(function() {
var accItem = $(this);
var accID = accItem.attr(module.vars.attrItem);
var accOpened = accItem.hasClass(module.vars.classOpened) ? true : false;
// Store data of ID
module.accData(accID, 'accID', accID);
// Store data of item
if (!module.accData(accID, 'accItem')) {
module.accData(accID, 'accItem', accItem);
} else {
module.accData(accID, 'accItem', module.accData(accID, 'accItem').add(accItem));
}
// Store data of state
if (!module.accData(accID, 'accOpened')) module.accData(accID, 'accOpened', accOpened);
// Check to open or close accItem
accOpened ? module.toggle(accID, true) : module.toggle(accID, false);
});
},
'getSize': function(accItem) {
var module = this;
accItem.addClass(module.vars.classPrepare);
var height = accItem.outerHeight();
accItem.removeClass(module.vars.classPrepare);
return height;
},
'toggle': function(accID, open, skipAnimation) {
var module = this;
var accItems = module.accData(accID, 'accItem');
var accToggles = module.accData(accID, 'accToggle');
var accOpened = module.accData(accID, 'accOpened');
var action;
// Check for action open/close and set vars
if (open) {
module.accData(accID, 'accOpened', true);
action = 'addClass';
} else {
module.accData(accID, 'accOpened', false);
action = 'removeClass';
}
// Loop items
if (accItems) {
accItems.each(function() {
var accItem = $(this);
accItem[action](module.vars.classOpened);
// Timer fights against no animation
if (module.timer) clearTimeout(module.timer);
module.timer = setTimeout(function() {
accItem.css('max-height', open ? module.getSize(accItem) : 0);
}, 10);
});
}
// Loop toggles
if (accToggles) {
accToggles.each(function() {
var accToggle = $(this);
accToggle[action](module.vars.classOpened);
});
}
}
}
$(document).ready(function() {
Accordion.init();
});
.f-control {
background: #ddd;
}
*[data-accordion-item] {
max-height: 0;
padding-bottom: 6px;
overflow: hidden;
opacity: 0;
-webkit-transition-property: max-height, opacity;
transition-property: max-height, opacity;
-webkit-transition-duration: 300ms;
transition-duration: 300ms;
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
*[data-accordion-item]._active {
opacity: 1;
}
*[data-accordion-item]._preparing {
max-height: initial !important;
-webkit-transition: none;
transition: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="f-row">
<a href="#" class="side-title" data-accordion-toggle="1">
<span>Show/hide</span>
</a>
<div class="f-control" data-accordion-item="1">
<h1>Test1</h1>
<h2>Test2</h2>
</div>
</div>
JQuery has a simple enough way of generating this kind of functionality using slideToggle to show/hide elements. You can even set the speed :)
$('#showHide').click(function(){
$('div').slideToggle("fast");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="showHide">hideshow</button>
<div>
this <br/>
and this
</div>

Use function everywhere without writing it more than once

Trying to get my code cleaner I don't want to write the same code many times but don't know how to accomplish it. You can see in the code below is the if/else written twice but doing the same. How can I return data and call that function again with writing it only once?
Help and advices are much appreciated.
Code is like this:
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
// don't want to write this more than once
// but need to call here on document ready
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
$(window).scroll(function(event){
scroll = $(this).scrollTop();
// here I need it again
// scroll is changing on scroll
// but "function" does exactly the same like above
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
});
})(jQuery);
if you need html and css working example: fiddle http://jsfiddle.net/cejs3jhs/ and rest of code:
<header>
<div class="big">
<h1>Page Title</h1>
</div>
<div class="small">
<span class="icon nav-icon">Nav Icon</span>
</div>
</header>
<div class="page"></div>
<style type="text/css">
header {
width:100%;
background-color:red;
opacity:0.5;
}
header.toggle-nav {
height:100%;
}
header.toggle-nav ul {
display:block;
}
header > div {
position:relative;
width:976px;
margin:0 auto;
}
header > div.big {
padding:30px 0;
}
.page {
height:5000px;
background-color:orange;
opacity:0.5;
}
</style>
So just make separate function for that:
function showHideNav(scroll, headerBigWrapHeight, element) {
var scroll = element.scrollTop(),
header = $('header'),
headerSmall = header.children('.small'),
headerBigWrap = header.children('.big')
headerBigWrapHeight = headerBigWrap.height();
if( scroll >= headerBigWrapHeight ) {
header.css('position','fixed');
} else {
header.css('position','static');
}
headerBigWrap.toggle();
headerSmall.toggle();
}
(function($){
showHideNav(scroll);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
showHideNav(scroll);
});
})(jQuery);
The answer to your question is simply what Justinas said, make another function. But you can improve a bit with some more aggressive editing, which is what I've done.
(function ($) {
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
function setNavStyle() {
var scroll = $(this).scrollTop();
if( scroll >= headerBigWrapHeight ) {
header.css('position', 'fixed');
headerSmall.css('display', 'block');
headerBigWrap.css('display', 'none');
} else {
header.css('position', 'static');
headerSmall.css('display', 'none');
headerBigWrap.css('display', 'block');
}
}
$(window).scroll(setNavStyle);
setNavStyle();
})(jQuery);
That's one way, but it would be better (more maintainable, simpler, faster) to do the bulk of
the work with CSS, like so:
CSS:
header {
position: static;
}
header>.small {
display: none;
}
header>.big {
display: block;
}
.stickyNav header {
position: fixed;
}
.stickyNav header>.small {
display: block;
}
.stickyNav header>.big {
display: none;
}
JavaScript:
(function ($) {
var bigNavHeight = $('header>.big').height();
function setNavStyle() {
var bigIsOffscreen = $(this).scrollTop() >= bigNavHeight;
$(document.body).toggleClass('stickyNav', bigIsOffscreen);
}
$(window).scroll(setNavStyle);
setNavStyle();
})(jQuery);
You can define a new function just as you did with the showNav & hideNav functions
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
var checkScroll = function (scroll,headerBigWrapHeight){
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
checkScroll(scroll,headerBigWrapHeight);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
checkScroll(scroll,headerBigWrapHeight);
});
})(jQuery);
Please find below updated JS code:
(function($){
var scroll = $(this).scrollTop();
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
var headerBigWrapHeight = headerBigWrap.height();
var showNav = function() {
header.css('position','fixed');
headerBigWrap.css('display','none');
headerSmall.css('display','block');
}
var hideNav = function() {
header.css('position','static');
headerSmall.css('display','none');
headerBigWrap.css('display','block');
}
var callFun = function(scroll) {
if( scroll >= headerBigWrapHeight ) {
showNav();
} else {
hideNav();
}
}
callFun(scroll);
$(window).scroll(function(event){
scroll = $(this).scrollTop();
callFun(scroll);
});
})(jQuery);
Do it exactly like you have done with functions showNav and hideNav: define a function with if/else inside somewhere and you can call it by name wherever needed. There are also some variables which can be omitted then, so I show all code here:
(function($){
// var scroll is moved into function scrollFunc
var header = $('header');
var headerSmall = header.children('.small');
var headerBigWrap = header.children('.big');
// var headerBigWrap is moved into function scrollFunc
var showNav = function() {
/* your code */
}
var hideNav = function() {
/* your code */
}
var scrollFunc = function () {
if($(this).scroll() >= headerBigWrap.height() ) {
showNav();
} else {
hideNav();
}
}
$(window).scroll(function(event){
scrollFunc();
});
scrollFunc(); // call it first time to initialize
});

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

setInterval and Switch Between Divs

I'm trying to switch between divs at an interval, but also be able to stop it in order to include the ability to switch on command with an arrow button on the screen. (Like a slideshow of divs with an arrow to switch immediately.)
Therefore, I cannot use .delay(), as it cannot be stopped, so I'm trying to use .setTimeout, but I'm failing miserably. Can someone tell me what I'm doing wrong?
var divs = $('div[id^="Frame"]').hide(),
i = 0;
(function cycle() {
divs.eq(i).fadeIn(1000)
.setTimeout(function(){divs.eq(i).fadeOut(1000, cycle);},2000);
i = ++i % divs.length; // increment i,
// and reset to 0 when it equals divs.length
})();
I'm not sure what you are trying to achieve, but here is some code which will fadein/fadeout the divs and you have a chance to stop the process:
var divs = $('div[id^="Frame"]').hide(),
i = 0,
currentDiv = null,
interval = null;
var stopFading = function() {
clearTimeout(interval);
}
var showDiv = function() {
if(currentDiv) {
currentDiv.fadeOut(1000, function() {
currentDiv = null;
showDiv();
});
} else {
currentDiv = divs.eq(i);
currentDiv.fadeIn(1000, function() {
interval = setTimeout(showDiv, 2000);
});
i += 1;
if(i > divs.length) i = 0;
}
}
showDiv();
LIVE DEMO
JS:
var H = $('#FrameHolder'),
D = $('#Frame > div'),
B = $('#Button'),
n = D.length,
f = 400, // fade time
p = 2500,// pause
c = 0, // counter
i; // interval
function loop(){
i = setInterval(function(){B.click();},p);
}loop();
H.hover(function(e){
var mEnt = e.type.match('t');
B.stop().fadeTo(f,!!mEnt);
return mEnt?clearInterval(i):loop();
});
B.click(function(){
D.stop().fadeOut(f).eq(++c%n).fadeIn(f);
});
HTML:
<div id="FrameHolder">
<div id="Frame">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div id="Button"></div>
</div>
CSS:
#FrameHolder{
position:relative;
margin:0 auto;
width:400px;
height:300px;
overflow:hidden;
}
#frame{
}
#Frame > div{
position:absolute;
top:0;
text-align:center;
line-height:276px;
width:400px;height:300px;
}
#Frame > div + div{
display:none; /* hide all but 1st */
}
#Button{
cursor:pointer;
position:absolute;
width:60px;
height:60px;
background:rgba(0,0,0,0.5);
border-radius:50%;
right:20px;
top:50%;
margin-top:-30px;
display:none;
}
Haven't taken a look to see if the rest of your code is working, but the immediate error is that setTimeout is not chainable. So the code should look like this...
EDIT -- SHOULD WORK
The other issue was that the increment of i needed to be done in the setTimeout otherwise, i would be incremented before the function ran
http://jsfiddle.net/RJe86/1/
var divs = $('div[id^="Frame"]').hide(),
i = 0;
(function cycle() {
divs.eq(i).fadeIn(1000,function(){
setTimeout(function(){
divs.eq(i).fadeOut(1000, cycle);
i = ++i % divs.length; // increment i,
// and reset to 0 when it equals divs.length
},2000);
});
})();

Categories