Trigger an event on a specific part of an image - javascript

I want to trigger an event handler when the user hovers on a particular part of the image, like the center of the image or the right side of the image (area would include, say, about a 100 pixels). I am not using any framework, so this is normal javascript that I am working with.
I am not sure if using image maps would work. Can anyone help?

Quirksmode about mouse position
Given the craziness involved here I would:
Use a framework (I just did something like this with Mootools)
Put absolutely positioned divs over the image and listen to events on them, instead of the image (did this too recently, a left 50% and a right 50%, way less cumbersome than tracking the mouse position).
Or go for it, quirksmode gives a decent function to get the mouse position, then you'll need to calculate the position of the image, then do the math to get the position of the mouse on the image, do the math in a mouseover event of the image, then continually check if the position meets your criteria, then do something about it when it does :)

You can use the MouseMove event to find out the location of the cursor, and then implement your own logic to calculate this position relative to the image.
See this page on getting the mouse coordinates.

i do not know how many areas you need and if they need to be especially shaped or something like that....
a straightforward solution would be placing (CSS) empty div elements "over" the image which will trigger the events
afaik it is not possible to trigger js events with an image map

An image map coupled with jquery is a great solution I've used before. I see that you're not using a framework, but it's worth a look.
Here's a little code snippet I used with an image map and mouseenter / mouseleave events.
$(".map-areas area")
.mouseenter(function() {
idx = $(".map-areas area").index(this);
showMapArea(idx);
})
.mouseleave(function() {
$(".map-hovers img").hide();
$(".map-titles img").hide();
});

