Moving Div within window using arrows - javascript

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>

Related

jQuery make image popup in random position not working

I want to make an image randomly show up every 2 sec using jQuery. But the image always shows in a static position (top-left). I console.logged the attribute of the image and its left and top shows random px.
let score = 0;
let id = 0;
$(document).ready(function () {
setInterval(setImage, 2000);
});
function setImage() {
$("#container").append(
`<img src='images/virus.gif' id='${id}' width='75px' position='absolute' class='virus' left=${randomLeft()} top=${randomTop()}/>`
);
$("#" + id)
.slideUp(0)
.fadeIn(1000);
id++;
$("#" + id).on("click", function (event) {
$(event.target).remove();
score++;
console.log($(event.target).attr("id"), score);
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
You need to use style rather than left/top attributes
style="left:10px;right:10px"
Couple of other tweaks to your snippet:
include jquery (option on the left of snippet editor adds <script> to the html)
needs a #container to put them in, I made this position:relative so the position:absolute will work
removed the need for the $("#"+id) re-finding by chaining the append
put the i++ at the beginning so that you don't try to attach click to something that doesn't exist yet (but doesn't matter as not used for re-finding new element)
$(this).remove() must come after $(this).attr("id") - you were removing it before getting its ID
used this inside the click handler rather than event.target
would be better as data-id=${++id} rather than using a numerical id, but that's a small change (not made)
Updated snippet:
let score = 0;
let id = 0;
$(document).ready(function() {
setInterval(setImage, 2000);
});
function setImage() {
var img = $(`<img src='images/img4.jpg' id='${++id}' class='virus' style='left:${randomLeft()};top:${randomTop()}' />`);
img.appendTo("#container")
.slideUp(0)
.fadeIn(1000)
.on("click", function() {
score++;
console.log($(this).attr("id"), score);
$(this).remove();
});
}
function randomTop() {
let height = $(window).height();
let randomHeight = Math.floor(Math.random() * (height - 75)) + "px";
return randomHeight;
}
function randomLeft() {
let width = $(window).width();
let randomLeft = Math.floor(Math.random() * (width - 75)) + "px";
return randomLeft;
}
#container {
position: relative;
height: 100%;
width: 100%;
}
.virus {
border: 1px solid red;
position: absolute;
width: 75px;
height: 20px;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>

jQuery mouseover animation with alert

My question is - Writing a page containing a small square,every time user brings the cursor close to the box, the box must move away from the mouse pointer. Finally when the box reaches the corner of the page, it should display a message.
So far, I have animated the box from INITIAL to last position on the screen. How to revert it back to original position, with an alert message??
$(document).ready(function() {
var x = $(window).width();
var y = $("#div2").width();
$("#div2").mouseover(function(){
for (var i = y ; i <= x ; i++) {
$("#div2").animate({
left: 100 + "px"
});
}
});
});
#div2 {
top: 100px;
/*left: 100px;*/
height: 100px;
width: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" style="position: relative;"></div><br>
$(document).ready(function() {
var x = $(window).width();
var y = $("#div2").width();
var left = 0;
$("#div2").mouseover(function(){
left+= 100;
if(left <= x ){
$("#div2").animate({
left: left + "px"
});
} else {
alert('Back to original');
$(this).css('left', '0');
left=0; //this should be their else it will alert many times...
}
});
});
#div2 {
top: 100px;
/*left: 100px;*/
height: 100px;
width: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" style="position: relative;"></div><br>
i i=529(window width=531) for quick out put initialize i=y then if it reaches end it will be moved to left:opx
you said you already made it to move to last and your mistake is you didn't assign i in left.
$(document).ready(function() {
var x = $(window).width();
var y = $("#div2").width();
$("#div2").mouseover(function(){
for (var i = 529 ; i <= x ; i++) {
$("#div2").animate({
left: i+"px"
});
}
alert("reached");
$("#div2").animate({
left: "0px"
});
});
});
#div2 {
top: 100px;
/*left: 100px;*/
height: 100px;
width: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" style="position: relative;"></div><br>
Is this what you wanted?
$(document).ready(function() {
var x = $(window).width();
var y = $("#div2").width();
var left = 0;
$("#div2").mouseover(function(){
left+= 100;
if(left <= x ){
$("#div2").animate({
left: left + "px"
});
} else {
alert('Back to original');
$(this).css('left', '0');
left = 0;
}
});
});
#div2 {
top: 100px;
/*left: 100px;*/
height: 100px;
width: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" style="position: relative;"></div><br>
First of all you don't need a loop to animate element to relative position, just use '+=100px' notation. You could also calculate element's next position to prevent if from overflow the window. Check this snippet.
$(document).ready(function() {
var vw = $(window).width();
var $el = $('#div2');
var width = $el.width();
var direction = 1;
var defaultAmount = 100; // Default travel distance
var amount = defaultAmount;
$el.mouseover(function() {
var changeDir = false;
// Check if element will be out of range
if (isOutOfRange() && direction === 1) {
alert('Will be at the end, will reverse')
amount = vw - $el.offset().left - width;
changeDir = true;
}
if (isAtBeginning() && direction === -1) {
alert('Will be at the beginning, will reverse')
amount = $el.offset().left;
changeDir = true;
}
$el.animate({
left: direction === 1 ? '+=' + amount + 'px' : '-='+ amount + 'px'
});
// Change direction to opposite if ellement is at the edge
if (changeDir) direction = direction * -1;
// Return to default
amount = defaultAmount;
});
function isOutOfRange() {
return width + amount + $el.offset().left >= vw;
}
function isAtBeginning(){
return $el.offset().left - amount <= 0;
}
});
#div2 {
top: 100px;
/*left: 100px;*/
height: 100px;
width: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div2" style="position: relative;"></div><br>
Final Solution
$(document).ready(function() {
var direction=1;
var x = $(window).width();
var y = $("#div2").width();
var left = 0;
$("#div2").mouseover(function(){
if(left + y <= x )
{
left = left + direction*100;
$("#div2").animate({
left: left + "px"
});
}
else
{
alert("Moving Back!");
direction = -1;
left = left + direction*100;
$("#div2").animate({
left: left + "px"
});
}
if(left <= 0)
{
direction = 1;
left = left + direction*100;
alert("Moving Forward!!");
$("#div2").animate({
left: left + "px"
});
}
//$(this).css("left", "0");
});
});

Does computed style give the calculated value which might be different from the actual value?

I was trying
var oldleft = mydiv.style.left;
mydiv.style.left = "-100%";
newleft = parseInt(window.getComputedStyle(mydiv,null).getPropertyValue("left"));
and the jquery version:
var oldleft = mydiv.style.left;
mydiv.style.left = "-100%";
newleft = parseInt($(mydiv).css("left"));
on a div. The mydiv also uses css3 animations. I thought newleft would get the pixel value of left property after the div had moved to -100%. What I observed was that newleft had the same value as that of oldleft. So,
Does computed style give the calculated value which might be different from the actual inline style value?
I want the value of left property of mydiv in pixels after it would have moved to -100%. How do I get this?
EDIT: I am posting the minimalistic sample replicating the issue
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.panel-group {
width: 200px;
height: 200px;
background-color: gray;
position: absolute;
top: 0;
left: 0;
transition: all 0.5s linear;
}
</style>
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="panel-group">
Hello
</div>
<script type="text/javascript">
var center = document.getElementsByClassName("panel-group")[0];
var initialleft = parseInt($(".panel-group").css("left"));
center.style.left = initialleft;
var intpos, increment = 0, lastpos, direction, oldx = 0;
lastpos = initialleft;
var pressed = 0;
center.addEventListener("touchend", function(){
pressed = 0;
if( parseInt(increment) > 100 ) {
center.style.left = (screen.width - 10) + "px";
lastpos = parseInt(center.style.left);
}
else if( (parseInt(increment) < -100) ) {
center.style.left = initialleft + "px";
lastpos = parseInt(center.style.left);
}
else{
center.style.left = lastpos + "px";
}
});
center.addEventListener("touchstart", function(down) {
intpos = down.touches[0].screenX;
pressed = 1;
});
center.addEventListener( "touchmove", function(Dmove) {
if(pressed == 1) {
increment = (Dmove.touches[0].screenX - intpos);
center.style.left = (lastpos + increment) + "px";
}
/*
if (Dmove.pageX < oldx) {
direction = "left";
} else if (Dmove.pageX > oldx) {
direction = "right";
}
oldx = Dmove.pageX;
*/
});
$(window).on("orientationchange",function(){
alert("screen is" + screen.width);
center.style.left = "0px";
initialleft = parseInt(window.getComputedStyle(center,null).getPropertyValue("left"));
lastpos = initialleft;
alert(lastpos);
});
/* Swiping menu finishes here */
</script>
</body>
</html>
Open the above code as a html file in google chrome. Then use mobile landscape mode in developer tools. Click the gray box and slide it to right. Now change from landscape mode to potrait mode. AS per the following snippet
$(window).on("orientationchange",function(){
alert("screen is" + screen.width);
center.style.left = "0px";
initialleft = parseInt(window.getComputedStyle(center,null).getPropertyValue("left"));
lastpos = initialleft;
alert(lastpos);
});
initialleft should be 0 but it is not. You can check the value of initialleft in the console window.

Change Div Width Along on load and resize

I wrote this code to change width and height of the wrapper box based on the available space on the screen. When I open the page, div loads well but when I resize it the size of the div does not change.
var width = (($(window).width()) - 100);
var height = (($(window).height()) - 100);
$(window).ready(function() {
$("#wrapper").width(width);
$("#wrapper").height(height);
});
$(window).resize(function(){
$("#wrapper").width(width);
$("#wrapper").height(height);
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Xyz</title>
</head>
<body>
<div id="wrapper">
asd
</div>
</body>
</html>
You need to recalculate the height and width variables within the event handlers:
$(window).ready(calculateSize);
$(window).resize(calculateSize);
function calculateSize() {
var width = $(window).width() - 100;
var height = $(window).height() - 100;
$("#wrapper").width(width);
$("#wrapper").height(height);
}
Note however, that this is possible in CSS alone:
#wrapper {
position: absolute;
top: 0;
left: 0;
right: 100px;
bottom: 100px;
}
You need to recalculate the dimension.
$( window ).resize(function(){
width = (($(window).width())-100);
height = (($(window).height())-100);
$("#wrapper").width( width );
$("#wrapper").height( height );
});
I use this function I wrote and it is working well:
//when I load the page
window.onload = function(event) { resizeDiv(); }
//when I resize the page
window.onresize = function(event) { resizeDiv(); }
function resizeDiv() {
vpw = $(window).width()-100;
vph = $(window).height()-100;
$('#wrapper').css({'height': vph + 'px'});
$('#wrapper').css({'width': vpw + 'px'});
}

Display text when mousemove active

I want to display true in a paragraph when mousemove is active and false when it is not active. tried an if statement but didn't work
$(document).ready(function() {
var Clickcount = 1;
$(".chimp").mousemove(function(e) {
if (Clickcount % 2) {
$('.chimp').css({
'top': e.clientY - 20,
'left': e.clientX - 20
});
}
});
$("body").mousemove(function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$(".cords").html("clientX " + x + " clientY= " + y);
});
$(document.body).on('click', function() {
Clickcount++;
});
});
I'm not quite sure what you mean with mousemove is active. If you want to check if the mouse is insida a specific element or not you can use something like this:
$(".chimp").hover(function () {
$("#bool").text('true');
},function () {
$("#bool").text('false');
});
Demo
But if you want to detect if the mouse has stopped moving, you can try it with this code-snippet:
var timeout;
$(".chimp").mousemove(function () {
$("#bool").text('true');
clearTimeout(timeout);
timeout = setTimeout(function() {
$("#bool").text('false');
}, 1000);
});
This will trigger if the mouse is not moved for 1 second. You can adjust the treshold for that easily, just edit the number in the timeout-function.
Demo
Use "html" instead of "body"
$("html").mousemove(function(e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
$(".cords").html("clientX " + x + " clientY= " + y);
});
.cords {
width: 20em;
height: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cords"></div>
here you go
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drag Me</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
#dragg
{
position: absolute;
background-color: red;
height: 200px;
width: 200px;
}
p{
position: relative;
top: 210px;
right: 5px;
}
</style>
</head>
<body>
<div id="dragg">
red
</div>
<p id="bool"></p>
<script>
$(document).ready(function () {
$('#dragg').on({
mousedown: function (e) {
$(window).data({
down:true,
oX: e.offsetX,
oY: e.offsetY,
el:this
})
},
mouseup: function (e) {
$(window).data('down',false)
},
})
$(window).on({
mousemove: function (e) {
var data=$(window).data()
if (data.down) {
$("#bool").text('true');
$(data.el).css({
left: e.clientX - data.oX,
top: e.clientY - data.oY
});
}
else{
$("#bool").text('false');
}
},
})
});
</script>
</body>
</html>

Categories