position (X, Y coordinates) update on page resize - javascript

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();
});

Related

How do I shrink this jquery?

I have this script, and it does exactly what I want. shows and hides a div and follows mouse-cursor around and does it only when viewport is a certain size and above, but I would like to know how to condense it so the whole script is not duplicated twice, one for on load and one for when listening to browser window resizing.
<script>
$( document ).ready(function() { //document ready
$( window ).on( "load", function() { //entire page has loaded
if ($(window).width() < 963) {
tip = $(this).nextAll('#tail');
tip.hide();
}
else {
//Tooltips
$("#mainbody").hover(function(){
tip = $(this).nextAll('#tail');
tip.show(); //Show tooltip
}, function() {
tip.hide(); //Hide tooltip
}).mousemove(function(e) {
if ($(window).width() > 962) {
//Change these numbers to move the tooltip offset
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
//var tipVisY = $(window).height() - (mousey + tipHeight);
var tipVisY = $("#mainbody").height() - (tipHeight);
if (tipVisX < 1) { //If tooltip exceeds the X coordinate of viewport
//mousex = e.pageX - tipWidth - 20;
} if (tipVisY < 1) { //If tooltip exceeds the Y coordinate of viewport
//mousey = e.pageY - tipHeight - 20;
}
//Absolute position the tooltip according to mouse position
tip.css({ top: mousey, left: mousex });
}
});
}
$( window ).resize(function() {
if ($(window).width() < 963) {
tip = $(this).nextAll('#tail');
tip.hide();
}
else {
//Tooltips
$("#mainbody").hover(function(){
tip = $(this).nextAll('#tail');
tip.show(); //Show tooltip
}, function() {
tip.hide(); //Hide tooltip
}).mousemove(function(e) {
if ($(window).width() > 962) {
//Change these numbers to move the tooltip offset
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
//var tipVisY = $(window).height() - (mousey + tipHeight);
var tipVisY = $("#mainbody").height() - (tipHeight);
if (tipVisX < 1) { //If tooltip exceeds the X coordinate of viewport
//mousex = e.pageX - tipWidth - 20;
} if (tipVisY < 1) { //If tooltip exceeds the Y coordinate of viewport
//mousey = e.pageY - tipHeight - 20;
}
//Absolute position the tooltip according to mouse position
tip.css({ top: mousey, left: mousex });
}
});
}
});
});
});
</script>
You can insert code to function and call this function where you want.
$( document ).ready(function() { //document ready
$( window ).on( "load", function() { //entire page has loaded
change(this)
$( window ).resize(function() {
change(this)
});
});
});
function change(_this){
if ($(window).width() < 963) {
tip = $(_this).nextAll('#tail');
tip.hide();
}
else {
//Tooltips
$("#mainbody").hover(function(){
tip = $(this).nextAll('#tail');
tip.show(); //Show tooltip
}, function() {
tip.hide(); //Hide tooltip
}).mousemove(function(e) {
if ($(window).width() > 962) {
//Change these numbers to move the tooltip offset
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
//var tipVisY = $(window).height() - (mousey + tipHeight);
var tipVisY = $("#mainbody").height() - (tipHeight);
if (tipVisX < 1) { //If tooltip exceeds the X coordinate of viewport
//mousex = e.pageX - tipWidth - 20;
} if (tipVisY < 1) { //If tooltip exceeds the Y coordinate of viewport
//mousey = e.pageY - tipHeight - 20;
}
//Absolute position the tooltip according to mouse position
tip.css({ top: mousey, left: mousex });
}
});
}
}
An alternative is to manually fire the event handler using .trigger('[eventname]'):
$( window ).on( "load", function() {
$( window ).resize(function() {
//do some stuff
}).trigger('resize');
});

How to create a div completely inside the borders of another div?

I am trying to write a code so that whenever I click on a div, another div is created inside it at the mouse coordinates where I clicked. This is what I did:
$("#main_div").mouseup(function (e){
var parentOffset = $(this).offset();
var x = e.pageX - parentOffset.left;
var y = e.pageY - parentOffset.top;
$(this).prepend('<div style="position:absolute;width:150px;height:80px;background-color:#FFF19A;border:1px solid #eee;padding:5px;left:'+x+'px;top:'+y+'px;padding:5px;"></div>');
});
The problem is that once I click near the right border of main_div, part of the created div shows up outside the main_div. Is there a way to make the created div always show up inside main_div?
So that when click near right border of main_div, the created div has left position equal to x minus some quantity. I am not sure what this quantity is. I hope you understand my problem.
Something like this? https://jsfiddle.net/0tyhb7nx/1/
$("#main_div").mouseup(function (e){
var parentOffset = $(this).offset();
var parentWidth = $(this).width();
var parentHeight = $(this).height();
var x = e.pageX - parentOffset.left;
var y = e.pageY - parentOffset.top;
if (x + 162 > parentWidth)
x = x - 162;
if (y + 92 > parentHeight)
y = y - 92;
$(this).prepend('<div style="position:absolute;width:150px;height:80px;background-color:#FFF19A;border:1px solid #eee;padding:5px;left:'+x+'px;top:'+y+'px;padding:5px;"></div>');
});
This solution takes into account the position of the container too, so you can move it freely.
You have to remember to set the position of the container to position: relative;
Just for clarification:
162 = 150 (width) + 2 * 5 (padding) + 2 * 1 (border)
92 = 80 (height) + 2 * 5 (padding) + 2 * 1 (border)
You probably better use variables for all these numbers and not hardcode them like this.
check this fiddle. using bumpy's solution.
but modified it a bit.
JS
$("#main_div").mouseup(function (e) {
var parentOffset = $(this).offset();
var parentWidth = $(this).width();
var parentHeight = $(this).height();
var x = e.pageX - parentOffset.left + 10;
var y = e.pageY - parentOffset.top + 10;
if (x + 150 > parentOffset.left + parentWidth) x = x - 170;
if (y + 80 > parentOffset.top + parentHeight) y = y - 100;
$(this).prepend('<div style="position:absolute;width:150px;height:80px;background-color:#FFF19A;border:1px solid #eee;padding:5px;left:' + x + 'px;top:' + y + 'px;padding:5px;"></div>');
});

