I am trying to move an image so that it is centered around the position that the user clicked, both vertically and horizontally, using JavaScript. How would this be accomplished?
I have tried the following code, but it aligns the top left corner of the image to the position that was clicked, which is not what I want.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x + 'px';
cat.style.top = y + 'px';
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png" />
</div>
Simply subtract half the image's width from the x-coordinate and half the height from the y-coordinate to center the image around the clicked position.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = '';
cat.style.position = 'absolute';
cat.style.left = x - cat.width / 2 + 'px';
cat.style.top = y - cat.height / 2 + 'px';
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png"/>
</div>
You can take the width and height of the image and divide them by two, then subtract the x by the width divided by two and subtract the y by the height divided by two. This'll give you the center of the image.
document.onclick = userClicked;
function userClicked() {
var x = event.clientX;
var y = event.clientY;
var cat = document.getElementById("catAppear");
cat.style.display = "block";
cat.style.left = x - (cat.width/2) + 'px';
cat.style.top = y - (cat.height/2) + 'px';
};
#catAppear {
position: absolute;
}
<div class="container">
<img alt="catAppear" id="catAppear" style="display: none" src="https://www.coopmcs.com/dotclear/public/chat.png" />
</div>
Related
I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.
Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.
WORKFLOW
The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.
CODE
HTML post item:
<article class="col-md-4 col-sm-6 post-entry">
<a href="#" title="">
<figure class="post-thumb">
<img src="http://placehold.it/300x300" alt="">
<div class="pointer" style="background: red;"></div>
</figure><!-- End figure.post-thumb -->
</a>
</article><!-- End article.col-md-4 post-entry -->
JS:
$('.entry .post-entry').each(function() {
$(this).on("mouseenter", mouseEnter);
$(this).on("mousemove", mouseMove);
$(this).on("mouseleave", mouseLeave);
});
function mouseEnter(event) {
console.log('enter');
var target = $(this);
var dot = target.find('.pointer');
var mX = (event.clientX);
var mY = (event.clientY);
set(
dot, {
x: mX,
y: mY,
force3D: !0
}
);
};
function mouseMove(event) {
console.log('move');
var target = $(this);
var dot = target.find('.pointer');
// var offset = target.offset();
// var width = target.width();
// var height = target.height();
// var top = offset.top;
// var left = offset.left;
var mX = (event.clientX);
var mY = (event.clientY);
$(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');
};
function mouseLeave(event) {
console.log('leave');
var target = $(this);
var dot = target.find('.pointer');
$(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');
};
function onClick(event) {
event.preventDefault();
console.log('click');
};
function set(el, obj) {
var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
return dot;
};
PROBLEM / DEMO
As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here
I tried already something like this for the mX and mY variables, but with no succes:
var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();
Also the answer from #hiEven doesn't work and will let me with the same issue:
transform: calc(mX - 50%, mY - 50%)
I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.
UPDATE
I created two new Codepen projects:
Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.
When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.
Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.
Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.
So I don't know what's missing and why it only works with the first example (without images) and only for the first item?
Try the code below
<html>
<head>
<style>
#mouse_div{
position: absolute;
background-color: black;
}
</style>
<script>
var div_width = 100;
var div_height = 100;
var div_x, div_y;
function mouse_position(event){
var mouse_x = event.clientX;
var mouse_y = event.clientY;
document.getElementById("mouse_div").style.width = div_width + "px";
document.getElementById("mouse_div").style.height = div_height + "px";
div_x = mouse_x - (div_width / 2);
div_y = mouse_y - (div_height / 2);
document.getElementById("mouse_div").style.left = div_x + "px";
document.getElementById("mouse_div").style.top = div_y + "px";
}
</script>
</head>
<body onmousemove="mouse_position(event)" onload="mouse_position(event)">
<div id="mouse_div"></div>
</body>
</html>
This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.
Note: you must make sure that the position of the div is set to absolute or the program will not work.
I assume you want the circle being center of your mouse, right?
try do this
transform: `translate(calc(${mx}px - 50%), calc(${my}px - 50%))
here is the demo
Based on my latest update, I did not conform to the correct formula that is needed to center the element .pointer to the mouse.
In order to use the following calculation within mouseMove:
var mX = (event.clientX);
var mY = (event.clientY);
Should be changed to this:
var height = dot.height();
var width = dot.width();
var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;
var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;
So this formule is considering that the following DOM element .pointer will follow the mouse movements of the user. I don't know exactly why this working, but the offset from the previous item will be decreased from the current clientX coordinates, so the position of the second item is reset to zero, so the pointer will start at the left side of each item.
Here is a working demo of above code: http://codepen.io/anon/pen/AXdxZO?editors=0110
I have a script that moves an image slightly to the left or right when the user moves their mouse. The problem is this image is always in the top left of my window when I need it to always stay in the center.
<html>
<head>
</head>
<body>
<img id="logo" src="logoHeader.png" style="position:absolute;" />
</body>
<script lang="javascript">
function updateLogoPosition( e )
{
var logo = document.getElementById("logo");
var m = e.x / 12;
logo.style.left = m + "px";
}
document.onmousemove = updateLogoPosition;
</script>
</html>
You would have to do some more calculation to do this.
You need to know the width and height of the viewport to find the middle. Then you need to normalise the mouse position so that you calculate the offset from the centre line not from the top left as you e.x was doing.
Something like this should do it, where "modifier" will allow you to change the violence of the offset.
<html>
<head>
</head>
<body>
<img id="logo" src="http://placehold.it/150x150" style="position:absolute;" />
<script>
window.onload = setInitialLogoPosition;
document.onmousemove = updateLogoPosition;
function setInitialLogoPosition(){
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
logo.style.left = leftOffset;
logo.style.top = topOffset;
}
function updateLogoPosition( e ){
// Get height and width of body
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
// Get height and width of logo
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
/* Normalise the mouse so that 0 is the centre
with negative values to the left and positive to the right */
var x = (e.x / bodyWidth * 100) - 50;
var y = (e.y / bodyHeight * 100) - 50;
// Calculate the position of the logo without mouse manipulation
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
// Set violence of offset
var modifier = 0.5;
// Add the mouse offset to the central position
leftOffset += (x * modifier);
topOffset += (y * modifier);
// Apply the calculated position to the logo
logo.style.left = leftOffset + "px";
logo.style.top = topOffset + "px";
}
</script>
</body>
</html>
To center horizontally you can do it with CSS:
<img id="logo" src="logoHeader.png" style="position:relative; text-algin:center; display: block; margin: 0 auto;" />
jsFiddle
Trying to capture the position of click on an image (marked as x for end users). But on window resize the 'X' position changes. Is something I am missing in my code, how can i maintain the position in portrait and landscape modes
<script>
$("#_img").on("click",function(event){
var X = event.pageX-5, Y = event.pageY-5;
$("#marker").css({
"left":X,
"right":Y
}).show();
});
</script>
<img id="_img" src="car.png" width="550px" height="168px"/>
<div id="_mrk" style="display:none;">x</div>
You have to update position of 'x' everytime window resized or orientation changed and image should be in perentage instead of pixels
var width = 0;
var height = 0;
$("#_img").on("click", function(event) {
var X = event.pageX,
Y = event.pageY;
$("#_mrk").css({
"left": X,
"top": Y
}).show();
width = $("#_img").width();
height = $("#_img").height();
});
function getNewValue(posValue, oldImgPos, newImgPos) {
return posValue * (newImgPos / oldImgPos);
}
$(window).resize(function() {
var newx = getNewValue($('#_mrk').offset().left, width, $("#_img").width());
$("#_mrk").css("left", newx);
var newy = getNewValue($('#_mrk').offset().top, height, $("#_img").height());
$("#_mrk").css("top", newy);
width = $("#_img").width();
height = $("#_img").height();
});
#_mrk {
position: absolute;
}
#_img {
width: 100%;
}
<img id="_img" src="http://clipartion.com/wp-content/uploads/2015/11/colorable-car-line-art-free-clip-art.png" width="550px" height="168px" />
<div id="_mrk" style="display:none;">x</div>
Save value of document width when img is clicked. Add event listener to resize event and change X and Y values when it fired:
var X, Y, doc_width, a_ratio;
$("#_img").on("click", function(event){
X = event.pageX-5;
Y = event.pageY-5;
doc_width = document.documentElement.clientWidth;
a_ratio = $(this).width()/$(this).height();
move_mark(X, Y);
});
$(window).on("resize", function(){
var x = X + (document.documentElement.clientWidth - doc_width);
var y = Y + (x - X)/a_ratio;
move_mark(x, y);
})
function move_mark(X,Y){
$("#marker").css({
"left":X,
"right":Y
}).show();
}
You can use percentage instead of pixels to support all sizes.
First of all make sure the container of the img and the marker is position relative, and the marker is position absolute.
Then, when clicking you will need to calculate the X and Y within the image, and then based on that calculate percentage.
var img = $("#_img");
img.on("click", function(event){
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
var left = 'calc(' + ((x / img.width()) * 100) + '% - 5px)';
var right = 'calc(' + ((y / img.height()) * 100) + '% - 5px)';
$("#marker").css({
"left": left,
"right": right
}).show();
});
HTML:
<img src="img/image1.jpg" id = "image1" style="width: 100%;" allign = "center">
JavaScript:
var image1 = document.getElementById("image1");
How would I get the center of this given image, and then place another image which has an absolute position on top of it dead center?
You can use getBoundingClientRect() on the images to find their exact position and calculate using those values. This method will take into consideration the CSS size as well as scroll position etc.
The second image is placed below using fixed position, for demo, but you can use a parent div set to relative and place the image inside that using absolute etc.
Example
function centerImages() {
var image1 = document.getElementById("image1");
var rect1 = image1.getBoundingClientRect();
var cx = rect1.left + rect1.width * 0.5; // find center of first image
var cy = rect1.top + rect1.height * 0.5;
var image2 = document.getElementById("image2");
var rect2 = image2.getBoundingClientRect();
var x = cx - rect2.width * 0.5; // use center of first, subtract second
var y = cy - rect2.height * 0.5;
image2.style.cssText = "position:fixed;left:" + x + "px; top:" + y + "px";
}
window.onload = window.onresize = window.onscroll = centerImages;
<img src="http://i.stack.imgur.com/UDTPI.gif" id="image1" style="width: 100%;">
<img src="http://i.stack.imgur.com/fk5Js.gif" id="image2">
http://jsfiddle.net/33ra14az/1/ here's a way I came up with using JS + resize event for responsive.
function setImg() {
var img1 = document.getElementById('image1'),
img2 = document.getElementById('image2'),
offtop = ((img1.offsetHeight/2)-(img2.offsetHeight/2)),
offleft = ((img1.offsetWidth/2)-(img2.offsetWidth/2));
img2.style.top = offtop + "px";
img2.style.left = offleft + "px";
}
window.load = setImg();
window.addEventListener('resize',setImg);
well you can try this :
$(document).ready(function() {
var top=($("#image1").height()/2)-($("#image2").height()/2);
var left=($("#image1").width()/2)-($("#image2").width()/2);
$("#image2").css('left',left+'px');
$("#image2").css('top',top+'px');
});
and the css is simple:
#image2{
position: absolute;
display:block;
width:100px;
height:100px;
}
and this is the html code:
<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo.png" id = "image1" style="width: 100%;" allign = "center">
<img src="http://www.hakandemirel.com.tr/blog/wp-content/uploads/jsfiddle.png" id ="image2">
this is demo:
http://jsfiddle.net/yysdged6/22/
I was just messing around in jsfiddle trying to resize a box base on the mouse position. Making the box larger as the mouse moves away is simple, just get the distance. However, I want to do the opposite; I want the box to increase in size as the mouse gets closer and decrease as the mouse moves away. I haven't been able to think up any formulas for this. I feel there could be something really simple that I am missing.
<div id="box"></div>
#box {
height: 100px;
width: 100px;
background: black;
}
var box = document.getElementById('box');
// center point of the box
var boxX = 50;
var boxY = 50;
document.addEventListener('mousemove', function(e) {
var x = e.pageX,
y = e.pageY;
var dx = x - boxX,
dy = y - boxY;
var distance = Math.sqrt(dx *dx + dy * dy);
box.style.width = box.style.height = distance + 'px';
}, false);
Here is a link to the fiddle:
http://jsfiddle.net/gSDPq/
Any help is appreciated, Thanks
Try distance = Math.max(0,200-Math.sqrt(dx*dx + dy*dy));
This should have the box disappear when the mouse is 200px or more away, and steadily grow to 200px in size as you get nearer the middle. Adjust numbers as needed (for instance, divide the Math.sqrt() part by 2 to reduce the effect that distance has, or adjust the 200 to affect the max size)
jsfiddle
var box = document.getElementById('box');
// center point of the box
var boxX = 50;
var boxY = 50;
var ux=500, uy=500;// 1.stage
document.addEventListener('mousemove', function(e) {
var x = e.pageX,
y = e.pageY;
var dx = ux-(x - boxX),
dy = uy-(y - boxY);// 2.stage
var distance = Math.sqrt(dx *dx + dy * dy);
box.style.width = box.style.height = distance + 'px';
}, false);
I'm not sure that Kolink's answer actually did what you wanted to do. You seem to want the box to grow when the mouse is getting closer to it.
Just subtracting both x and boxX from some predefined box size value should do that:
var dx = 400 - x - boxX,
dy = 400 - y - boxY;
if(dx<0) dx = 0;
if(dy<0) dy = 0;
http://jsfiddle.net/gSDPq/3/