I am using this code to move images randomly in an area. But I need to show atleast 3 images always. Here is what I had done:
HTML
<div class="fade">Image 1</div>
<div class="fade">Image 2</div>
<div class="fade">Image 3</div>
<div class="fade">Image 4</div>
<div class="fade">Image 5</div>
<div class="fade">Image 6</div>
jQuery
(function fadeInDiv() {
var divs = jQuery('.fade');
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.fadeIn(Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.fadeOut(Math.floor(Math.random() * 1000), function() {
elem.before('<div> </div>');
fadeInDiv();
});
}
})();
This code fadein and fadeout images randomly as a result show 2 images at a time sometimes 1 image at a time sometime 3. I need to show 3 images with in 6 images every time with fadein fadeout functionality.
Here is how my home page look like:
Image1 Image2
Image3
I want it to look like:
Image1
Image2 Image3
or
Image1
Image2 Image3
or any other pattern with this images
you need to use css properties to change their position on the screen.
You ll have to precise their positionning style, IE absolute.
elem.css('top','15px') and elem.css('left','15px') are the propers method to move objects on screen. You ll adjust the 15px to the value you ll need. It s relative to the top-left corner of your screen.
fadeIn / fadeOut only change opacity property of those objects on the screen.
Try a recursive algorithm with delay lengths depending on the random order of the objects:
window.refresh = function(delay) {
delay *= 1000;
var doms = [];
var randos = [];
var index = 0;
function fadeout() {
if (index < 3) {
var random = $(doms.get(randos[index]));
$(random).delay(delay + 200 * index).fadeTo(200, 0, function() {
$(random).css("visibility", "hidden");
});
doms = doms.not(random);
index++;
fadeout(doms);
}
}
doms = $('.grid-item');
doms.css("visibility","visible");
doms.css("opacity","1");
var num = Math.floor(Math.random() * doms.length);
for (var i = 0; i < doms.length; i++) {
while (randos.indexOf(num) > -1) {
num = Math.floor(Math.random() * doms.length);
}
randos.push(num);
}
fadeout();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
<div class="grid-item">Image 1</div>
<div class="grid-item">Image 2</div>
<div class="grid-item">Image 3</div>
<div class="grid-item">Image 4</div>
<div class="grid-item">Image 5</div>
<div class="grid-item">Image 6</div>
</div>
<br>
<button onclick="refresh(0)">Trigger Animation</button>
<br>
<br>
<input type="number" placeholder="Time in Seconds">
<button onclick="refresh($(this).prev().val())">Trigger Delayed Animation</button>
Related
Im trying to create a Javascript carousel that displays a random div and changes every 3 seconds.
I have the random div displaying on load but unsure what to add make it change to the next one.
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content1">This is content 1</div>
<div id="content2">This is content 2</div>
<div id="content3">This is content 3</div>
<div id="content4">This is content 4</div>
<div id="content5">This is content 5</div>
<div id="content6">This is content 6</div>
put your code in an interval like this :
setInterval(function(){
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
else{
$(elems[i]).show();
}
}
}
},1000); // change every 1s ;
================================
UPDATE
to hide all divs before interval starts u have two way .
first way is to use css . u can add a css class to divs named "hide-at-start" and define it like this :
.hide-at-start
{
display:none;
}
and add it to divs :
<div id="content1" class="hide-at-start">This is content 1</div>
<div id="content2" class="hide-at-start">This is content 2</div>
<div id="content3" class="hide-at-start">This is content 3</div>
<div id="content4" class="hide-at-start">This is content 4</div>
<div id="content5" class="hide-at-start">This is content 5</div>
<div id="content6" class="hide-at-start">This is content 6</div>
second way is to do it via javascript like this :
function showRandomDiv(){
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
else{
$(elems[i]).show();
}
}
}
}
showRandomDiv(); // runs once
setInterval(showRandomDiv,1000); // change every 1s ;
i prefer the first solution however .
========================
UPDATE
to add animations there are many ways . for instance u can use css #keyframes like this :
#keyframes fade-in-from-left {
0% {left: 0px;opacity: 0;}
50% {left: 20px;opacity: 0.5;}
100%{left:0px;opacity: 1;}
}
.fade-in-from-left{
position: relative;
animation: fade-in-from-left 0.5s forwards;
}
then add fade-in-from-left to your divs like this :
<div class="hide-at-start fade-in-from-left">This is content 1</div>
<div class="hide-at-start fade-in-from-left">This is content 2</div>
<div class="hide-at-start fade-in-from-left">This is content 3</div>
<div class="hide-at-start fade-in-from-left">This is content 4</div>
<div class="hide-at-start fade-in-from-left">This is content 5</div>
<div class="hide-at-start fade-in-from-left">This is content 6</div>
I have a problem,
in Html
<div class="item ">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
in JS
var random = Math.floor(Math.random() * $('.item').length);
$('.item').hide().eq(random).show();
I need add class (no-active) of automatically and randomly in the div with class (item), but no for all divs. only some div.
Now my code only show 1 div, and it's not what I want.
you try this :
var random = Math.floor(Math.random() * $('.item').length);
var newrandom = 0;
//alert(random);
if(random==0){//alert(random);
$('.item').hide().eq(random).show();
}else if(random>0){
$('.item').hide();
for(var i=1; i<=random; i++){
newrandom = Math.floor(Math.random() * $('.item').length);
$('.item').eq(newrandom).show();
//alert(newrandom);
}
}
Using this u will get random no. for random times.
You can use each and toggleClass for that:
$(".item").each(function () {
$(this).toggleClass('no-active', Math.random() < 0.5);
});
.no-active { visibility: hidden }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item ">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
I would like to create something akin to a slide show, whenever the button #more-projectsis clicked 4 divs would show, when it's clicked again those divs get hidden and the next 4 divs show, this needs to loop infinitely and be applied to any number of divs.
In this context I have 6 divs with the class .thumbnail-cnt within the div '#container', when I click #more-projects I would like the first 4 of these divs to show, divs 1,2,3,4. When #more-projects is clicked again the next 4 divs in the cycle would be shown so 5,6,1,2. Clicked again, divs 1,2,3,4 are shown. How can I select the next index and make the function iterate over the elements infinitely?
<div id="container">
<div class="thumbnail-cnt" data-num="1">1
</div>
<div class="thumbnail-cnt" data-num="2">2
</div>
<div class="thumbnail-cnt" data-num="3">3
</div>
<div class="thumbnail-cnt" data-num="4">4
</div>
<div class="thumbnail-cnt" data-num="5">5
</div>
<div class="thumbnail-cnt" data-num="6">6
</div>
</div>
<button id="more-projects" > Next
</button>
My JS so far is
var startIndex = 0;
$('#more-projects').on("click", function() {
var endIndex = startIndex + 4;
var nextIndex = endIndex +1;
$('#container .thumbnail-cnt').slice(startIndex, endIndex).addClass('visible');
var startIndex = nextIndex;
}
CSS
.thumbnail-cnt {
display: none;
}
.visible {
display: block;
}
A solution can be based on:
save the initial value of max number of visible items as data value of your div
save the start index as another data value
So, the initial value is:
<div id="container" data-start-index="0" data-max-visible-length="4">
In the click handler compute the end index position. If it exceeds the max you need to start from the beginning. Save this new value as the new start index.
$('#more-projects').on("click", function() {
var startIndex = $('#container').data('startIndex');
var maxVisibleLength = $('#container').data('maxVisibleLength');
var endIndex = startIndex + maxVisibleLength;
var itemCounts = $('#container .thumbnail-cnt').length;
$('#container .thumbnail-cnt.visible').removeClass('visible');
if (endIndex > itemCounts) {
endIndex = endIndex - itemCounts;
$('#container .thumbnail-cnt').slice(startIndex).addClass('visible');
$('#container .thumbnail-cnt').slice(0, endIndex).addClass('visible');
} else {
$('#container .thumbnail-cnt').slice(startIndex, endIndex).addClass('visible');
}
$('#container').data('startIndex', endIndex);
});
.thumbnail-cnt {
display: none;
}
.visible {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" data-start-index="0" data-max-visible-length="4">
<div class="thumbnail-cnt" data-num="1">1
</div>
<div class="thumbnail-cnt" data-num="2">2
</div>
<div class="thumbnail-cnt" data-num="3">3
</div>
<div class="thumbnail-cnt" data-num="4">4
</div>
<div class="thumbnail-cnt" data-num="5">5
</div>
<div class="thumbnail-cnt" data-num="6">6
</div>
</div>
<button id="more-projects" > Next
</button>
You can try this for your JS. This will ensure an infinite loop-
var startIndex = 0;
$('#more-projects').on("click", function() {
var count = 0;
var divs = $('#container .thumbnail-cnt');
var len = divs.length
var index;
while( count < 4 ){
index = (startIndex+count) % len;
divs[index].addClass('visible');
count++;
}
startIndex += count;
index++; //to ensure removal start from the next
while( count < len ){
index = index % len;
divs[index++].removeClass('visible');
count++;
}
}
% ensures the boundary and wrapping. Removing class visible for the other divs that need not be shown. Your current implementation must have been failing on this.
The given code is only working in Firefox and not in any other browser.
I have given the Fiddle link for it.The code is working fine in Firefox and the functions are also working but it is not supported by any other browser.
The error shows is
Error due to long Script
Fiddle
Here is the code.
var $boxes;
$(document).ready(function() {
$boxes = $(".box");
setupColumns();
$(window).on("resize", setupColumns);
});
function setupColumns() {
var $columnwrapper = $("#columns");
var w = $("<div>").addClass("column").width();
var cnt = Math.floor($columnwrapper.width() / w);
var cols = [];
for (var i = 0; i < cnt; i++) {
var $col = $("<div>").addClass("column");
cols.push($col);
}
$columnwrapper.append(cols);
var cnt = 0;
$boxes.each(function() {
$(this).detach().appendTo(cols[cnt]);
cnt = (cnt + 1) % cols.length;
});
}
$(".box").click(function() {
if ($(this).height() != 100)
$(this).animate({
height: 100
}, 1000);
else
$(this).animate({
height: 150
}, 1000);
});
.column {
width: 114px;
float: left
}
.box {
height: 100px;
width: 100px;
border: 2px solid;
margin-bottom: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="columns"></div>
<div class="box">HELLO WORLD 1</div>
<div class="box">HELLO WORLD 2</div>
<div class="box">HELLO WORLD 3</div>
<div class="box">HELLO WORLD 4</div>
<div class="box">HELLO WORLD 5</div>
<div class="box">HELLO WORLD 6</div>
<div class="box">HELLO WORLD 7</div>
<div class="box">HELLO WORLD 8</div>
<div class="box">HELLO WORLD 9</div>
<div class="box">HELLO WORLD 10</div>
The problem is due to following line:
var w = $("<div>").addClass("column").width();
Apart from Firefox, in other browsers its returning 0 which causes cnt to become Infinity. That's why you are getting a really long running script that's creating infinite divs and adding them to cols[]
Documentation for .width() says:
The value reported by .width() is not guaranteed to be accurate when
the element or its parent is hidden. To get an accurate value, ensure
the element is visible before using .width().
So what you will need to do is:
var $boxes;
$(document).ready(function() {
$boxes = $(".box");
setupColumns();
$(window).on("resize", setupColumns);
});
function setupColumns() {
var $columnwrapper = $("#columns");
//////////start change////////////
var dummy = $("<div>").addClass("column");
dummy.appendTo($columnwrapper); // add it to wrapper so that it gets displayed
var w = dummy.width(); // this now returns 114
dummy.remove(); // now that we have got the width, remove it
// just to be on safer side:
if(w == 0){
console.log("column width is 0.");
return;
}
//////////end change////////////
var cnt = Math.floor($columnwrapper.width() / w);
var cols = [];
for (var i = 0; i < cnt; i++) {
var $col = $("<div>").addClass("column");
cols.push($col);
}
$columnwrapper.append(cols);
var cnt = 0;
$boxes.each(function() {
$(this).detach().appendTo(cols[cnt]);
cnt = (cnt + 1) % cols.length;
});
}
$(".box").click(function() {
if ($(this).height() != 100)
$(this).animate({
height: 100
}, 1000);
else
$(this).animate({
height: 150
}, 1000);
});
.column {
width: 114px;
float: left
}
.box {
height: 100px;
width: 100px;
border: 2px solid;
margin-bottom: 10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="columns"></div>
<div class="box">HELLO WORLD 1</div>
<div class="box">HELLO WORLD 2</div>
<div class="box">HELLO WORLD 3</div>
<div class="box">HELLO WORLD 4</div>
<div class="box">HELLO WORLD 5</div>
<div class="box">HELLO WORLD 6</div>
<div class="box">HELLO WORLD 7</div>
<div class="box">HELLO WORLD 8</div>
<div class="box">HELLO WORLD 9</div>
<div class="box">HELLO WORLD 10</div>
This is maybe because of cross-browser security concept by the modern browsers. If you are trying to run in Google Chrome. You might have to use the older version or install the plugin such as this:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
I am creating a simple game that has 9 divisions and each 8 of the divisions have a penguin hidden in them and the 9th one has a monster. Now my game works fine but what I want to do is every time I load the page, arrangement of the divisions should change so as to add randomness to the game.
Here is my code:
$(document).ready(function() {
//This code will run after your page loads
$('body').on('mousedown', '.yeti', function(event) {
alert("Yaaaarrrr!");
});
});
<div class="gameholder">
<div class="title"></div>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti"></div>
</div>
After adding images and some positioning to the div's this is how it looks
Keeping Your Animals Contained
Consider creating a container for all of your game elements as you only want to randomize their order as you don't want to get the title mixed up in all of this :
<div class='game-container'>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti">
</div>
Shuffling Them Around
This should make them easier to randomize through a simple jQuery extension function like this one mentioned in this related thread :
$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
}).detach().appendTo(this);
});
return this;
};
You can combine these two approaches by then simply calling the following when your page has loaded :
$(document).ready(function(){
// Define your randomize function here
// Randomize all of the elements in your container
$('.game-container').randomize('div');
});
Example
$.fn.randomize = function(selector){
(selector ? this.find(selector) : this).parent().each(function(){
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
}).detach().appendTo(this);
});
return this;
};
// Randomize all of the <div> elements in your container
$(".game-container").randomize('div');
.game-container { width: 300px; }
.penguin { background: url('http://vignette1.wikia.nocookie.net/farmville/images/b/be/Baby_Penguin-icon.png/revision/latest?cb=20110103080900'); height: 100px; width: 100px; display: inline-block; }
.yeti { background: url('http://www.badeggsonline.com/beo2-forum/images/avatars/Yeti.png?dateline=1401638613'); height: 100px; width: 100px; display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='game-container'>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='penguin'></div>
<div class='yeti'></div>
<div class='penguin'></div>
</div>
<body>
<div class="gameholder">
<div class="title"></div>
<div class="penguin1"></div>
<div class="penguin2"></div>
<div class="penguin3"></div>
<div class="penguin4"></div>
<div class="penguin5"></div>
<div class="penguin6"></div>
<div class="penguin7"></div>
<div class="penguin8"></div>
<div class="yeti"></div>
</div>
<script type="text/javascript">
$(document).ready( function() {
$('.gameholder div').shuffle();
/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
var j;
for (var i = 0; i < this.length; i++) {
j = Math.floor(Math.random() * this.length);
$(this[i]).before($(this[j]));
}
return this;
};
//This code will run after your page loads
$('body').on('mousedown', '.yeti', function(event) {
alert("Yaaaarrrr!");
});
});
</script>
Here you would like to know what this 2 line of code is doing ->
j = Math.floor(Math.random() * this.length); // (1)
$(this[i]).before($(this[j])); // (2)
Here in line 1 first I am getting random number using Math.random, Math.random gives you floating number ranging from zero to one. so here I am multiplying that number with length, so it gives me random floating number from zero to length, now I am flooring this number to integer, to get integer from zero to length - 1
If we have a selector $('#b').before('#a') then it puts #a element before #b element, so here we are getting one by one element and putting them in the random order.