I suggest putting an invisible div in the place where you want to check for mouse_over in the image. (In the case that the area you want is rectangular of course). And then trigger on mouse_over for this div.
If you want to check for non rectangular areas (that can't be a div), I would suggest that you put a div of the same size of the image on top of it. Check mouse position on that div, and use it to compare with a mask image.
Example:
MousePosOnGhostDiv_X = 76;
MousePosOnGhostDiv_Y = 145;
if(CheckColorOfMaskImage(MousePosOnGhostDiv_X,MousePosOnGhostDiv_Y)=="orange") do something.
By knowing which color it is on the mask image you can set multiple events.

Related

How to make HTML elements react on mouse movements?

my question is how can I add specific movement to x-y axis for an HTML element according to mouse movements.
Look at the site here and scroll to second slide:
http://community.saucony.com/kinvara3/
How can i achieve such effect!?
If you're going to write the library-free version, you will need to start with the following:
Learn DOM-manipulation.
var myEl = document.querySelector("#my-el");
Learn the <element>.style interface.
myEl.style.position = "absolute";
Learn the CSS properties, their values and how to read/use them from the style interface.
myEl.style.left = 10 + "px";
You'll need to understand the following CSS properties at a minimum:
"display"
"position"
"top"
"left"
"z-index"
Learn how to parse numbers from strings, properly, in JS.
...this will be unimportant, working with the mouse,
but very important, working with the DOM.
Learn how to write event-handlers.
window.addEventListener("mousemove", function (evt) {/*mousemove event object*/});
Learn the properties of event-objects (specifically the event-types that are important, like mouse, keyboard, touch).
Learn how to manage events, and control the number/frequency of operations, based on an ideal framerate, when the browser won't do it for you.
Learn how to make all of these things happen in a cross-browser, IE8+ way.
Learn a little linear-algebra (honestly, learning enough of it to understand an inverted-axis scaled-parallax is just a tiny bit harder than Grade 6 geometry.
You can get a similar effect CSS only, no JS needed!
You can see an example here: Pure CSS 3D Meninas, by Román Cortés. In his blog, there is also the explanation.
Basically, you have to split the target element in small elements, and on hover, set the position of different background layers according to your trigonometric calculations.
From his explanation,
There are 80 vertical hover elements of 5*455 pixels each, covering
the full effect. Each hover element contains inside elements to define
every layer position, the background image and the lateral background
image. When the hover element is not active (without the mouse over
it), all is inside elements showing images are hidden, with display:
none.
When the hover element is active, the images are set to display:
block, and the position of these are set. These positions have been
calculated and are written in the CSS code for each layer and each of
the 80 vertical hover elements. This is what does the magic.

selecting an element on mouse click overlapped by another transparent div

I am working on a dashboard where user can drag and drop elements to create html pages.Now,he can have multiple images using an image component.We have managed to calculate the z-index of the images and they can be adjusted using up-down keys.
Issue:
The issue we are facing is when we select a image component we attach a dotted layer above it for helping the user to easily drag and resize it.If the user places the images as shown in the image below
we are not able to select the inner image again because the z-index of the selection div(the one with the blue dots) is(has to be) the highest(highest bcoz we have to use it for all components).So if I try to select the inner image now it cannot be selected.How can I handle the situation? For reference it works on this site as expected.
I believe we have get the element under the parent when it is clicked.But not sure how!We are using javascript,jquery to handle the events.
You can use JavaScript or jQuery to get the position of the inner image, and when the user clicks on the outer image, check to see whether the mouse position lies within the range of the smaller image. The range can be calculated with the position, width, and height of the inner element.
To get the element's position: use jQuery .offset() or .position() (The former is relative to the document, the latter to the parent).
To get the mouse position: http://docs.jquery.com/Tutorials:Mouse_Position
You could consider hiding the masking element quickly in order to gather the coordinate for your underlying element, when done, you could re enable visibility for the masking element. Use document.elementFromPoint() in order to get the DOM item from mouse coordinate.
An example:
http://jsfiddle.net/s94cnckm/14/
Alternatively you can use The CSS property pointer-events: none; on the masking element.
Related:
https://developer.mozilla.org/de/docs/Web/CSS/pointer-events
How to detecting a click under an overlapping element?

Apply gradient over page without hindering user interaction [duplicate]

I have a div that has background:transparent, along with border. Underneath this div, I have more elements.
Currently, I'm able to click the underlying elements when I click outside of the overlay div. However, I'm unable to click the underlying elements when clicking directly on the overlay div.
I want to be able to click through this div so that I can click on the underlying elements.
Yes, you CAN do this.
Using pointer-events: none along with CSS conditional statements for IE11 (does not work in IE10 or below), you can get a cross browser compatible solution for this problem.
Using AlphaImageLoader, you can even put transparent .PNG/.GIFs in the overlay div and have clicks flow through to elements underneath.
CSS:
pointer-events: none;
background: url('your_transparent.png');
IE11 conditional:
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='your_transparent.png', sizingMethod='scale');
background: none !important;
Here is a basic example page with all the code.
Yes, you CAN force overlapping layers to pass through (ignore) click events.
PLUS you CAN have specific children excluded from this behavior...
You can do this, using pointer-events
pointer-events influences the reaction to click-, tap-, scroll- und hover events.
In a layer that should ignore / pass-through mentioned events you set
pointer-events: none;
Children of that unresponsive layer that need to react mouse / tap events again need:
pointer-events: auto;
That second part is very helpful if you work with multiple overlapping div layers (probably some parents being transparent), where you need to be able to click on child elements and only that child elements.
Example usage:
.parent {
pointer-events:none;
}
.child {
pointer-events:auto;
}
<div class="parent">
I'm unresponsive
I'm clickable again, wohoo !
</div>
Allowing the user to click through a div to the underlying element depends on the browser. All modern browsers, including Firefox, Chrome, Safari, and Opera, understand pointer-events:none.
For IE, it depends on the background. If the background is transparent, clickthrough works without you needing to do anything. On the other hand, for something like background:white; opacity:0; filter:Alpha(opacity=0);, IE needs manual event forwarding.
See a JSFiddle test and CanIUse pointer events.
I'm adding this answer because I didn’t see it here in full. I was able to do this using elementFromPoint. So basically:
attach a click to the div you want to be clicked through
hide it
determine what element the pointer is on
fire the click on the element there.
var range-selector= $("")
.css("position", "absolute").addClass("range-selector")
.appendTo("")
.click(function(e) {
_range-selector.hide();
$(document.elementFromPoint(e.clientX,e.clientY)).trigger("click");
});
In my case the overlaying div is absolutely positioned—I am not sure if this makes a difference. This works on IE8/9, Safari Chrome and Firefox at least.
Hide overlaying the element
Determine cursor coordinates
Get element on those coordinates
Trigger click on element
Show overlaying element again
$('#elementontop').click(e => {
$('#elementontop').hide();
$(document.elementFromPoint(e.clientX, e.clientY)).trigger("click");
$('#elementontop').show();
});
I needed to do this and decided to take this route:
$('.overlay').click(function(e){
var left = $(window).scrollLeft();
var top = $(window).scrollTop();
//hide the overlay for now so the document can find the underlying elements
$(this).css('display','none');
//use the current scroll position to deduct from the click position
$(document.elementFromPoint(e.pageX-left, e.pageY-top)).click();
//show the overlay again
$(this).css('display','block');
});
I currently work with canvas speech balloons. But because the balloon with the pointer is wrapped in a div, some links under it aren't click able anymore. I cant use extjs in this case.
See basic example for my speech balloon tutorial requires HTML5
So I decided to collect all link coordinates from inside the balloons in an array.
var clickarray=[];
function getcoo(thatdiv){
thatdiv.find(".link").each(function(){
var offset=$(this).offset();
clickarray.unshift([(offset.left),
(offset.top),
(offset.left+$(this).width()),
(offset.top+$(this).height()),
($(this).attr('name')),
1]);
});
}
I call this function on each (new) balloon. It grabs the coordinates of the left/top and right/down corners of a link.class - additionally the name attribute for what to do if someone clicks in that coordinates and I loved to set a 1 which means that it wasn't clicked jet. And unshift this array to the clickarray. You could use push too.
To work with that array:
$("body").click(function(event){
event.preventDefault();//if it is a a-tag
var x=event.pageX;
var y=event.pageY;
var job="";
for(var i in clickarray){
if(x>=clickarray[i][0] && x<=clickarray[i][2] && y>=clickarray[i][1] && y<=clickarray[i][3] && clickarray[i][5]==1){
job=clickarray[i][4];
clickarray[i][5]=0;//set to allready clicked
break;
}
}
if(job.length>0){
// --do some thing with the job --
}
});
This function proofs the coordinates of a body click event or whether it was already clicked and returns the name attribute. I think it is not necessary to go deeper, but you see it is not that complicate.
Hope in was enlish...
Another idea to try (situationally) would be to:
Put the content you want in a div;
Put the non-clicking overlay over the entire page with a z-index higher,
make another cropped copy of the original div
overlay and abs position the copy div in the same place as the original content you want to be clickable with an even higher z-index?
Any thoughts?
I think the event.stopPropagation(); should be mentioned here as well. Add this to the Click function of your button.
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Just wrap a tag around all the HTML extract, for example
<a href="/categories/1">
<img alt="test1" class="img-responsive" src="/assets/photo.jpg" />
<div class="caption bg-orange">
<h2>
test1
</h2>
</div>
</a>
in my example my caption class has hover effects, that with pointer-events:none; you just will lose
wrapping the content will keep your hover effects and you can click in all the picture, div included, regards!
An easier way would be to inline the transparent background image using Data URIs as follows:
.click-through {
pointer-events: none;
background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}
I think that you can consider changing your markup. If I am not wrong, you'd like to put an invisible layer above the document and your invisible markup may be preceding your document image (is this correct?).
Instead, I propose that you put the invisible right after the document image but changing the position to absolute.
Notice that you need a parent element to have position: relative and then you will be able to use this idea. Otherwise your absolute layer will be placed just in the top left corner.
An absolute position element is positioned relative to the first parent
element that has a position other than static.
If no such element is found, the containing block is html
Hope this helps. See here for more information about CSS positioning.
You can place an AP overlay like...
#overlay {
position: absolute;
top: -79px;
left: -60px;
height: 80px;
width: 380px;
z-index: 2;
background: url(fake.gif);
}
<div id="overlay"></div>
just put it over where you dont want ie cliked. Works in all.
This is not a precise answer for the question but may help in finding a workaround for it.
I had an image I was hiding on page load and displaying when waiting on an AJAX call then hiding again however...
I found the only way to display my image when loading the page then make it disappear and be able to click things where the image was located before hiding it was to put the image into a DIV, make the size of the DIV 10x10 pixels or small enough to prevent it causing an issue then hiding the containing div. This allowed the image to overflow the div while visible and when the div was hidden, only the divs area was affected by inability to click objects beneath and not the whole size of the image the DIV contained and was displaying.
I tried all the methods to hide the image including CSS display=none/block, opacity=0, hiding the image with hidden=true. All of them resulted in my image being hidden but the area where it was displayed to act like there was a cover over the stuff underneath so clicks and so on wouldn't act on the underlying objects. Once the image was inside a tiny DIV and I hid the tiny DIV, the entire area occupied by the image was clear and only the tiny area under the DIV I hid was affected but as I made it small enough (10x10 pixels), the issue was fixed (sort of).
I found this to be a dirty workaround for what should be a simple issue but I was not able to find any way to hide the object in its native format without a container. My object was in the form of etc. If anyone has a better way, please let me know.
I couldn't always use pointer-events: none in my scenario, because I wanted both the overlay and the underlying element(s) to be clickable / selectable.
The DOM structure looked like this:
<div id="outerElement">
<div id="canvas-wrapper">
<canvas id="overlay"></canvas>
</div>
<!-- Omitted: element(s) behind canvas that should still be selectable -->
</div>
(The outerElement, canvas-wrapper and canvas elements have the same size.)
To make the elements behind the canvas act normally (e.g. selectable, editable), I used the following code:
canvasWrapper.style.pointerEvents = 'none';
outerElement.addEventListener('mousedown', event => {
const clickedOnElementInCanvas = yourCheck // TODO: check if the event *would* click a canvas element.
if (!clickedOnElementInCanvas) {
// if necessary, add logic to deselect your canvas elements ...
wrapper.style.pointerEvents = 'none';
return true;
}
// Check if we emitted the event ourselves (avoid endless loop)
if (event.isTrusted) {
// Manually forward element to the canvas
const mouseEvent = new MouseEvent(event.type, event);
canvas.dispatchEvent(mouseEvent);
mouseEvent.stopPropagation();
}
return true;
});
Some canvas objects also came with input fields, so I had to allow keyboard events, too.
To do this, I had to update the pointerEvents property based on whether a canvas input field was currently focused or not:
onCanvasModified(canvas, () => {
const inputFieldInCanvasActive = // TODO: Check if an input field of the canvas is active.
wrapper.style.pointerEvents = inputFieldInCanvasActive ? 'auto' : 'none';
});
it doesn't work that way. the work around is to manually check the coordinates of the mouse click against the area occupied by each element.
area occupied by an element can found found by 1. getting the location of the element with respect to the top left of the page, and 2. the width and the height. a library like jQuery makes this pretty simple, although it can be done in plain js. adding an event handler for mousemove on the document object will provide continuous updates of the mouse position from the top and left of the page. deciding if the mouse is over any given object consists of checking if the mouse position is between the left, right, top and bottom edges of an element.
Nope, you can't click ‘through’ an element. You can get the co-ordinates of the click and try to work out what element was underneath the clicked element, but this is really tedious for browsers that don't have document.elementFromPoint. Then you still have to emulate the default action of clicking, which isn't necessarily trivial depending on what elements you have under there.
Since you've got a fully-transparent window area, you'll probably be better off implementing it as separate border elements around the outside, leaving the centre area free of obstruction so you can really just click straight through.

