I have an iOS uiwebview with multiple imagemaps that I need to catch clicks on, so I can handle scaling on different iOS devices. The click handler I install works on the first image, but not on subsequent images. How do I make the click handler work on multiple images? The relevant code is below:
$.fn.imageMapSetup2 = function () {
$('img').each(function () {
if (typeof ($(this).attr('usemap')) == 'undefined') {
return;
}
var img = $(this);
// add click handler
img.on('click', function (event) {
img.imgClick(event);
});
});
};
$.fn.imgClick = function (mouseDown) {
mouseDown.preventDefault();
var $img = this;
var map = $img.attr('usemap').replace('#', '');
$('map[name="' + map + '"]').find('area').each(function () {
var $this = $(this),
coords = $this.attr('coords').split(',');
// lots of scaling code omitted
if (mouseX >= left && mouseX <= right &&
mouseY >= top && mouseY <= bottom) {
window.location = $this.attr('href');
}
});
};
FYI I have debugged the code in Safari and function imgClick() is not getting called for the second and subsequent images.
Add a click event listener to the parent element of the images. This could be the body element. Pass the event as an argument. Then, check the event, and use that variable to make changes to your image.
document.addEventListener("click", function (event) {
if (!event.target.tagName === "img") return;
if (typeof event.target.getAttribute("usemap") == "undefined") {
return;
}
imgClick(event);
});
Related
I want to use an if statement to check if the mouse is inside a certain div, something like this:
if ( mouse is inside #element ) {
// do something
} else {
return;
}
This will result in the function to start when the mouse is inside #element, and stops when the mouse is outside #element.
you can register jQuery handlers:
var isOnDiv = false;
$(yourDiv).mouseenter(function(){isOnDiv=true;});
$(yourDiv).mouseleave(function(){isOnDiv=false;});
no jQuery alternative:
document.getElementById("element").addEventListener("mouseenter", function( ) {isOnDiv=true;});
document.getElementById("element").addEventListener("mouseout", function( ) {isOnDiv=false;});
and somewhereelse:
if ( isOnDiv===true ) {
// do something
} else {
return;
}
Well, that's kinda of what events are for. Simply attach an event listener to the div you want to monitor.
var div = document.getElementById('myDiv');
div.addEventListener('mouseenter', function(){
// stuff to do when the mouse enters this div
}, false);
If you want to do it using math, you still need to have an event on a parent element or something, to be able to get the mouse coordinates, which will then be stored in an event object, which is passed to the callback.
var body = document.getElementsByTagName('body');
var divRect = document.getElementById('myDiv').getBoundingClientRect();
body.addEventListener('mousemove', function(event){
if (event.clientX >= divRect.left && event.clientX <= divRect.right &&
event.clientY >= divRect.top && event.clientY <= divRect.bottom) {
// Mouse is inside element.
}
}, false);
But it's best to use the above method.
simply you can use this:
var element = document.getElementById("myId");
if (element.parentNode.querySelector(":hover") == element) {
//Mouse is inside element
} else {
//Mouse is outside element
}
Improving using the comments
const element = document.getElementById("myId");
if (element.parentNode.matches(":hover")) {
//Mouse is inside element
} else {
//Mouse is outside element
}
$("div").mouseover(function(){
//here your stuff so simple..
});
You can do something like this
var flag = false;
$("div").mouseover(function(){
flag = true;
testing();
});
$("div").mouseout(function(){
flag = false;
testing();
});
function testing(){
if(flag){
//mouse hover
}else{
//mouse out
}
}
I have a draggable function in jquery to make it so I can drag and move elements on a div. Sometimes, when dragging the mouse comes off the div and I am not able to put back down the element.
I'm trying to add a keydown event for the escape button or something so that when pressed, the same thing happens on .on("mouseup", function(event) {
I've tried doing .on("mouseup keydown", function(event) { but it doesn't catch any keys that are being pressed.
Does anyone have any ideas on how I can cancel the drag? Either by a keydown or even on a mouseup regardless of if the mouse is on the div or not that is being dragged?
Just to be clear, the problem I am having is sometimes I will be dragging the element, I will mouseup but the mouse wasn't on the element when mouseup was called. Therefore, the element is still dragging and I no longer have my finger on the mouse and I have no way to stop the element from dragging to get it back on the document.
EDIT: Here is a jsfiddle, notice I am trying to get this to work on a scaled container. youtube video showing drag glitch
(function($) {
$.fn.drags = function(opt, callback) {
opt = $.extend({
handle: "",
cursor: "move"
}, opt);
if (opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
if (opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
$drag.css('z-index', 1000).parents().on("mousemove", function(e) {
$('.draggable').offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
}).on("mouseup", function() {
$(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault();
}).on("mouseup", function(event) {
if (opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
if (typeof callback == 'function') {
alert("this is a callback");
}
});
}
})(jQuery);
Here are a few things that might work:
Instead of listening for mouseup on the target element, listen for it on document.body. That way it will fire regardless of if the cursor is over the dragged element.
If you want to cancel the drag when the cursor wanders out of the page, add an event listener for mouseleave on document.body and use it to cancel the drag.
If you make a code-pen (or similar) test case, I will be happy to dig into the code.
Edit__
Handling mouseleave on the document prevents it from getting stuck in a draggable state. It also fixes the multiplied movement that you were seeing.
$(document.body).on('mouseleave', function(){
$el.removeClass('draggable').css('z-index', z_idx);
});
Edit2__
Previous JSFiddle was incorrect.
https://jsfiddle.net/spk4523t/6/
I have a javascript bookmarklet I put together to make an arduous task a little more bearable. Essentially I am going through hundreds of pages of training material and making sure that all of it has been properly swapped from Helvetica to Arial. The bookmarklet code is below, but a quick breakdown is that it creates a mousemove event listener and a small, absolutely positioned div. On mousemove events, the div moves to the new mouse position (offset by 10px down and right), gets the element under the mouse with elementFromPoint and shows the font-family property for that element. oh and it changes it's background color based on whether Arial appears within the property.
var bodyEl=document.getElementsByTagName("body")[0];
var displayDiv=document.createElement("div");
displayDiv.style.position="absolute";
displayDiv.style.top="0px";
displayDiv.style.top="0px";
bodyEl.appendChild(displayDiv);
function getStyle(el,styleProp) {
var camelize = function (str) {
return str.replace(/\-(\w)/g, function(str, letter){
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
function getTheElement(x,y) {return document.elementFromPoint(x,y);}
fn_displayFont=function displayFont(e) {
e = e || window.event;
var divX=e.pageX+10;
var divY=e.pageY+10;
var font=getStyle(getTheElement(e.pageX,e.pageY),"font-family");
if (font.toLowerCase().indexOf("arial") != -1) {
displayDiv.style.backgroundColor = "green";
} else {
displayDiv.style.backgroundColor = "red";
}
displayDiv.style.top= divY.toString() + "px";
displayDiv.style.left= divX.toString() + "px";
displayDiv.style.fontFamily=font;
displayDiv.innerHTML=font;
}
window.addEventListener('mousemove', fn_displayFont);
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
window.removeEventListener('mousemove', fn_displayFont);
bodyEl.removeChild(displayDiv);
}
};
(for the record, I stole the style determining code from an answer here on SO, but I lost the tab not long after. Thanks, anonymous internet guy!)
So this all works great - UNTIL I try to hover over a part of the page that is scrolled down from the top. The div sits at where it would be if I had the mouse on the very bottom of the screen while scrolled to the top of the page, and if I scroll down far enough firebug starts logging that e.pageX is undefined.
Any ideas?
Alrighty then, figured it out. I saw http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/276742/elementfrompoint-problems-when-window-has-been-scrolled- and thought it meant I had to minus the pageoffset straight away from the e.pageX/Y values, before I used it to calculate the div position or anything else, this just broke everything for me so I assumed it must have been unrelated - not so!
From what I now understand the elementFromPoint method takes a point relative in the current view of the browser, which is to say, base on the top left corner of what can currently be seen, not the page as a whole. I fixed it by just taking the offset from the X and Y values when I was getting the element. The now-working code is below.
var bodyEl=document.getElementsByTagName("body")[0];
var displayDiv=document.createElement("div");
displayDiv.style.position="absolute";
displayDiv.style.top="0px";
displayDiv.style.top="0px";
bodyEl.appendChild(displayDiv);
function getStyle(el,styleProp) {
var camelize = function (str) {
return str.replace(/\-(\w)/g, function(str, letter){
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el,null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
function getTheElement(x,y) {return document.elementFromPoint(x,y);}
fn_displayFont=function displayFont(e) {
e = e || window.event;
var divX=e.pageX + 10;
var divY=e.pageY + 10;
var font=getStyle(getTheElement(e.pageX - window.pageXOffset,e.pageY - window.pageYOffset),"font-family");
if (font.toLowerCase().indexOf("arial") != -1) {
displayDiv.style.backgroundColor = "green";
} else {
displayDiv.style.backgroundColor = "red";
}
displayDiv.style.top= divY.toString() + "px";
displayDiv.style.left= divX.toString() + "px";
displayDiv.style.fontFamily=font;
displayDiv.innerHTML=font;
}
document.addEventListener('mousemove', fn_displayFont);
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) {
window.removeEventListener('mousemove', fn_displayFont);
bodyEl.removeChild(displayDiv);
}
};
Hmm instead of checking with the mouse, why not just check every leaf node? If any leaf node has a font-family of arial, then it should indicate that one of its ancestors has a font-family of Arial.
First you need to get jquery onto the page. Try this bookmarklet
Then run this code:
(function(){
var arialNodes = $('div:not(:has(*))').filter(function(){
return $(this).css('font-family').toLowerCase().indexOf("arial") != -1;
});
})();
The arialNodes variable should contain every leaf node that has a font-family of 'Arial'. You can then use this to figure out which parent element has the declaration.
Or if you just want to see if a page is compliant or not, just check the length.
Updated
Updated to reflect comments below
(function() {
var arialNodes = $('*:not(:has(*))', $('body')).filter(function() {
return $(this).css('font-family').toLowerCase().indexOf("arial") === -1;
});
var offendingParents = [];
arialNodes.each(function(){
var highestOffendingParent = $(this).parentsUntil('body').filter(function(){
return $(this).css('font-family').toLowerCase().indexOf("arial") === -1;
}).last();
if(offendingParents.indexOf(highestOffendingParent) === -1){
offendingParents.push(highestOffendingParent);
}
});
})();
Why does FramedCloud popup steal click events inside the popup?
current_popup = new OpenLayers.Popup.FramedCloud(
"featurePopup",
f.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(0,0),
"<b>Наблюдения</b><br/>" + $.map(features, function(fe) { return fe.attributes.description; }).join('<br/>'),
null, false, null);
map.addPopup(current_popup, true);
$('#map').on('click', function() { console.log('test'); return false; });
Captures click events always except when I click a link inside a popup. The popup and the anchors are descendants of #map.
Click the map => callback is fired
Click a marker => callback is fired, popup is shown
click inside popup (not on a link) => callback is not fired
click a link inside a popup => same way, nothing happens
The code in that part of OL is quite obscure.
Why does it catch clicks inside the popup? How do I take them back?
edit: debugging deeper in OL: this function is fired:
bindAsEventListener: function(func, object) {
return function(event) {
return func.call(object, event || window.event);
};
event.target is the anchor, exactly what I expect:
<a class="edit-card-link" href="/form/?id=806">...</a>
func is:
handleBrowserEvent: function(evt) {
var type = evt.type, listeners = this.listeners[type];
if (!listeners || listeners.length == 0) {
return;
}
var touches = evt.touches;
if (touches && touches[0]) {
var x = 0;
var y = 0;
var num = touches.length;
var touch;
for (var i = 0; i < num; ++i) {
touch = touches[i];
x += touch.clientX;
y += touch.clientY;
}
evt.clientX = x / num;
evt.clientY = y / num;
}
if (this.includeXY) {
evt.xy = this.getMousePosition(evt);
}
this.triggerEvent(type, evt);
}
this is OpenLayers.Event class instance, evt.target is still that anchor, listeners contains 1 listener:
function (evt){OpenLayers.Event.stop(evt,true);}
Is this the reason? How do I take it out?
If you want to stop the popup from stealing a mouse event then in your CSS you could, as suggested here, set the pointer-events: none; for the id corresponding to the popup id given at its creation. Thus in your case it would be:
#featurePopup{
pointer-events: none;
}
It worked like a charm for me when I wanted to avoid flickering of a popup which I showed on mouseover.
I did it another way. I let OpenLayers capture the event, but before that I trigger another one.
$('a', current_popup.contentDiv).on('click', function(evt) {
var jtarget = $(evt.target);
hide_popup(); // hides OpenLayers popup
$(document).trigger('edit_link_clicked', {
feature: features[jtarget.parent().find('a').index(jtarget)],
cluster: f,
url: jtarget.attr('href')
});
return false;
});
Here's the JSFiddle.
I'm trying to make mouseenter work on Chrome, Firefox, etc. using the following function:
var addMouseenter = (function () {
var contains = function (parent, elem) {
return parent.contains ? parent.contains(elem) :
!!(parent.compareDocumentPosition(elem) & 16);
},
wrap = function (elem, method) {
return function (e) {
if (elem === e.target && !contains(elem, e.relatedTarget)) {
method.call(elem, e);
}
};
};
return function (elem, listener) {
var listener2 = wrap(elem, listener);
elem.addEventListener('mouseover', listener2, false);
};
}());
Everything worked fine until I ran into this specific situation:
Element A has one of these custom mouseenter listeners
Element A contains Element B
Element B is right up against the edge of Element A
You enter Element A at that same edge
My expectation was that the mouseover event would be triggered on Element B and bubble up to Element A. However, that does not appear to be the case. I tested with Chrome 13 and Firefox 3.6 and got the same result. Did I mess something up?
If you don't oppose using jQuery:
$(document).ready(function() {
$('#first').mouseover(function (e) {
if ($(e.target).attr('id') != 'second') {
alert('hello');
}
});
});
Tried that in your JSFiddle and it works:
when you enter the green square it doesn't fire; when you enter red square from outside it fires; when you enter red square from green square it fires. That's what you wanted right?
new JSFiddle
Or keeping your javascript approach:
// Misc set-up stuff
var greet = function () { alert('Hi, my name is "' + this.id + '."'); },
first = document.getElementById('first'),
second = document.getElementById('second');
// The Actual Function
var addMouseenter = (function () {
var contains = function (parent, elem) {
return parent.contains ? parent.contains(elem) :
!!(parent.compareDocumentPosition(elem) & 16);
},
wrap = function (elem, method) {
return function (e) {
//if (elem === e.target && !contains(elem, e.relatedTarget)) {
if (elem === e.target && (e.target != second)) {
method.call(elem, e);
}
};
};
return function (elem, listener) {
var listener2 = wrap(elem, listener);
elem.addEventListener('mouseover', listener2, false);
};
}());
// GOGOGO
addMouseenter(first, greet);
http://jsfiddle.net/AUc88/
The reason my custom function wasn't firing is because it didn't work.
I updated the fiddle showing that all is as it should be.
My mistake was only checking to see if e.target was the same as the element I had attached the listener to. What I needed to be checking was if they were the same or if e.target was a child of the element.
When you mouse over the two squares really quickly, it only registers the mouseover event on the inner one, and because my listener was attached to the outer one, the elem === e.target test was failing.
So I changed the if code in the wrap function to this:
if ((elem === e.target || contains(elem, e.target)) &&
!contains(elem, e.relatedTarget)) {
e.stopPropagation();
method.call(elem, e);
}