Click location in image using JQuery - javascript

is there an easy way to find where user clicked inside an image (div, ...), relative to top-left corner of the element? (using js/jquery)
Basic event.pageX/event.pageY does not take into account scrolling and element position. Combining Document.getScrollTop() and element.getAbsoluteTop ( Mouse click location on an image ) does not look nice at all (may not even work on all browsers as far as I know).
Is there a simpler way to this?

This seems simple enough:
$('#yourImg').click(function(e){
var x = e.pageX - e.target.offsetLeft,
y = e.pageY - e.target.offsetTop;
});
See demo →

Related

change start position of horizontal scrollbar without jquery

In Jquery I'm aware you can move the scrollbars' starting location. Is this possible with pure javascript? To clarify, when the user loads the page I simply want the horizontal scrollbar to start scrolled all the way to the right, instead of starting at the left. If there are cross-browser issues, I'm particularly concerned with this working in Chrome.
document.body.scrollLeft = ( divRef.scrollWidth - divRef.offsetWidth ) / 2 ;
NOTE:
This can give odd results with IE8 and earlier.
I've made an example with a div, you can easily adjust this to your body tag, or another div, please see the demo.
var a = document.getElementById('body');
console.log(a.clientWidth)
function moveWin(a) {
window.scrollTo(a.clientWidth,0);
}
moveWin(a)
DEMO
SIDENOTE:
To select the body, simply use
var a = document.getElementsByTagName('body')[0]

Why does this simple drag and drop code cause the element to flicker?

I've got some very simple drag and drop jQuery code for vertical drag and drop:
function drag(ele){
$(document).mousemove(function(e){
yPos = ele.offset();
yPos = yPos.top;
diff = (yPos + ele.height()) - e.pageY;
ele.css('top', e.pageY - diff);
}).mouseup(function(){
$(this).unbind('mousemove');
});
}
It works perfectly well, except sometimes it starts flickering through small changes and the diff variable jumps around. I have no idea what may be causing this, perhaps someone else does?
http://jsfiddle.net/GTGMN/2/
The problem is much more prominent in the jsFiddle.
It's because you're changing the top property on the element and at the same time you're using that info to move the element. Try this for example:
function drag(ele){
$(document).mousemove(function(e){
ele.css('top', e.pageY);
}).mouseup(function(){
$(this).unbind('mousemove');
});
}
$('.box').mousedown(function(){
drag($(this));
})
This code will put the element directly where the cursor is. It might not be exactly what you want, but try to move the element without depending directly on its previous position.
Update:
The question asked for a 1-1 movement where the click started. This fiddle does that. The idea is to calculate the difference from the click position to the top of the box when the dragging begins, and then update the position using that offset.
Your math seems very strange. What exactly is the point of the diff variable?
Don't you just want: ?
ele.css('top', e.pageY);
or
ele.css('top', e.pageY - ele.height() / 2);

Is there a way to find the div name out from from location(x,y cords)

It is fairly easy to find the location of a div, when you know the div name. But is there an easy way to get the div id when all I know is the X/Y cords of the screen?
There will be no overlapping divs within a range of divs named '#Items1' to '#Items50' on a board (another div) called #HarbourRadar. Each div #Items can have more than one stacked image in it.
Anyway any hint to find the div out from a location would be greatly appreciated.
The following code (taken from the answer below on this side) gets the id of the div #HarbourRadar, that is partially right since the div #marker is layered ontop on that one, but does not return the div #marker that is selected - ie one with a higher Z-index.
var pos = $("#marker").position();
alert(document.elementFromPoint(pos.left, pos.top).id);
Yeah, it is possible using the document.elementFromPoint method.
This is how it is documented by Microsoft.
Here is Mozilla documentation.
The function is almost fully compatible, as you can see in this browser comparison.
Here is some sample code from MDN docs:
function changeColor(newColor) {
elem = document.elementFromPoint(2, 2);
elem.style.color = newColor;
}
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
have a look at this existing StackOverflow conversation you may find this helps:
Determine which element the mouse pointer is on top of in Javascript
This is using a javascript function document.elementFromPoint and has a great demo that shows a working example.
The jsFiddle URL is: http://jsfiddle.net/MPTTp/
Code from the fiddle:
$(window).click(function(e) {
var x = e.clientX, y = e.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
alert(elementMouseIsOver);
});

enlarge image and move it with the pointer on mouse over

