I have an div Element with the ID mypointer, wich has an absolute position. I animate this div on a page with jquery. The goal is a presentation where the elements show the same reaktion on the div element like the mousepointer. So I want to simulate mouseover, click and rightclick events.
Is that possible? Can someone give me an example which show me how to do that?
Thank you for your answers
Lara
P.S.
Example here
link text
the red square is over an h1 element. Is it possible to execute the h1 mouseover event, when there is a collision of the mypointer and an h1 element?
I'm not quite sure if I get you well, but to 'simulate' events like mouseover et cetera, you can always use jQuery's .trigger() in a form like:
$('#my_div_id').trigger('mouseover');
You can also call a more 'detailed' version, where you can specify the events arguments
$('#my_div_id').trigger({
type: 'keypress',
which: 13,
ctrlKey: true
});
which infact would simulate a return key while ctrl key is pressed to 'my_div_id'. If you just need the event handler code to execute, use .triggerHandler().
Maybe i don't understand your idea completely, but i wrote some code.
It works very simple. We bind two events "click mouseover" on #mypointer and also on h1 (or any other selector). When the event fires on #mypointer we check every h1 element to match it's position with position of #mypointer and if match -- trigger the event on matched element.
"use strict";
/*global $*/
function getElementCoordinates(el) {
return {
left: el.offsetLeft,
right: el.offsetLeft + el.offsetWidth,
top: el.offsetTop,
bottom: el.offsetTop + el.offsetHeight
};
}
function checkIntersection($el) {
var pointer = getElementCoordinates($('#mypointer')[0]);
var element = getElementCoordinates($el[0]);
if ((pointer.left >= element.left && pointer.left = element.left && pointer.right = element.bottom && pointer.bottom = element.bottom && pointer.top
$(function () {
$('#mypointer').live('click mouseover', function (e) {
//here write selectors you want to check for collision
$('h1').each(function () {
if (checkIntersection($(this))) {
$(this).trigger(e.type);
return false;
}
});
});
$('h1').live('click mouseover', function (e) {
$("#output").html(e.type + ' fired on ' + e.target.nodeName);
});
});
Sorry, parser "eat" checkIntersection function, so full code available on http://www.everfall.com/paste/id.php?263utdc1nmqy
wbr,
Roman.
Related
Okay so I can detect a mouseover using .on('mouseover')
and I can detect keypresses using
$(document).keypress(function(e) {
console.log(e.which);
}
but how do I detect which image my mouse is hovering over when I press a certain button?
the idea is to be able to delete an image by pressing d while hovering over it. any ideas ?
You can just toggle a class or data-attribute that shows you which one is currently being hovered
$('img').hover(function(){
$(this).toggleClass('active'); // if hovered then it has class active
});
$(document).keypress(function(e) {
if(e.which == 100){
$('.active').remove(); // if d is pressed then remove active image
}
});
FIDDLE
I'v added a better example with jsFiddle:
http://jsfiddle.net/cUCGX/ (Hover over one of the boxes and press enter.)
Give each image an on('mouseover') and set a variable based on that image.
So
var activeImage = null;
myImage.on('mouseover', function() {
activeImage = 'myImage';
});
myImage2.on('mouseover', function() {
activeImage = 'myImage2';
});
$(document).keypress(function(e) {
if (e.which == 'certainKeyPress' && activeImage) {
//do something with activeImage
console.log('The cursor was over image: ' + activeImage + ' when the key was pressed');
}
});
Maybe also add an onmouseout to each image as well to clear activeImage if you want the key press to only work WHEN being hovered.
You should use a mousemove event to permanently store the x & y position in a global variable.
Then, in the keypress handler, grab the element at the last-known mouse position with the document.elementFromPoint(x, y) method.
See https://developer.mozilla.org/en-US/docs/Web/API/document.elementFromPoint
I'm going to go ahead and necro this as I was playing around with this and found I liked my quick solution more. It may not be the best, but it worked better for my needs where I needed a namespace type solution in that the handler would be removed when the dom was in a certain state (sortable):
// Create handler for binding keyup/down based on keyCode
// (ctrl in this example) with namespace to change the cursor
var setCursorBindings = function() {
$(document).on('keydown.sortable', function(event) {
if (event.keyCode === 17) {
$('body').css('cursor', 'pointer');
}
}).on('keyup.sortable', function(event) {
if (event.keyCode === 17) {
$('body').css('cursor', 'inherit');
}
});
};
// Create a handler for reverting the cursor
// and remove the keydown and keyup bindings.
var clearCursorBindings = function() {
$('body').css('cursor', 'inherit');
$(document).off('keydown.sortable').off('keyup.sortable');
};
// Use the jQuery hover in/out to set and clear the cursor handlers
$('.myElementSelector').hover(function() {
setCursorBindings();
}, function() {
clearCursorBindings();
});
Tested in Chrome v41
Use this to test whether the mouse is over the image with id img:
$('#img').is(":hover")
I want to have the click and drag functionality that Raphael.js provides, an example here: https://qiao.github.io/PathFinding.js/visual/.
The way you add and remove obstacles is great, it's essentially combining mousedown event and hover. But how on earth is that done? Any help please?
The closest I have is: https://codepen.io/ProgrammingKea/pen/ZowWJx
The salient bit is
div.addEventListener("mousedown", function(ev){
this.classList.add("obstacle");
});
div.addEventListener("mousemove", function(ev){
this.classList.add("obstacle");
});
div.addEventListener("mouseup", function(ev){
this.classList.add("obstacle");
});
If you press large, then hover over the grid, that's the closest I've got.
But my issue is that its only hover here, I don't have the click functionality the above link does
Please post answers containing only vanilla JS
It maybe feels a bit clunky putting a handler on every element. I'd be tempted to put a handler on the main container and then check from there...
Maybe first add a bit of code to check if mouse is down.
var main = document.getElementById('main')
var mouseDown = 0;
main.onmousedown = function() {
mouseDown=1;
}
main.onmouseup = function() {
mouseDown=0;
}
Then we can check if a mouse is down or over event...
main.addEventListener('mouseover', mousecheck)
main.addEventListener('mousedown', mousecheck)
Then we preventDefault (stop a drag).
If the mouse is down, and the element being acted on is a box, then we'll change it's colour.
function mousecheck( ev ) {
ev.preventDefault();
if( mouseDown && ev.target.className.startsWith( 'box') ) {
ev.target.style.backgroundColor = ev.target.style.backgroundColor == "red" ? 'white' : 'red';
}
}
Codepen
You can use something like:
["mousedown", "mousemove", "mouseup"]
.forEach(function (eve) {
div.addEventListener(eve, function(ev){
this.classList.add("obstacle");
});
});
I found some code and I made a jsfillde with it. I need to know how to trigger mouseup in the function below, when you leave document body (in the fiddle example it's like dragging the object into HTML section for instance and leave the mouse click there).
function handleMouseMove(e) {
if (canMove) {
var left = getMousePosX(e);
var top = getMousePosY(e);
var newLeft = ($(elemToMove).css('left').toDecNum() + (left - lastPosX));
var newTop = ($(elemToMove).css('top').toDecNum() + (top - lastPosY));
$(elemToMove).css('left', newLeft);
$(elemToMove).css('top', newTop);
lastPosX = left;
lastPosY = top;
}
return false;
}
Thanks for any suggestion.
You can use
document.onmouseout = handleMouseUp;
This says that when the mouse leaves the document object, the handleMouseUp handler should be called.
Updated fiddle:
http://jsfiddle.net/vp14utt1/1/
-
P.S. for event handlers that simply take the event as an argument, you can just use the function name without wrapping it.
document.onmousedown = function (e) { handleMouseDown(e); };
document.onmousedown = handleMouseDown;
$(elemToMove).trigger('mouseup');
Should do it.
Add this line (new Fiddle):
document.onmouseleave = function (e) { handleMouseUp(e); };
This fires your 'mouse up' logic when the mouse is dragged off the browser window.
To quote The difference between mouseout() and mouseleave():
The mouseout event triggers when the mouse pointer leaves any child elements as well the selected element.
The mouseleave event is only triggered when the mouse pointer leaves the selected element.
I think you want the later.
I have this piece of code:
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
I'd like ajax_call() to be called only when clicking on empty space inside div but not on "Mylink". Is it possible without any external javascript framework?
Moreover I have this piece of css:
div#mydiv:hover{
background-color: blue;
}
Is it possible to disable the :hover stylesheet when the cursor is placed over "Mylink" (in order to suggest that clicking on "Mylink" won't trigger ajax_call() but will take to myurl)?
Attach the function at child element with click event, After clicked on child element it's handler stops the immediate propagation, As a result ajax_call() will not be invoked.
HTML
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
javaScript
function ajax_call(){
alert("empt space");
}
//this function stops the propagation and not triggered above
//function when clicked on child element.
function notCall(event) {
event.stopImmediatePropagation();
return false;
}
DEMO
I'm not sure what you want but if I keep my imagination may be that this work, lucky !
$("div#mydiv a").hover(function(){
$(this).parent().css("background-color","transparent")
})
Sure, what you need is the event target || scrElement
Like
function ajax_call() {
var target = event.target ? event.target : event.srcElement;
if(target.id==="mydiv") { alert("good to go"); }
}
See : http://jsbin.com/qujuxufo/1/edit
Edit/Update ( missed the second part ) - Started to answer this before the q was closed - but might as well as it now ..
For the second part of the question - it is not possible to set parent elements in CSS ( it flows top to bottom ) - for that some more JS is needed.
See http://jsbin.com/cileqipi/1/edit
CSS
#mydiv:hover { background-color:green; color:#fff}
#mydiv.anchorhover, #mydiv.anchorhover:hover { background-color:white;}
Then JS
var _mydiv = document.getElementById("mydiv");
var _mydiv_anchors = _mydiv.getElementsByTagName("a");
function toggleClass() {
var addClass=true, cls="anchorhover";
if((_mydiv.className).indexOf(cls) >= 0){ addClass=false; }
if(addClass) {
_mydiv.className=_mydiv.className+=' '+cls;
} else {
/* remove */
_mydiv.className=_mydiv.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');
}
}
for(var i=0, len=_mydiv_anchors.length; i<len; ++i) {
_mydiv_anchors[i].onmouseover = toggleClass;
_mydiv_anchors[i].onmouseout = toggleClass;
}
^ That feels like quite a trip compared to how simple jquery abstracts it .. >
$("#mydiv a").hover(function() {
$(this).parent().addClass("anchorhover");
}, function() {
$(this).parent().removeClass("anchorhover");
});
Either way, the principle is : to add a style class to the parent element on mouseover and remove it on mouseout
I'm using jquery ui autocomplete and want to decipher between focus events triggered by keyboard interaction and mouse interaction. How would I go about this?
$('input').autocomplete({
source: function(request, response) {
...
},
focus: function(event, ui) {
// If focus triggered by keyboard interaction
alert('do something');
// If focus event triggered by mouse interaction
alert('do something else');
}
});
Thanks
The only way I can think of doing this is to have a handler listen in on the keypress and click events, and toggle a boolean flag on/off. Then on the focus handler of your input, you can just check what the value of your flag is, and go from there.
Probably something like
var isClick;
$(document).bind('click', function() { isClick = true; })
.bind('keypress', function() { isClick = false; })
;
var focusHandler = function () {
if (isClick) {
// clicky!
} else {
// tabby!
}
}
$('input').focus(function() {
// we set a small timeout to let the click / keypress event to trigger
// and update our boolean
setTimeout(focusHandler,100);
});
Whipped up a small working prototype on jsFiddle (don't you just love this site?). Check it out if you want.
Of course, this is all running off a focus event on an <input>, but the focus handler on the autocomplete works in the same way.
The setTimeout will introduce a bit of lag, but at 100ms, it might be negligible, based on your needs.
You should actually be able to determine this from the event-Object that is passed into the focus-event. Depending on your code structure this might be different, but there is usually a property called originalEvent in there, which might be nested to some depth. Examine the event-object more closely to determine the correct syntax. Then test on mousenter or keydown via regular expression. Something like this:
focus: function(event, ui){
if(/^key/.test(event.originalEvent.originalEvent.type)){
//code for keydown
}else{
//code for mouseenter and any other event
}
}
The easiest and most elegant way I've found of achieving this is to use the "What Input?" library. It's tiny (~2K minified), and gives you access to the event type both in scripts:
if (whatInput.ask() === 'mouse') {
// do something
}
...and also (via a single data attribute that it adds to the document body) styles:
[data-whatinput="mouse"] :focus,
[data-whatinput="touch"] :focus {
// focus styles for mouse and touch only
}
I particularly like the fact that where you just want a different visual behaviour for mouse / keyboard it makes it possible to do that in the stylesheet (where it really belongs) rather than via some hacky bit of event-checking Javascript (though of course if you do need to do something that's not just purely visual, the former approach lets you handle it in Javascript instead).
The first thing that comes to mind is that you can find the position of the mouse and check to see if its within the position of the element
Use this to store the position of the element:
var input = $('#your_autocompleted_element_id'),
offset = input.offset(),
input_x = offset.top,
input_y = offset.left,
input_w = input.outerWidth(),
input_h = input.outerHeight();
Then use this to find absolute position of the mouse within the window:
var cur_mx, cur_my;
$(document).mousemove(function(e){
cur_mx = e.pageX;
cur_my = e.pageY;
});
Then in your autcomplete setup:
focus: function(event, ui) {
// mouse is doing the focus when...
// mouse x is greater than input x and less than input x + input width
// and y is greater than input y and less than input y + input height
if (cur_mx >= input_x && cur_mx <= input_x + input_w && cur_my >= input_y && cur_my <= input_y + input_h) {
// do your silly mouse focus witchcraft here
} else {
// keyboard time!
}
}
This can be handled using mousedown event, see my example below.
this.focusFrom = 'keyboard' =>
onFocus = () => {
if (this.focusFrom === 'keyboard') {
// do something when focus from keyboard
}
}
handleMouseDown = () => {
this.focusFrom = 'mouse';
}
handleOnClick = () => {
this.focusFrom = 'keyboard';
}