I have a simple game where I have an animated image flying around the screen that you click to score points. After about 5 seconds the image will fly off the screen. I just want to contain it to a div by whatever means necessary.
$(document).ready(function () {
$('#cursor').animate({
top: '500px'
, left: '500px'
});
$('img').click(function () {
var randomNumber = Math.random();
console.log(randomNumber);
$('#output').html(function (i, val) {
return val * 1 + 10
});
$(this).animate({
top: '+=' + ((Math.random() * 500) - 400) + 'px'
, left: '+=' + ((Math.random() * 500) - 400) + 'px'
})
})
function explode() {
alert("TIME UP!");
}
setTimeout(explode, 10000);
});
Is this solution just a css fix or does it need to be done in jquery?
1.
DonĀ“t use "+=" in your animate.
$(this).animate({
top: '+=' + ((Math.random() * 500) - 400) + 'px'
, left: '+=' + ((Math.random() * 500) - 400) + 'px'
})
2.
To contain it in the viewport consider the use of
window.innerHeight
and
window.innerWidth
3.
To contain it in a div you need to know the width and heigth of the div and consider that into your calculations (e.g. multiply the max with/height with a random number between 0 to 1 and subtract the image size from it)
Example to contain an image into the viewport
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
</head>
<body>
<img style="background: black; width: 15px; height: 15px; position: relative"></img>
<script>
$(document).ready(function () {
$('img').click(function () {
$(this).animate({
top: (Math.random() * window.innerHeight - this.height) + 'px'
, left: (Math.random() * window.innerWidth - this.width) + 'px'
})
})
})
</script>
</body>
</html>
You can easily adapt this to contain your image in your div.
Related
I have some code that shows one or two random images form a list and places it in a random position in a div. Sometimes the images appear outside the div. How can I contain the images to only show in boundaries of parent div?
Current code :
$('.draggable').each(function(i, el) {
var tLeft = Math.floor(Math.random() * 99) + 1 + '%',
tTop = Math.floor(Math.random() * 99) + 1 + '%';
$(el).css({
'left': tLeft,
'top': tTop
});
});
.draggable {
position: absolute;
}
.top-images {
position: relative;
width: 700px;
height: 80vh;
margin: 0 auto;
}
.top-images img {
width: 300px;
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-images">
<img class="draggable" src="http://serwer1858479.home.pl/autoinstalator/wordpress/wp-content/themes/cincio/img/main/main_page(9).jpg">
<img class="draggable" src="http://serwer1858479.home.pl/autoinstalator/wordpress/wp-content/themes/cincio/img/main/main_page(3).jpg">
</div>
in js get the width and height of each image...
get the width and height of parent..
place the image randomly between 0,0 to (parent_width-img_width+1),(parent_height-img_height+1)
Note:new to js so the exact code might differ slightly but the general cocept is accurate
replace this in the math function
var tLeft = Math.floor(Math.random() * ($(el).parent().width()-$(el).clientwidth+1)) + 'px',
tTop = Math.floor(Math.random() * ($(el).parent().height()-$(el).clientheight+1)) + 'px';
if the size is auto it might mess up the values
Edit 1: errors in the code
Since 300px (width of images) is 43% of 700 (width of the div that images appear in)
you need to limit tleft to 57 (100-43). But tTop is a bit different since you used pixels for it. Try this :
var maxTop = $('.top-images').first().height() - $(this).height(),
tLeft = Math.floor(Math.random() * 57) + 1 + '%',
tTop = Math.floor(Math.random() * maxTop) + 'px';
I'm new to coding and trying to make a game were I move my div along the x and y axis. When I run code I get an error in the marginLeft variable as well as the marginTop. I included these variables because I want successive keydown strokes to continue to move div. I would like to code using only jquery if possible.
var player = $('#player');
var marginleft = $('#player').offset().left;
var margintop = $('#player').offset().top;
function movePlayer(e) {
if (e.keydown==39) {
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.keydown==37) {
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.keydown==40) {
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.keydown==38) {
margintop -=2;
player.css('top', margintop + 'px');
}
}
#player {
width: 50px;
height: 50px;
background-color: red;
left: 0px;
top: 0px;
position: absolute;
}
body {
height: 100%;
width: 100%;
background-color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="player"></div>
</body>
</html>
Your code worked fine when I modified it to use e.which in the event listeners. I also attached the event listener in the bottom of the snippit.
Click inside the game before using the arrow keys: https://jsfiddle.net/CoryDanielson/kchrv4t4/
var player = $('#player');
var marginleft = $('#player').offset().left;
var margintop = $('#player').offset().top;
function movePlayer(e) {
if (e.which==39) {
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.which==37) {
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.which==40) {
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.which==38) {
margintop -=2;
player.css('top', margintop + 'px');
}
}
$(document.body).on('keydown', movePlayer);
You should use e.which when using jQuery. There's a lot of discrepancies between browsers and key codes. which is the safe way to determine keycodes. https://api.jquery.com/event.which/
When I run code I get an error in the marginLeft variable as well as the marginTop
This phare let me think you are defining and initializing the variables outside the document ready...
If you need to move your div only inside visible document area a solutioon can be:
//
// declare global variables and functions outside the
// document ready
//
var player;
var marginleft;
var margintop;
var docWidth;
var docHeight;
function movePlayer(e) {
if (e.which==39) {
if (marginleft >= docWidth) {
return;
}
marginleft +=2;
player.css('left', marginleft + 'px');
}
if (e.v==37) {
if (marginleft<=0) {
return;
}
marginleft -=2;
player.css('left', marginleft + 'px');
}
if (e.which==40) {
if (margintop >= docHeight) {
return;
}
margintop +=2;
player.css('top', margintop + 'px');
}
if (e.which==38) {
if (margintop<=0) {
return;
}
margintop -=2;
player.css('top', margintop + 'px');
}
}
//
// On document ready: set the variables and
// add the event listener for keydown event
//
$(function () {
player = $('#player');
marginleft = $('#player').offset().left;
margintop = $('#player').offset().top;
docWidth = $(document).width() - player.width();
docHeight = $(document).height() - player.height();
$(document).on('keydown', function(e) {
movePlayer(e);
});
});
#player {
width: 50px;
height: 50px;
background-color: red;
left: 0px;
top: 0px;
position: absolute;
}
body {
height: 100%;
width: 100%;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="player"></div>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I tried to find a code that makes a div escaping from the cursor randomly but I couldn't find any. Maybe I don't know how to search, maybe it's so easy but my English is not good enough to solve that situation.
I want a div which escapes from cursor randomly in a parent div, can you help me?
Thanks a lot!
Randomized but also animated :
$("#move").mouseenter(function () {
$(this).animate({
top: Math.random() * 300
}, 100);
$(this).animate({
left: Math.random() * 300
}, 100);
});
JSFiddle demo
Cheers :D
Hope it will help:
HTML
<div id="runner">
</div>
CSS
#runner {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
left: 100px;
top: 100px;
}
JS
$("#runner").on('mouseover', function(){
var offset = $(this).offset();
var goX = Math.random() < 0.5 ? -1 : 1;
var goY = Math.random() < 0.5 ? -1 : 1;
$(this).css('top', offset.top + 20 * goY);
$(this).css('left', offset.left + 20 * goX);
});
https://jsfiddle.net/3hLp6myj/
HTML
<div class="touchMeNot"></div>
jQuery
$('.touchMeNot').on('mouseenter',function(e){
var maxX = $(window).width() - $(this).width();
var maxY = $(window).height() - $(this).height();
$(this).css({
'left':getRandomInt(0, maxX),
'top':getRandomInt(0, maxY)
});
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
CSS
.touchMeNot{
position:absolute;
border: 1px solid red;
height:50px;
width:50px;
}
Here is the fiddle.
Update
This is done in order to avoid the box going out of the window.
var maxX = $(window).width() - $(this).width();
var maxY = $(window).height() - $(this).height();
We can generalize by using the div width in the function itself.
We've done this as a joke not too long ago, it's quite simple:
$('button').hover(function() {
$(this).text("Can't touch this!");
$(this).css('top', Math.random()*500 + 'px').css('left', Math.random()*600 + 'px');
});
Fiddle example
This has been answered in another question, here is the example that was created http://jsfiddle.net/karalamalar/atNva/ . I believe this is what you was after correct?
jQuery(function($) {
$('#img').mouseover(function() {
var dWidth = $(document).width() - 100, // 100 = image width
dHeight = $(document).height() - 100, // 100 = image height
nextX = Math.floor(Math.random() * dWidth),
nextY = Math.floor(Math.random() * dHeight);
$(this).animate({ left: nextX + 'px', top: nextY + 'px' });
});
});
Here is the other question: Need to animate an image to move away from cursor postion on each mouseover?
Hope this helps.
I'm looking for an effect very similar to this:
http://jsfiddle.net/G5Xrz/
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
But i'd prefer a flexible layout, ie images not bound by a div with predefined height and width, instead responding to the dimensions of the browser.
The following piece of code seems to have a more appropriate way of generating the random positions:
http://jsfiddle.net/Xw29r/15/
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();
});
};
However I'm very much a beginner with javascript and I don't know how to combine the two.
Can anyone help?
Thanks
Take this part from the second code:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
and use those variables h and w with the browser height and width (minus 50) as the appropriate parameters in this part of the first code:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
Also, the first code has this HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
That hard-codes the height and width at pixel values. You can use a CSS percentage value to make the width respond to the parent container's size. However, you will need JS to set the height properly; a percentage for the height does nothing
Putting that all together (and removing the "minus 50" part), you get this:
jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
This updates the height of the container when the page is first loaded, and once again whenever the random image is placed. More robust code would have a separate height-adjusting event handler that updates the height whenever the page size changes.
I have just currently started learning jQuery and I seem to be able to get it work how I want but I feel that the way that I am writting it is not very efficient. Could anyone assist me in this example below:
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
$(window).resize(function() {
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
});
So here I am positioning a div in the center of the screen. And then it also does it again on window resize as its contents width properties are percentage values. It works perfectly but I can't help but feel that there must be a better way to write this. Any help would be greatly appreciated. Thank you
You can cache the object and trigger the resize event, this way the resize handler is executed on DOM Ready.
$(window).resize(function() {
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
}).resize()
var $tilesWrapper = $('.tiles-wrapper');
function setWrapperStyle () {
var halfWidth = $tilesWrapper.width() * 0.5;
var halfHeight = $tilesWrapper.height() * 0.5;
$tilesWrapper.css({
top: '50%',
left: '50%',
margin: '-' + halfHeight + 'px 0 0 -' + halfWidth + 'px'
});
}
setWrapperStyle();
$(window).on('resize', setWrapperStyle);
You should make a fonction with your first line :
function center(){
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
}
and then you call it a first time and you call it when you resize your window:
center();
$(window).resize(center);
Do you really need jquery here ?
You can use directly css
.tiles-wrapper{
top:50% ;
left:50% ;
width: //what u given
height: //what u given
margin-left: //tiles width/2
margin-right: //tiles height/2
position: //absolute or float
}
if you want to calculate height and width dynamically
just write this on document ready
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
In re-size it will automatically on center position.