Sorry if this might seem trivial for me to ask but..
I have some images and I need them to enlarge when I hover my mouse over them. But.. I want for the enlarged image to stick next to the pointer as I move it across the image. I don't know what to call it. I'm pretty sure it's only done with javascript, just css won't work here.
Something like this http://www.dynamicdrive.com/style/csslibrary/item/css-popup-image-viewer/ , but you know, it has to move with the pointer in motion.
What's the most effective way to do this?
The previous answers may be exactly what you're looking for, and you may already have this solved. But I note that you didn't mention jquery anywhere in your post and all of those answers dealt with that. So for a pure JS solution...
I'll assume from the way the question was phrased that you already know how to pop the image up? This can be done by coding an absolutely positioned hidden img tag in the html or generated on the fly with JS. The former may be easier if you are a JS novice. In my examples I'll assume you did something similar to the following:
<img src="" id="bigImg" style="position:absolute; display:none; visibility:hidden;">
Then you need an onMouseOver function for your thumbnail. This function must do three things:
1) Load the actual image file into the hidden image
//I'll leave it up to you to get the right image in there.
document.getElementById('bigImg').src = xxxxxxxx;
2) Position the hidden image
//See below for what to put in place of the xxxx's here.
document.getElementById('bigImg').style.top = xxxxxxxx;
document.getElementById('bigImg').style.left = xxxxxxxx;
3) Make the hidden image appear
document.getElementById('bigImg').style.display = 'block';
document.getElementById('bigImg').style.visibility = 'visible';
Then you'll need to capture the onMouseMove event and update the now un-hidden image's position accordingly using the same code you would have used in (2) above to position the image. This would be something like the following:
//Get the mouse position on IE and standards compliant browsers.
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
var curCursorX = e.pageX;
var curCursorY = e.pageY;
} else {
var curCursorX = e.clientX + document.body.scrollLeft;
var curCursorY = e.clientY + document.body.scrollTop;
}
document.getElementById('bigImg').style.top = curCursorY + 1;
document.getElementById('bigImg').style.left = curCursorX + 1;
And that should just about do it. Just add an onMouseOut event to hide the bigImg image again. You can change the "+1" in the last two lines to whatever you like to place the image correctly in relation to the cursor.
Note that all of the code above was for demonstration purposes only; I haven't tested any of it, but it should get you on the right track. You may want to expand upon this idea further by preLoading the larger images. You could also forgoe capturing mousemove events by using setTimeout to update the position every 20 ms or so, though I think that approach is more complicated and less desirable. I only mention it because some developers (including me when I started) have an aversion to JS event handling.
I did something similar to this with a custom ColdFusion tag I wrote that would generate a floating div users could click and drag around the screen. Same principle. If you need me to I can dig that out to answer any additional questions in more depth.
Good luck!
Liece's solution is close, but won't achieve the desired effect of the large image following the cursor.
Here's a solution in jQuery:
$(document).ready(function() {
$("img.small").hover (function () {
$("img.large").show();
}, function () {
$("img.large").hide();
});
$("img.small").mousemove(function(e) {
$("img.large").css("top",e.pageY + 5);
$("img.large").css("left",e.pageX + 5);
});
});
The HTML is:
<img class="small" src="fu.jpg">
<img class="large" src="bar.jpg">
CSS:
img { position: absolute; }
Try this links [jquery with auto positioning]
1.Simple
http://jquery.bassistance.de/tooltip/demo/
2.Good with forum
http://flowplayer.org/tools/tooltip/index.html
if I understood you correctly you want to position your big image relatively to the cursor. One solution in jquery (i'm not 100% sure of the code here but the logic is there):
$('.thumb').hover(function(e){
var relativeX = e.pageX - 100;
var relativeY = e.pageY - 100;
$(.image).css("top", relativeY);
$(.image).css("left", relativeX);
$(.image).show();
}, function(){
$(.image).hide();
})
Jquery is the easiest route. position absolute is key.
^ In addition to the above, here is a working JS Fiddle. Visit: jsfiddle.net/hdwZ8/1/
It has been roughly edited so it isnt using just overall IMG css tags, easy for anyone to use with this now.
I am using this script instead of a Lightbox in my Wordpress client site, a quick zoomed in image with mouse over is much nicer IMO. It is very easy to make efficient galleries especially with AdvancedCustomFields plug-in & in the WP PHP repeater loops!

How to know when an element will be off screen?

I am writing a simple script that displays a dialog box when a user hovers over a profile picture. It dynamically determines the profile pics location on the page and then places itself to the left of it and about 100px above it. This part is working fine.
My issue arises when a profile pic is at the top of the screen and a user mouses over it. The dialog will appear but the top portion of it will be above the fold (i.e. not in the current browser window). Naturally this is not good usability and I would like it to appear on the screen.
My question is how do I know when a dialog will be off screen so I can recalculate its position on the page?
I saw this question which seems like the same as mine but unfortunately no actual solution was provided other then to link to a jQuery plugin. I am using Prototype.
Prototype already provides positions with Element.viewportOffset().
Edit, as Mathew points out document.viewport gives the rest of the information. For example,
var dialogtop = dialog.viewportOffset().top;
if (dialogtop < 0) {
// above top of screen
}
elseif (dialogtop + dialog.getHeight > document.viewport.getHeight()) {
// below bottom of screen
}
You'll want to find the profile pic's position relative to the document (here's a good article on how, though I suspect Prototype's Element.Offset already handles this), then compare it to the body's scrollTop property to see if it's close enough to the top that it needs to have its dialog repositioned.
I am familiar with this problem, however, last time I was able to use a library (Seadragon) to get the screen dimensions and mouse position. I was also working with a fixed size overlay so no code to share with you other than general approach.
For my pop up box I decided to use the event mouse position rather than location of the div on the page. I then compared the mouse position to the known screen size, which I determined on start or resize.
From How do I get the size of the browser window using Prototype.js?
var viewport = document.viewport.getDimensions(); // Gets the viewport as an object literal
var width = viewport.width; // Usable window width
var height = viewport.height; // Usable window height
In Prototype you can also get the mouse coordinates:
function getcords(e){
mouseX = Event.pointerX(e);
mouseY = Event.pointerY(e);
//for testing put the mouse cords in a div for testing purposes
$('debug').innerHTML = 'mouseX:' + mouseX + '-- mouseY:' + mouseY;
}
Source : http://remorse.nl/2008/06/mouse_coordinates_with_prototype/

Categories

Resources