I'm trying to make my menu items move to random positions without overlapping on top of each other. I'm using animate with top left and obviously for those to work I set the position property to absolute.
Now the problem with this approach is that they will go across on top of each other when I just want them to bounce off on each other.
Is there a way to accomplish this?
function Menu($item) {
this.item = $item;
};
Menu.prototype.makeNewPosition = function ($container) {
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
};
Menu.prototype.move = function () {
var that = this;
$.each(this.item, function(index, value) {
var newq = that.makeNewPosition($(value).parent());
$(value).animate({
top: newq[0],
left: newq[1]
}, 2000, function() {
that.move();
});
});
};
var $menu = new Menu($('.nav li'));
$menu.move();
JSfiddle
Related
I need some help here.
First off, here is a small demo code from my game: https://jsfiddle.net/MiloSx7/a0dn9a4f/2/
Animation idea: Make the coin scale to 2x after it's collected, then slowly move it and gradually reduce scale to the exact spot where the image displaying the coin inventory stat is , invLocation is the ID of the element where the animation should end. It starts from the current coinId X and Y
Is it possible to somehow get the X and Y of the invLocation, so that I know where should I tell the animation to move?
You can do this with JQuery position() and offset() methods.
const spawnTime = 10000;
var coin = 0;
var intervalId = '';
var coinDiv = $('#coinDiv');
var coinImg = $('#coinImg');
var invDiv = $('#invDiv');
var invId = $('#inventoryId');
var invImg = $('#invLocation');
coinImg.on('click', collect);
intervalId = setInterval(setLocation, spawnTime);
function setLocation() {
var x = parseInt( Math.random()*(80-20+1) ) + 20;
var y = parseInt( Math.random()*(80-20+1) ) + 20;
coinImg.animate({
opacity: 1
}, 3000,
function() {
coinImg.css('top', x+'%');
coinImg.css('left', y+'%');
coinImg.css('display', 'initial');
setTimeout( () => coinImg.animate({ opacity: 0 }, 3000), 6000);
});
}
function collect() {
clearInterval(intervalId);
coinImg.stop();
coinImg.css('opacity', 1);
/* Increment coin counter */
coin++;
invId.text(coin);
/* In order to disable multiple clicks */
coinImg.css('pointer-events', 'none');
/* Double the size */
coinImg.css('width', '128px');
coinImg.css('height', '128px');
/* Animate and return to normal */
coinImg.animate({
width: '32px',
height: '32px',
left: invImg.offset().left + 'px',
top: invImg.offset().top + 'px'
}, 1500,
function() {
coinImg.css('pointer-events', 'auto');
coinImg.css('display', 'none');
coinImg.css('width', '64px');
coinImg.css('height', '64px');
intervalId = setInterval(setLocation, spawnTime);
}
);
}
Working example: https://jsfiddle.net/wz4q9w69/
I'm creating a sample application where I need to change the color of a div as soon as user moves cursor away from it.
It's working but accurate, not sure where I'm going wrong.
See my sample application below.
http://jsfiddle.net/manishparab/3q1trzwk/
var cursorX = 0;
var cursorY = 0;
$(document).ready(function() {
$(".a").mouseover(function() {
animateDiv();
setInterval(function() {
isCursorOnSquare('.a')
}, 1);
});
});
$(document).on('mousemove', function(e) {
cursorX = e.pageX;
cursorY = e.pageY;
});
function isCursorOnSquare(elem) {
var pos, width, height;
pos = $(elem).position();
if ((Math.abs(pos.left - cursorX) <= 100 && Math.abs(pos.top - cursorY) <= 100)) {
$(elem).css("background-color", "red");
} else {
$(elem).css("background-color", "yellow");
}
}
function makeNewPosition() {
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
var speed = 2000;
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function() {
animateDiv();
});
}
In your code using .abs() the mouse event is also firing when the mouse is -100px to the left or top of the div.
You could also use mouseenter() to accomplish this,
$("div").mouseenter(function(){
$("div").css("background-color", "red");
}).mouseleave(function(){
$("div").css("background-color", "yellow");
});
Use 'mouseenter' and 'mouseout' events it will help.
$('#divID').on('mouseenter', function () {
//your code
});
$('#divID').on('mouseout', function () {
//your code
});
I have this javascript code that make the div randomly move around web page,but i am not understanding how to make it that it does not flow continuously,its like if user click then it move and then stops there and whenever it clicks again it moves to another random position and after 5 time it shows a message and disappears.I am not getting how to make this animation not like a flow but like a leaf falling from a tree.
here is the jsfiddle : JSFIDDLE
below is the javascript code :
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
I would use the CSS3 transitions, they hare hardware accelerated that mean smoother animations:
$(document).ready(function(){
var counter = 0;
$('.a').click( function () {
if ( ++counter < 5 ) {
var pos = makeNewPosition();
this.style.left = pos[1] +'px';
this.style.top = pos[0] +'px';
}
else if ( counter = 5 ) {
this.style.display = 'none';
alert( 'Your message' );
}
});
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
div.a {
width : 50px;
height: 50px;
background-color: red;
position: fixed;
left : 0px;
top : 0px;
-webkit-transition: left 2s, top 2s;
-moz-transition: left 2s, top 2s;
-o-transition: left 2s, top 2s;
transition: left 2s, top 2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='a'></div>
The animateDiv function calls itself at the end, so as soon as it reaches its destination it picks a new destination and goes there. Here it is with the recursive callback removed:
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed);
};
And an updated fiddle, which now requires clicking the box to animate it: http://jsfiddle.net/Xw29r/3975/
Something like this ?
var isStart = true;
$(".a").click(function () {
animateDiv(isStart);
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
if (isStart) {
$('.a').animate({
top: newq[0],
left: newq[1]
}, speed, function () {
animateDiv();
});
isStart = false;
} else {
$('.a').stop();
isStart = true;
}
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class='a'></div>
I'm trying to create a slider and one of its function is being able to be move to next and previous by mouse event.
It is already working but the problem is that when it reaches the end, it keeps scrolling. Here is my JSfiddle.
Any idea?
var sliding,
dir,
startClientX = 0,
prevClientX = 0,
$mainDiv = $('#main-div');
function move(dir, step) {
var $ul = $mainDiv.find('.slider'),
liWidth = $ul.find('div').width();
$ul.animate({
left: '+=' + (dir * liWidth)
}, 200);
}
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir, step);
});
Instead of writing custom javascript code, I would suggest going for using jQuery cycle2 plugin that will make your life easier.
http://jquery.malsup.com/cycle2/
Demo
You need to check if slider reached left or not;
var sliding,
dir,
startClientX = 0,
prevClientX = 0,
$mainDiv = $('#main-div');
function move(dir, step) {
var $ul = $mainDiv.find('.slider'),
liWidth = $ul.find('div').width();
var childCount = $(".slider div").length;
if (((childCount - 1) * liWidth + getLeftPos()) <= 0) {
return false;
}
$ul.animate({
left: '+=' + (dir * liWidth)
}, 200);
}
function getLeftPos() {
var childPos = $(".slider").offset();
var parentPos = $(".slider").parent().offset();
return (childPos.left - parentPos.left);
}
$mainDiv.mousedown(function (event) {
sliding = true;
startClientX = event.clientX;
return false;
}).mouseup(function (event) {
var step = event.clientX - startClientX,
dir = step > 0 ? 1 : -1;
step = Math.abs(step);
move(dir, step);
});
Hi i found this animation, which i would like to use to give my navigation links a tiny, gentle random movement, but it just doesn't look very smooth. http://jsfiddle.net/2TUFF/
(Random Movement in a Fixed Container)
$(document).ready(function() {
animateDiv();
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
$container = ($container || $(window))
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.a');
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
I've tried playing around with container size and speed but that doesn't help a lot, I also tried adding easing to the jquery myself but I have no knowledge of that mastery and failed.
Thanks!
I believe you need http://ijin.net/crSpline/demo.html for smooth "light breeze" animations.
Related answer: how to smooth jquery animations
Here is a full example in fiddle using jQuery.crSpline:
http://jsfiddle.net/2TUFF/295/