I am trying to get the ball element to both move and shrink towards the goals on mouse click.
I have created a function that grabs the coordinates of the mouse click in the goals, however I have been struggling with the ball animation.
I thought about using keyframes, but I don't know how to use keyframes in JavaScript.
I also tried doing a transform - which I know wouldn't work, but tried as you can see in the move() function.
This is my javascript/html file
function goal(){
var score = getScore();
increaseDifficulty(score)
document.getElementById("score").innerHTML = score + 1 ;
var b = getShotCordinates();
move(b[0],b[1]);
}
function save(){
resetScore();
}
function resetScore(){
document.getElementById("score").innerHTML = 0;
}
function getScore(){
return parseInt(document.getElementById("score").innerHTML);
}
function move(x,y){
const fxMove = `translate(${x}px, ${y}px);`;
const fxAnim = `transition: transform 0.5s; transform: translate(0, 0);`;
document.getElementById("ball").style.transform = translate(x,y);
}
function getShotCordinates(){
var e = window.event;
var Cordinates = [e.clientX, e.clientY];
console.log(Cordinates[0] + " - " + Cordinates[1])
return Cordinates;
}
<BODY>
<div id="canvas" class="field">
<div id="goals" class="goals" onclick="goal()">
</div>
<div id="goalkeeper" onclick="save()">
</div>
<div id="kick-off">
<div id="ball" class="ball">
</div>
</div>
<div id="score-container">
<div id="counter">
<h1 class="counter-text">Score</h1>
<h1 class="counter-score" id="score">0</h1>
</div>
</div>
</div>
<script src='js/script.js'></script>
</BODY>
Just in case, this is my canvas/UI
If you are looking for something like this:
const div = document.querySelector("div");
document.addEventListener("click", (e)=>{
console.log(e)
div.style.top = e.clientY + "px";
div.style.left = e.clientX + "px";
})
div{
width:50px;
height:50px;
background:red;
border-radius:50%;
position:absolute;
transition:.3s;
transform:translate(-50%, -50%);
}
<div></div>
Just give the ball position absolute, and on every click event change the top and the left of the ball with javascript.
Related
I am trying to move a image in a div like a facebook cover page, but it is not moving smoothly with image tag . when I put this image in a div like a background image it is working
my js code is ..
var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
var ele = document.getElementById('ele');
var width = 400-ele.clientWidth;
var height = 400-ele.clientHeight;
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
});
}
function init() {
var ele = document.getElementById('ele');
draggable(ele);
}
and my html code which is not working is..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<img src="Desert.jpg" id="ele" style="position:absolute;"></img>
</div>
</body>
and this code is working..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<div id="ele" style="width:100%; height:100%; background-color: gray; position:absolute; background-image:url( 'Desert.jpg' );"></div>
</div>
</body>
You could refer to this question, which handles the same idea of dragging images, althought the question is slightly different. Check out his/her JSFiddle from question.
Check it out here!
<img> is a self-closing tag. You don't need the </img> as it's not valid. Remove that and it should work fine. Depending on your doctype you should use:
HTML5
<img src="Desert.jpg" id="ele" style="position:absolute;">
XHTML (note the / at the end of the tag)
<img src="Desert.jpg" id="ele" style="position:absolute;" />
<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/
I wrote below code to get co-ordinate of x/y in JAVASCRIPT , it's not working .
I want to create a color picker using this image
when ever some one click on button pick color then it prompts a window with color and button cancel , When user clicked on image than i need to find x/y co-ordinate so that i can specify which color it is .
Problem is that these alerts are not working
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display:none;
position: fixed;
background: #f2f2f2;
border-radius:5px;
z-index: 10;
}
#dialogboxhead{background:white;height:40px;margin:10px;}
#text {float:left; text-align:center;margin:10px; font-size:19px;}
#cancel{float:left;margin:9px;}
#image{
margin-top:0px;
padding:10px;
}
</style>
<script type="text/javascript">
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function position(e){
var offsetl = document.getElementById('image').offsetLeft;
var offsett = document.getElementById('image').offsetTop;
alert(offsetl);
alert(offsett);
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
}
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead">
<p id="text">Select color</p>
<input type="button" onClick="Alert.cancel()" id="cancel" name="Cancel" value="Cancel"/>
</div>
<div>
<img id="image" src="color.png" onClick="position()"/>
</div>
</div>
<button onclick="Alert.render('Hello World');" >pick color </button>
</body>
</html>
I recommend use jQuery and attach click event handler in you image. The event object return in jQuery include two properties, pageX and pageY. This properties contains mouse position relative to the top edge of the document (jQuery Event Object). The code look like this:
$(document).ready(function () {
$('img#image').click(position);
});
function position(e) {
var offsetX = e.pageX,
offsetY = e.page;
}
The sample is in JSFiddle http://jsfiddle.net/zV3dH/.
I hope this help you.
Try this code buddy.. Sure it works
function getClickPos(e) {
return {x:e.clientX,y:e.clientY};
}
Now u can use it like this:
document.querySelector("#img").onclick = function(e) {
var pos= getClickPos(e);
alert(pos.x);
};
I have this simple JavaScript code that is supposed to side a div in and a div out. it is working perfectly when it comes to sliding in. By working perfectly is sliding the div easily. However when you click slideout the div just disappears from the browser. I don't know why and I cant find a fault. My code is here
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function slideIt()
{
var stopPosition = 50;
var slidingDiv = "";
slidingDiv = document.getElementById("d3");
if (parseInt(slidingDiv.style.left) < stopPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
setTimeout(slideIt, 1);
}
}
function slideOut()
{
var startPosition =-150;
var slidingDiv = "";
slidingDiv = document.getElementById("d4");
if (parseInt(slidingDiv.style.left) > startPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) - 2 + "px";
setTimeout(slideOut(), 1);
}
}
</script>
<div id="d1" onclick="slideIt();">Slide in</div>
<div id="d2" onclick="slideOut();">Slide out</div>
<div id="d3" style="position: absolute; left:-150px; top:300px" >horizontally sliding div</div>
<div id="d4" style="position: absolute; left:150px; top:300px">horizontally sliding div</div>
</body>
</html>
You don't need to invoke slideOut in the second timeout. Remove the parentheses.
setTimeout(slideOut, 1);
Here is a demonstration: http://jsfiddle.net/cctqf/
I am using the following coding
<html>
<head>
<style>
#thediv {
margin:0 auto;
height:400px;
width:400px;
overflow:hidden;
}
img {
position: relative;
left: 50%;
top: 50%;
}
</style>
</head>
<body>
<input type="button" value ="-" onclick="zoom(0.9)"/>
<input type="button" value ="+" onclick="zoom(1.1)"/>
<div id="thediv">
<img id="pic" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Nokota_Horses_cropped.jpg"/>
</div>
<script>
window.onload = function(){
zoom(1)
}
function zoom(zm) {
img=document.getElementById("pic")
wid=img.width
ht=img.height
img.style.width=(wid*zm)+"px"
img.style.height=(ht*zm)+"px"
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
</script>
</body>
</html>
For making a simple zoom in and zoom out function.
I this i have a difficulty of the image is zooming indefinitely. i want to fix a position to zoom in and zoom out. The image must not exceed that position while zooming in and zooming out.
I am adding a fiddle to this link
Here you go:
var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
You can modify the zoom levels to whatever you want.
I modified the fiddle a bit, since you only need to add javascript to the bottom-left area.