JavaScript coordinates showing as greater than the image width and height

I am trying to get the location of the mouse while hovering over an image in pixels from the top left corner of the image. I am currently using the pageX and pageY event attributes but this is returning a value greater than the width and height of the image itself.
var getImgCoord = function(e) {
var x = e.pageX,
y = e.pageY;
console.log(x + ' | ' + y);
}
$('.featuredImg').mousemove(function() {
getImgCoord(event);
});
Any help would be greatly appreciated.
pageX and pageY are the coordinates relative to the top left corner of the document not your image itself (the name already says it).
you need to subtract the offsets from your element:
$('.featuredImg').mousemove(function(e) {
var x = e.pageX - $(this).offset().left,
y = e.pageY - $(this).offset().top;
console.log(x + ' | ' + y);
});
http://jsfiddle.net/D5uuA/
var getImgCoord = function(e) {
var imageOffset = $(this).offset();
//or $(this).offset(); if you really just want the current element's offset
var x = e.pageX - imageOffset.left,
y = e.pageY - imageOffset.top;
console.log(x + ' | ' + y);
}
$('.featuredImg').mousemove(getImgCoord);

How to increase element size as mouse gets closer?

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/

Mouse on left of screen move image to left, same when mouse on right of screen

I'm trying to get an image that is around 1920x1200px to pan around on a 800x600px browser window.
So if my mouse is on the top-left of the browser window the image is alined so it's top-left margins are on the top-left of the browser window. The same goes for the bottum-right.
So if the mouse is in the centre of the screen the image should be centered too.
Im not sure what calculations are needed as my math is a bit rusty.
Currently I'm using a bit of javascript that just moves the image using CSS's top/left properties but without much success as it's just moving the picture around from it's top/left corner.
I'v also set the image's position to absolute in css.
function updateImgPosition( e )
{
var avatar = document.getElementById("avatar");
// Width
var windowWidth = window.innerWidth;
var mouseWidthLocation = e.x;
var percentOfWidth = (100 / windowWidth) * mouseWidthLocation;
// Height
var windowHeight = window.innerHeight;
var mouseHeightLocation = e.y;
var percentOfHeight = (100 / windowHeight) * mouseHeightLocation;
avatar.style.top = percentOfHeight + "%";
avatar.style.left = percentOfWidth + "%";
}
document.onmousemove = updateImgPosition;
This is a demo of what I have: http://jsfiddle.net/uQAmQ/1/
Fiddle: http://jsfiddle.net/uQAmQ/2/
You should not "pan" on an absolutely positioned element, because the window's width and height keep changing according to the image. A smoother solution involves using a background image. See the middle of my answer for the used logic.
Consider this JavaScript (read comments; HTML + CSS at fiddle):
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatar = document.getElementById("avatar");
var avatarWidth = avatar.width;
var avatarHeight = avatar.height;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseY = e.pageX; //e.pageX, NOT e.x
var mouseX = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
The logic behind it:
Relative units cannot be used, because the image size is specified in absolute units.
The offsets should change according to a specific ratio, which is similar to: image size divided by window size.However, this ratio is not complete: The image would disappear at the bottom/left corner of the window. To fix this, substract the window's size from the image's size. The result can be found in the code at variable ratioX and ratioY.
The previous code had to be loaded at the window.onload event, because the image's size was dynamically calculated. For this reason, a HTML element was also included in the body.
The same code can be written much smaller and efficient, by specifying the size of the background in the code. See this improved code. Fiddle: http://jsfiddle.net/uQAmQ/3/
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var avatarWidth = 1690;
var avatarHeight = 1069;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
/* Logic: Move */
var ratioY = (avatarHeight - windowHeight) / windowHeight;
var ratioX = (avatarWidth - windowWidth) / windowWidth;
function updateImgPosition( e ) {
var mouseX = e.pageX; //e.pageX, NOT e.x
var mouseY = e.pageY;
var imgTop = ratioY*(-mouseY);
var imgLeft = ratioX*(-mouseX);
document.body.style.backgroundPosition = imgLeft + "px " + imgTop + "px";
}
/* Add event to WINDOW, NOT "document"! */
window.onmousemove = updateImgPosition;
})();
If you don't mind a decreased code readability, the following code is the best solution, Fiddle: http://jsfiddle.net/uQAmQ/4/:
(function(){ //Anonymous function wrapper for private variables
/* Static variables: Get the true width and height of the image*/
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var ratioY = (windowHeight - 1069) / windowHeight;
var ratioX = (windowWidth - 1690) / windowWidth;
window.onmousemove = function( e ) {
document.body.style.backgroundPosition = ratioX * e.pageX + "px " + ratioY * e.pageY + "px";
}
})();

Categories

Resources