Custom cursor interaction point - CSS / JQuery

I'm trying to use a custom cursor for an online game, in this case it's a sniper scope.
The problem is when I reference the cursor via CSS, the interaction point is still the top left of the icon, whereas it needs to be dead center of the icon for the cursor to make any sense.
Here's the cursor:
cursor:url(http://www.seancannon.com/_test/sniper-scope.cur),default;
Here's a demo: http://jsfiddle.net/9kNyF/
If you put the red dot from the cursor over the red dot I created in the demo, it won't fire the click event. You have to attempt to aim the top left corner at it.
If you set the cursor back to cursor:default; you'll see the click event fires just fine, it's just a matter of "aiming" the cursor.
The game is coded in JQuery so if I need to add some logic there for cursor offset or something lame, so be it. Ideally I want this to be a CSS fix.
Thanks!
You just need to provide the hotspot's <x> and <y> position in your CSS:
In your example, the center happens to be 24px in from the top/left (huge ass cursor lol)
cursor:url(http://www.seancannon.com/_test/sniper-scope.cur) 24 24,default;
http://jsfiddle.net/9kNyF/15/ see?
As far as it not firing the click event try placing this around your event listener.
$(function(){
$('#point').click(function(){
alert('clicked point');
});
});
With the centering of the cross hairs it might be easier to use a div with the background of the image and using jQuery to place the div over your cursor in the correct place.
<div id="crosshairs"></div>
<script>
$(function(){
$("body").mousemove(function(e){
var CrossHairWidth = $('#crosshairs').width();
var CrossHairHeight = $('#crosshairs').height();
$('#crosshairs').css('top', e.pageY - (CrossHairHeight / 2));
$('#crosshairs').css('left', e.pageX - (CrossHairWidth / 2) );
});
});
</script>
You then hide the cursor doing something like so:
cursor: url(http://www.seancannon.com/_test/transparent.png), default;
whatever tool you used to create the cursor, should have an option for managing the click target area. You'd be chasing you tail looking for a javascript/css solution.

Getting javascript events to an object that's covered up

I'm trying to build a jquery app where I have a fixed image and a second draggable image. I need the fixed image to display z-index on top of the moveable image -- the fixed image is a picture with an alpha cut-out hole for a face like you might find at an amusement park. The problem is that as soon as the moveable (face) image is overlapping with the fixed image, click and drag events get captured by the fixed image which is on top and don't get to the moveable image. So it's no longer moveable. Here's my code...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js"></script>
<div id="fixed" style="position:relative; z-index: 2">
<img src="background.png">
</div>
<div id="face" style="position:relative; z-index: 1">
<img src="face.png">
</div>
<script>
$(function() {
$("#face").draggable();
});
</script>
How can I get the face object to be draggable when it's behind the fixed background? Can I manually fire the mouse events on the object underneath? If so, how do I invoke them so the jquery-ui draggable() works properly? Can I somehow get the fixed image just not to capture events? Or do I need to write my own draggable mechanism by hand?
I think i found a pretty simple solution for you. Basically you can relay the event only when certain conditions are met (eg #face is under the #fixed). Check out this fiddle for example.
A quick look at the even data revealed that draggable only binds mousedown, so that seems to be the only event you will need to relay.
$('#face').draggable();
$('#fixed').bind('mousedown', function(e){
// TODO: IF #face is under #fixed AND mouse is over #face THEN
$('#face').trigger(e); // trigger the event on face
});
I think you might be better off creating some sort of "drag handle" to the element underneath, which would always be visible (at least while dragging is enabled). That, or a separate UI control separated from the images which would act as a "joystick" for the draggable image, so that you could move the image without having to manually drag/drop the image itself.
Think about it: lets say they drag the item underneath the top item, then drop it; how are they to pick it up again? If this is setup like you explained (a cut-out hole for a face like you might find at an amusement park), then the user would not be able to visibly see the element underneath, and as such, it would be impossible for them to interact with that element using the mouse.

Categories

Resources