Combing "click" and "hover" permanently? - javascript

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

Related

Undo .removeAtribute function

I'm looking for a solution to restore a removed attribute. I'm not an experienced programmer, so I'm not sure where to start when sharing my code, so I'll try to give some context below.
I have an image of a map that has several hidden overlays. These overlays are activated by a series of adjacent buttons.
Each of these buttons has a mouseover and mouseout event, which temporarily reveals the overlay. They also have an onclick event that permanently displays the overlay. I've used a .removeAtribute function to remove the mouseout event so that my overlay is permanent.
All other layers are still visible with the mouseover and mouseout events (so that you can make comparisons).
When I onclick another overlay button, it clears the previous one, however, now the mouseout event for the previously selected button is still inactive, so hovering over it causes the overlay to appear permanently.
How can I restore the mouseout event after I've removed it?
I have tried to use .setAttribute("onmouseout"), but I've had no luck in making that work.
Hopefully, this all makes some sense; I'll post some of my code below, which might help give further context.
function btn01On() {
document.getElementById("btn01").removeAttribute("onmouseout");
}
function btnClear() {
document.getElementById("btn01").setAttribute("onmouseout");
}
<button id="btn01" class="map-button map-button1"
onclick="MM_showHideLayers('InfoCurrentExc','','show','OverlayCurrentExc','','show');btn01On();" onmouseover="MM_showHideLayers('OverlayCurrentExc','','show')" onmouseout="MM_showHideLayers('OverlayCurrentExc','','show')">
Current Excavation
</button>
Usually setting up event handlers using onevent attribute, (although oldest method for event handling) is not the recommended way, See https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers#dom_event_handler_list.
I recommend using EventTarget.addEventListener and EventTarget.removeEventListener for your case. Try the code below
const mouseoutHandler = function() {
MM_showHideLayers('OverlayCurrentExc', '', 'show');
};
const mouseOverHandler = function() {
MM_showHideLayers('OverlayCurrentExc', '', 'show');
};
const button01 = document.getElementById("btn01");
button01.addEventListener("mouseover", mouseOverHandler);
function btn01On() {
if (!mouseoutListener)
button01.addEventListener("mouseout", mouseoutHandler);
}
function btnClear() {
if (mouseoutListener) {
button01.removeEventListener("mouseout", mouseoutListener);
mouseoutListener = null;
}
}
const clickHandler = function() {
MM_showHideLayers('InfoCurrentExc', '', 'show', 'OverlayCurrentExc', '', 'show');
btn01On();
}
button01.addEventListener("click", clickHandler);
I was lucky enough to find someone who had a fix for this problem. I'll share the code below for anyone who might land here with a similar request.
I don't fully understand how this code works so if someone has a good explanation feel free to share it.
// Remove mouse outs
function btn01On() {
document.getElementById("btn01").removeAttribute("onmouseout");
}
// keep mouse outs
const buttonIds = ["btn01"];
const mouseOuts = {};
buttonIds.forEach((id) => {
const el = document.getElementById(id);
if (el) {
mouseOuts[id] = el.getAttribute('onmouseout');
}
});
const restoreMouseOutEvent = () => {
buttonIds.forEach((id) => {
const el = document.getElementById(id);
if (el && mouseOuts[id]) {
el.setAttribute('onmouseout', mouseOuts[id]);
}
});
}

How can I check for two different events simultaneously [duplicate]

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")

Differentiate between focus event triggered by keyboard/mouse

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';
}

Is it possible to trigger Mouseevents by a divcontainer?

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.

How do I detect clicks when using YUI drag drop?

I'm using YUI to add drag drop support to a div. It also responds to clicks. Unfortunately, the click behavior takes effect even after a drag drop operation. Here's a code snippet:
// Create a DOM object for the group tag.
div = document.createElement('div');
div.className = 'group';
div.onclick = function() { beginEditName(); }
container.appendChild(div);
// Enable drag/drop for the group tag.
dragdrop = new YAHOO.util.DD(div);
dragdrop.scroll = false;
dragdrop.on('dragEvent', function(ev) { onDrag(ev); });
dragdrop.on('endDragEvent', function(ev) { onEndDrag(ev); });
dragdrop.setXConstraint(0,0);
Click is supposed to edit text, while drag drop is supposed to move the tag. However, the onclick event is firing so that text editing begins after the tag is moved.
I could code around the problem, but is there a more direct YUI way of differentiating a simple click from a drag drop?
Michael,
http://ericmiraglia.com/yui/demos/ddclick.php
View the source, and let me know (ericmiraglia at yahoo dot com) if you have any further questions on this.
Modification. I will copy the code here, this way if this guy take off the code from his server people will be able to check the source.
var beingDragged = false;
var dd = new YAHOO.util.DD("drag");
dd.subscribe("mouseDownEvent", function(e){
beingDragged = false;
});
dd.subscribe("startDragEvent", function(e) {
beingDragged = true;
});
dd.subscribe("mouseUpEvent", function(e) {
if(beingDragged) {
alert("dragged")
} else {
alert("clicked");
}
})

Categories

Resources