So I found this already on here and it's almost exactly what I want. The only difference is that instead of creating boxes, I'd like for them to be words taken from an array - like
var textarray = [
"wow",
"so amaze",
"much hunt",
"such treasure"];
So that instead of colored boxes popping up randomly it would be one of those random words randomly colored. Here is the code from the jsfiddle.
(function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
$(this).remove();
makeDiv();
});
})();
How is this?
http://jsfiddle.net/x2EXz/1/
(comments about changes listed in-line below)
var textArray = [
"wow",
"so amaze",
"much hunt",
"such treasure"];
function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width': ' 30 px', // sets width to constant
'height': '10px', // sets height to constant
// removes background-color property of div, but keeps
// generating random colors that will be applied to the random words
// 'background-color': color
});
// randomWord will accommodate for textArray of any size
var randomWord = textArray[ (Math.floor(Math.random() * textArray.length)) ]
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
// appends randomWord to new div
$newdiv.text(randomWord).css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none',
// adds randomly generated color to random word
'color' : color
}).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
$(this).remove();
makeDiv();
});
}
makeDiv();
Related
For a personal project I'm trying to fill the window with randomly generated div's. I got started with a code I found in some thread and tweaked it to my liking (color and width of the div's for example).
However, this code was designed to generate a div, then make it fade out, and cycle that again. What I'd like is to have a set number of div's loaded on page load and without them disappearing.
I do recognize the ".fadeOut" and ".remove()" at the end of the code, but for the life of me I can't figure out how to prevent the div's from disappearing without breaking the code, let alone having a set number of randomly placed div's appear at once.
(function makeDiv() {
var divsize = ((Math.random() * 100) + 30).toFixed();
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width': 2 + 'px',
'height': divsize + 'px',
'border': '1px solid' + color,
'transform': 'rotate(' + divsize + 'deg)',
'background-color': color,
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position': 'absolute',
'left': posx + 'px',
'top': posy + 'px',
'display': 'none',
'border-radius': '100px',
}).appendTo('body').fadeIn(100).delay(300).fadeOut(200, function() {
$(this).remove();
makeDiv();
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So something like this?
All that I did was remove the fadeIn and fadeOut parts, and then added a simple function to create a fixed number of divs. I also removed the display: 'none' from the divs that were being created.
var makeDiv = () => {
var divsize = ((Math.random() * 100) + 30).toFixed();
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width': 2 + 'px',
'height': divsize + 'px',
'border': '1px solid' + color,
'transform': 'rotate(' + divsize + 'deg)',
'background-color': color,
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position': 'absolute',
'left': posx + 'px',
'top': posy + 'px',
'border-radius': '100px',
}).appendTo('body');
}
var generateDivs = (x) => {
for (let i = 0; i < x; i++) {
makeDiv();
}
}
generateDivs(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Please find the code, which iam facing issue with changing the direction of arrow, the arrow should change the facing from right to left once it reach the screen width. THE REQUIRED FUNCTIONALITY IS THE ARROW SHOULD NOT GO IN REVERSE it has to change its direction.
tried lot some one give solution.
http://jsfiddle.net/7xyuqe1k/5/
function AnimateFish() {
var Fish3 = $("[id^=fish]").not(".HoverFish"),
theContainer = $("#container"),
maxLeft = theContainer.width() - Fish3.width() - 50,
maxTop = theContainer.height() - Fish3.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100,
imgRight = "Assets/fish-glow3-right.gif",
imgLeft = "Assets/fish-glow3.gif";
/*Get position of the fish*/
//console.log(Fish3.position().left +" +"+leftPos);
//alert(Fish3.position().left);
if ($("[id^=fish]").position().left >= leftPos) {
$(this).css("background-image", 'url("' + imgRight + '")');
} else {
$(this).css("background-image", 'url("' + imgLeft + '")');
}
Fish3.animate({
"left": leftPos,
"top": topPos
}, 1800, AnimateFish);
}
There was a problem on fish's destination points(positions left & top) picking. First fish works properly since it's picking the destination point respective to itself, but rest of the fishes also were taking the destination points respective to 1st fish not themselves.
The working sample is available here http://jsfiddle.net/ravinila/7xyuqe1k/26/
$(document).ready(function(e) {
var newfishid = 0;
$('.post-button').click( function(e) {
var fish = $("<div/>", {"class":"large-fish fish", "id" : "fish"+(newfishid++)});
$('#container').append(fish);
fish.on("anim", function(e){
var _this = $(this),
theContainer = $("#container"),
maxLeft = theContainer.width() - _this.width() - 50,
maxTop = theContainer.height() - _this.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100,
imgLeft = "http://free-icon-download.com/modules/PDdownloads/images/screenshots/free-icon-download_left-arrow-blue.png",
imgRight = "http://www.newclassicdesign.com/r_arrow.png";
if (_this.position().left < leftPos) {
_this.css("background-image", 'url("' + imgRight + '")');
} else {
_this.css("background-image", 'url("' + imgLeft + '")');
}
_this.animate({
"left": leftPos,
"top": topPos
}, 2500, function(){
$(this).trigger("anim");
});
});
fish.trigger("anim");
fish.hover(function(e) {
$(this).stop();
}, function(e) {
$(this).trigger("anim");
});
});
});
I have taken a look at it and it looks like its a silly mistake. Your fiddle showed something was working since it changed something when the direction changed, so the basics are okay. You just forgot that there was an image tag inside you div that you're meant to be manipulating.
function AnimateFish() {
var Fish3 = $("#fish1").not(".HoverFish"),
theContainer = $("#container"),
maxLeft = theContainer.width() - Fish3.width() - 50,
maxTop = theContainer.height() - Fish3.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100;
imgRight = "http://www.newclassicdesign.com/r_arrow.png",
imgLeft = "http://free-icon-download.com/modules/PDdownloads/images/screenshots/free-icon-download_left-arrow-blue.png";
// below here you used $(Fish3), but Fish3 is already a JS object - you don't need to rewrap it.
// The biggest problem however, is that below that you used '$(this)', which won't work as there
// is no context defined (you're in an if, not a jQuery function).
// Replacing this with the same Fish3 does the job,
// as it already was a jQuery object anyhow.
// I have also changed your background from an image to red and green for testing purposes.
// As you can see, thats working. However, your image isn't changing..
// This is because you have an image inside you wrapper which you aren't changing.
if (Fish3.position().left >= leftPos) {
Fish3.css("background", 'green');
// So lets change the image...
Fish3.find("img").attr("src", imgLeft);
} else {
Fish3.css("background", 'red');
// So lets change the image...
Fish3.find("img").attr("src", imgRight);
}
Fish3.animate({
"left": leftPos,
"top": topPos
}, 1800, AnimateFish);
}
Check my comments inside the code to see what happened, but copying this into your fiddle and replacing the animation function did the trick.
I'm attempting to put together a webpage that has text that pops up at random locations on the page, fade out, then appear again at a random location again. I found something that suits my purposes for example. I want something like this, but with text that I can manipulate and make a list out of with text-shadow effects if needed.
(function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
$(this).remove();
makeDiv();
});
})();
Fiddle
This is a second example of something similar, only it doesn't have random position.
$('li').each(function(){
var randomTop = $('div').height()*Math.random(); //random top position
var randomLeft = $('div').width()*Math.random(); //random left position
$(this).css({ //apply the position each li
top : randomTop,
left : randomLeft
});
});
Fiddle
I'm hoping to sort of splice the two together in order to get what I'm ideally looking for. Please forget the formatting as its my first time here and I'm trying to conform to the standards.
I'm not sure if I understand exactly what you're looking for but I "spliced them together."
Fiddle
(function fadeInDiv(){
var divs = $('.fadeIn');
var divsize = ((Math.random()*100) + 50).toFixed();
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
var maxSize = 30;
var minSize = 8;
var size = (Math.random()*maxSize+minSize)
var elem = divs.eq(Math.floor(Math.random()*divs.length));
if (!elem.is(':visible')){
elem.fadeIn(Math.floor(Math.random()*1000),fadeInDiv);
elem.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'font-size': size+'px'
});
} else {
elem.fadeOut(Math.floor(Math.random()*1000),fadeInDiv);
}
})();
EDIT: Updated Fiddle URL
(function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(700).delay(3500).fadeOut(300, function(){
$(this).remove();
makeDiv();
});
})();
FIDDLE: http://jsfiddle.net/redler/QcUPk/8/
Design mockup: http://i.imgur.com/D4mhXPZ.jpg
I've tried fiddling with this code I found but I just end up butchering it and breaking it. In one instance I had the code doubling the objects every iteration and it almost crashed my PC, heh.
I need a few things happening here.
I need there to be at least 8 of these objects simultaneously performing this appearing and disappearing act, overlapping each other slightly offset (centerOffset?). Each appearing square should be in the front of previous images that still linger.
The objects are not colored squares, but should be images called randomly from a database (an inventory of products).
When you mouseover any of the pictures, the process should pause and that object will come to the front while you keep your mouse on it, displaying some text about the piece. If you click it it will navigate you away to the items page.
Note: The random sizing element is nice but I have some taller images, some wider images, etc. Not sure how to handle that.
There is quite a bit of animation/timing work to keep 8 objects simultaneously appearing/disappearing. The next hard bit is capturing the mouseover the objects and when to "come to the front", you might need the jQuery hover intent plugin. Anyways, here's some working code that will simultaneously animate 8 random objects onto the screen, and the appearing/disappearing act will stop when you mouseover an object. When your mouse leaves the object, the animation will continue: http://jsfiddle.net/amyamy86/Q6XKv/
The main gist is this (see fiddle for full code):
// Adds the box and animates in/out
var addBox = function () {
var makeBox = function () {
var divsize = ((Math.random() * 100) + 50).toFixed();
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
var newBox = $('<div class="box" id="box' + boxIds + '"/>').css({
'width': divsize + 'px',
'height': divsize + 'px',
'background-color': color
});
return newBox;
};
var newBox = makeBox();
var boxSize = newBox.width();
var posx = (Math.random() * ($(document).width() - boxSize)).toFixed();
var posy = (Math.random() * ($(document).height() - boxSize)).toFixed();
newBox.css({
'position': 'absolute',
'left': posx + 'px',
'top': posy + 'px',
'display': 'none'
}).appendTo('body').fadeIn(ANIMATE_SPEED / 2, function () {
if (timer !== null) {
$(this)
.delay(ANIMATE_SPEED * MAX_BOXES)
.fadeTo(1, 1, function () {
if (timer !== null) {
var id = $(this).attr('id');
removeBox(id);
}
});
}
});
boxIdList.push(boxIds++);
lastBox = newBox;
numBoxes++;
return newBox;
};
// Add the boxes in at interval animateSpeed, if there's too many then don't add
var animateBox = function () {
if (numBoxes < MAX_BOXES) {
addBox();
} else {
removeBox(boxIdList[0]);
}
timer = setTimeout(animateBox, ANIMATE_SPEED); // re-set timer for the next interval
};
// starts everything off
var start = function () {
timer = setTimeout(animateBox, ANIMATE_SPEED);
};
This should be enough for you to work off of to add the level of detail you want for the interaction and effects.
I'm trying to make Divs to appear randomly anywhere on a webpage with javascript. So a div appears then disappears, then another div appears somewhere else on the page then disappears, then another div appears again in another random spot on the page then disappears, and so on.
I'm not sure on how to generate random units in pixels or what technique to use to generate random positions.
How do I do that? Here's my code:
var currentDivPosition = myDiv.offset(),
myDivWidth = myDiv.width(),
myDivHeight = myDiv.height(),
var myDiv = $('<div>'),
finalDivPositionTop, finalDivPositionLeft;
myDiv.attr({ id: 'myDivId', class: 'myDivClass' }); // already defined with position: absolute is CSS file.
// Set new position
finalDivPositionTop = currentDivPosition.top + Math.floor( Math.random() * 100 );
finalDivPositionLeft = currentDivPosition.left + Math.floor( Math.random() * 100 );
myDiv.css({ // Set div position
top: finalDivPositionTop,
left: finalDivPositionLeft
});
$('body').append(myDiv);
myDiv.text('My position is: ' + finalDivPositionTop + ', ' + finalDivPositionLeft);
myDiv.fadeIn(500);
setTimeout(function(){
myDiv.fadeOut(500);
myDiv.remove();
}, 3000);
Here's one way to do it. I'm randomly varying the size of the div within a fixed range, then setting the position so the object is always placed within the current window boundaries.
(function makeDiv(){
// vary size for fun
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
// make position sensitive to size and document's width
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100).delay(1000).fadeOut(500, function(){
$(this).remove();
makeDiv();
});
})();
Edit: For fun, added a random color.
Edit: Added .remove() so we don't pollute the page with old divs.
Example: http://jsfiddle.net/redler/QcUPk/8/
Let's say you have this HTML:
<div id="test">test div</div>
And this CSS:
#test {
position:absolute;
width:100px;
height:70px;
background-color:#d2fcd9;
}
Using jQuery, if you use this script, whenever you click the div, it will position itself randomly in the document:
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
The way this works is...first you calculate the document width and height, then you calculate the div width and height, and then you subtract the div width from the document width and the div height from the document height and consider that the pixel range you're willing to put the div in (so it doesn't overflow out of the document). If you have padding and border on the div, you'll need to account for those values too. Once you've figured out the range, you can easily multiple that by Math.random() and find the random position of your div.
So once more: first find the dimensions of the container, then find the dimensions of your element, then subtract element dimensions from container dimensions, and THEN use Math.random() on that value.
The basic idea is encapsulated here:
http://jsfiddle.net/5mvKE/
Some bugs:
You missed to position the div absolutely. Otherwise it will not
work.
I think you need to ad 'px' to the numbers.
The map is made of strings
Right in your jQuery css setup:
myDiv.css({
'position' : 'absolute',
'top' : finalDivPositionTop + 'px',
'left' : finalDivPositionLeft + 'px'
});
I changed an existant code by this one for our website, you can see it on tweefox.nc
<script>
function draw() {
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con.clearRect(0,0,WIDTH,HEIGHT);
for(var i = 0; i < pxs.length; i++) {
pxs[i].fade();
pxs[i].move();
pxs[i].draw();
}
}
function Circle() {
this.s = {ttl:8000, xmax:10, ymax:4, rmax:10, rt:1, xdef:950, ydef:425, xdrift:4, ydrift: 4, random:true, blink:true};
this.reset = function() {
this.x = (this.s.random ? WIDTH*Math.random() : this.s.xdef);
this.y = (this.s.random ? HEIGHT*Math.random() : this.s.ydef);
this.r = ((this.s.rmax-1)*Math.random()) + 1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
this.hl = (this.s.ttl/rint)*(this.r/this.s.rmax);
this.rt = Math.random()*this.hl;
this.s.rt = Math.random()+1;
this.stop = Math.random()*.2+.4;
this.s.xdrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
this.s.ydrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
}
this.fade = function() {
this.rt += this.s.rt;
}
this.draw = function() {
if(this.s.blink && (this.rt <= 0 || this.rt >= this.hl)) {
this.s.rt = this.s.rt*-1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
} else if(this.rt >= this.hl) this.reset();
var newo = 1-(this.rt/this.hl);
con.beginPath();
con.arc(this.x,this.y,this.r,0,Math.PI*2,true);
con.closePath();
var cr = this.r*newo;
g = con.createRadialGradient(this.x,this.y,0,this.x,this.y,(cr <= 0 ? 1 : cr));
g.addColorStop(0.0, 'rgba(255,255,255,'+newo+')');
g.addColorStop(this.stop, 'rgba(255,255,255,'+(newo*.2)+')');
g.addColorStop(1.0, 'rgba(255,255,255,0)');
con.fillStyle = g;
con.fill();
}
this.move = function() {
this.x += (this.rt/this.hl)*this.dx;
this.y += (this.rt/this.hl)*this.dy;
if(this.x > WIDTH || this.x < 0) this.dx *= -1;
if(this.y > HEIGHT || this.y < 0) this.dy *= -1;
}
this.getX = function() { return this.x; }
this.getY = function() { return this.y; }
}
$(document).ready(function(){
// if( /Android|AppleWebKit|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// } else {
if(document.getElementById('pixie')) {
WIDTH = $(window).width();
HEIGHT = $(window).height();
canvas = document.getElementById('pixie');
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con = canvas.getContext('2d');
pxs = new Array();
rint = 60;
for(var i = 0; i < 50; i++) {
pxs[i] = new Circle();
pxs[i].reset();
}
setInterval(draw,rint);
}
// }
});
</script>