How to change the cursor on hover in openlayers 3? - javascript

I managed to add interactivity to a feature layer added from a remote GeoJSON resource. When I click on a feature I get its ID, fire an AJAX request and display some relevant info about the feature, on the page outside of the map area.
I used a Select interaction.
I would like to make it even clearer to the user that he can click on the features on the map. Is there any way I can change the mouse cursor to "cursor" of "hand" when the mouse hovers a feature contained in a ol.layer.Vector ?
I couldn't find anything in the doc, on this site or by googling.

It can be done as well without jQuery:
map.on("pointermove", function (evt) {
var hit = this.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return true;
});
if (hit) {
this.getTargetElement().style.cursor = 'pointer';
} else {
this.getTargetElement().style.cursor = '';
}
});

Here is another way to do it:
map.on('pointermove', function(e){
var pixel = map.getEventPixel(e.originalEvent);
var hit = map.hasFeatureAtPixel(pixel);
map.getViewport().style.cursor = hit ? 'pointer' : '';
});

If that doesn't work, try a combination of the 2, seemed to work for my vector popup...
var target = map.getTarget();
var jTarget = typeof target === "string" ? $("#" + target) : $(target);
// change mouse cursor when over marker
$(map.getViewport()).on('mousemove', function (e) {
var pixel = map.getEventPixel(e.originalEvent);
var hit = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
return true;
});
if (hit) {
jTarget.css("cursor", "pointer");
} else {
jTarget.css("cursor", "");
}
});

Thanks to the example link provided by Azathoth in the comments I worked a solution out:
using OL3 pointermove event
using jQuery to get the target element and change its cursor style
Here is the code :
var cursorHoverStyle = "pointer";
var target = map.getTarget();
//target returned might be the DOM element or the ID of this element dependeing on how the map was initialized
//either way get a jQuery object for it
var jTarget = typeof target === "string" ? $("#"+target) : $(target);
map.on("pointermove", function (event) {
var mouseCoordInMapPixels = [event.originalEvent.offsetX, event.originalEvent.offsetY];
//detect feature at mouse coords
var hit = map.forEachFeatureAtPixel(mouseCoordInMapPixels, function (feature, layer) {
return true;
});
if (hit) {
jTarget.css("cursor", cursorHoverStyle);
} else {
jTarget.css("cursor", "");
}
});
Here is the link to the example on OpenLayers site : http://openlayers.org/en/v3.0.0/examples/icon.html

For me it worked like this:
map.on('pointermove', function(e) {
if (e.dragging) return;
var pixel = e.map.getEventPixel(e.originalEvent);
var hit = e.map.forEachFeatureAtPixel(pixel, function (feature, layer) {
return true;
});
e.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
});
I also added a layer filter:
map.on('pointermove', function(e) {
if (e.dragging) return;
var pixel = e.map.getEventPixel(e.originalEvent);
var hit = e.map.forEachFeatureAtPixel(pixel, function (feature, layer) {
return layer.get('name') === 'myLayer';
});
e.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
});
I had to select a new solution as the old one I had use for the layer filter before did not work anymore:
var hit = e.map.hasFeatureAtPixel(e.pixel, function(layer){
return layer.get('name') === 'myLayer';
});

I did it with the following code:
var target = $(map.getTargetElement()); //getTargetElement is experimental as of 01.10.2015
map.on('pointermove', function (evt) {
if (map.hasFeatureAtPixel(evt.pixel)) { //hasFeatureAtPixel is experimental as of 01.10.2015
target.css('cursor', 'pointer');
} else {
target.css('cursor', '');
}
});

Another way (combined from parts of above answers, but even simpler):
map.on("pointermove", function (evt) {
var hit = map.hasFeatureAtPixel(evt.pixel);
map.getTargetElement().style.cursor = (hit ? 'pointer' : '');
});

Uncaught TypeError: Cannot set property 'cursor' of undefined.
Fixed with: map.getTargetElement()s.style.cursor = hit ? 'pointer' : ''; instead of map.getTarget().style.cursor = hit ? 'pointer' : '';

Simple way to get target element
var target = map.getTarget();
target = typeof target === "string" ?
document.getElementById(target) : target;
target.style.cursor = features.length > 0) ? 'pointer' : '';

If you guys are using Angular 2 you must use the following code:
this.map.on("pointermove", function (evt) {
var hit = evt.map.hasFeatureAtPixel(evt.pixel);
this.getTargetElement().style.cursor = hit ? 'pointer' : '';
});
If the map variable is a member class you refer to it as "this.map", instead if it is declared inside the current function it can be refered to as "map". But above all, you don't write
map.getTargetElement()
but you write
this.getTargetElement()

I tried to minimize pointermove event closure, by avoiding to update style when not necessary, because it calls so very often:
Example-1: uses jQuery:
var cursorStyle = "";
map.on("pointermove", function (e) {
let newStyle = this.hasFeatureAtPixel(e.pixel) ? "pointer" : "";
newStyle !== cursorStyle && $(this.getTargetElement()).css("cursor", cursorStyle = newStyle);
});
Example-2: no jQuery:
var cursorStyle = "";
map.on("pointermove", function (e) {
let newStyle = this.hasFeatureAtPixel(e.pixel) ? "pointer" : "";
if (newStyle !== cursorStyle) {
this.getTargetElement().style.cursor = cursorStyle = newStyle;
}
});

Easy way
map.on('pointermove', (e) => {
const pixel = map.getEventPixel(e.originalEvent);
const hit = map.hasFeatureAtPixel(pixel);
document.getElementById('map').style.cursor = hit ? 'pointer' : '';
});
}

Related

Getting error on vis js events

I'm building a timeline in vue.js app so I decided to use vis.js but I'm having problems with it when I want to add some events. First of all when i set #drop="myDropCallback()" and when I drop one item nothing happens so the function is not called but when i put #mouseOver="myDropCallback()" then it works, its strange.
Second when I'm doing the mouseOver event I want to get the event properties with this.$refs.timeline.getEventProperties(event) but I'm getting this error every time
Error in event handler for "click": "TypeError: Cannot read property 'center' of undefined"
and this error
Cannot read property 'center' of undefined
So does anyone know how to fix that? Or am I doing something wrong?
Template
<timeline v-if="items.length > 0" ref="timeline"
:items="items"
:groups="groups"
:options="options"
#drop="myDropCallback()">
</timeline>
Drop function
myDropCallback: function (event) {
console.log('value', this.$refs.timeline.getEventProperties())
},
Picture of timeline
Here's an excerpt from the vis.js source. You'll notice that the first thing it tries to do is to find the event's center value.
Timeline.prototype.getEventProperties = function (event) {
var clientX = event.center ? event.center.x : event.clientX;
var clientY = event.center ? event.center.y : event.clientY;
var x;
if (this.options.rtl) {
x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
} else {
x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
}
var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
var item = this.itemSet.itemFromTarget(event);
var group = this.itemSet.groupFromTarget(event);
var customTime = CustomTime.customTimeFromTarget(event);
var snap = this.itemSet.options.snap || null;
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
var time = this._toTime(x);
var snappedTime = snap ? snap(time, scale, step) : time;
var element = util.getTarget(event);
var what = null;
if (item != null) {
what = 'item';
} else if (customTime != null) {
what = 'custom-time';
} else if (util.hasParent(element, this.timeAxis.dom.foreground)) {
what = 'axis';
} else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {
what = 'axis';
} else if (util.hasParent(element, this.itemSet.dom.labelSet)) {
what = 'group-label';
} else if (util.hasParent(element, this.currentTime.bar)) {
what = 'current-time';
} else if (util.hasParent(element, this.dom.center)) {
what = 'background';
}
return {
event: event,
item: item ? item.id : null,
group: group ? group.groupId : null,
what: what,
pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
x: x,
y: y,
time: time,
snappedTime: snappedTime
};
};
So your issue is most likely due to not giving the method a valid event. I believe that this is because you aren't supplying any parameters to the getEventProperties method. I would try something like:
myDropCallback: function (event) {
console.log('value', this.$refs.timeline.getEventProperties(event))
},
Also, here is a good stack overflow post answered by one of the authors of vis.js: vis.js timeline how to add mouse over event to vis-item box-box

Event Listener on images ignored within modal window

I'm stuck as to why I can't get an AddEventListener click event to work on a set of images that appear in a modal. I had them working before before the modal aspect was involve, but I'm not sure that the modal broke the image click event either.
Here is the function in question, which is called within a massive document.addEventListener("DOMContentLoaded", function (event) function:
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.addEventListener('click', function (e) {
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
// console.log("childItems.forEach"); we get into here
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
// console.log("no tags selected"); we get to here
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
//console.log("before adding click to images"); we get here
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
attachClick();
//open a modal to show off the portfolio pieces for the selected client
var tingleModal = document.querySelector('.tingle-modal');
drawer.className = 'drawer';
var portfolioModal = new tingle.modal({
onOpen: function() {
if(tingleModal){
tingleModal.remove();
}
console.log('modal open');
},
onClose: function() {
console.log('modal closed');
//tingleModal.remove();
}
});
e.preventDefault();
portfolioModal.open();
portfolioModal.setContent(document.querySelector('.drawer-content').innerHTML);
});
});
};
And the specific bit that I'm having trouble with:
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
I tried removing the e.PreventDefault() bit but that didn't solve the issue. I know the images are being created, so the img variable isn't empty. I feel like the addEventListener is setup correctly. I also tried moving that bit up just under the img.src = item.thumb line, but no luck. For Some reason, the click event just will not trigger for the images.
So if I understand correctly, you have a modal that lies above the images (it has a higher z-index)? Well in this case the clicks are not reaching the images as they will hit the modal. You can pass clicks through elements that lie above by applying the css property pointer-events: none; to the modal, but thats somehow controversial to what a modal is intended to do.
Are the images present in the modal on DOMContentLoaded? You may be able to try delegating the handling of clicks to a parent element if that's the case.
You can try the delegation approach shown here: Vanilla JavaScript Event Delegation

check if images not exist on load change src

I'm trying to change my image size with javascript to be 500x375 instead of 130x98. If there is no 500x37 for that image, than I would like it to fallback to 130x98.
So far, I have the code below. It changes my images to 500x375, but the ones that do not have that size it appears broken instead of falling back to 130x98. Any ideas on how to fix this?
function ImageExists(selector) {
var imageFound = $(selector);
if (imageFound.height() === 0) {
console.log('no height');
return false;
}
return true;
}
$('div.photo > a > img').each(function(k, v) {
var x = v.src;
v.src = x.replace('130x98', '500x375');
if (!ImageExists(v)) {
console.log(v.src);
v.src = x.replace('500x375', '130x98')
}
});
You can try this code
$(document).ready(function(){
var src1 = '130x98';
var src2 = '500x375';
$('div.photo > a > img').each(function(){
var changeSrc;
var Image = $(this);
var GetSrc = $(this).attr('src');
Image.error(function() {
if(GetSrc.indexOf(src1) !== -1 ){
changeSrc = GetSrc.replace(src1 , src2);
}else if(GetSrc.indexOf(src2) !== -1 ){
changeSrc = GetSrc.replace(src2 , src1);
}
Image.attr("src", changeSrc);
});
})
});
DEMO
Are you missing semicolon in v.src = x.replace('500x375', '130x98'):in this line??
try putting alert();function in which line you doubted... alert(); will not work if any previous line is in error
$('div.photo > a > img').each(function (k, v) {
var x = v.src;
v.src = x.replace('130x98', '500x375');
if (!ImageExists(v)) {
console.log(v.src);
v.src = x.replace('500x375', '130x98');
};
How about trying the on error event instead of your ImageExists method:
$("img").error(function () {
//load in your default image dimensions.
});
When there's an error loading the image this will be triggered.
You might also want to unbind this event the first time it us run in case it continuously loops.

android detect touchstart on prototype js

i'm trying to make a magento extension work on android mobile devices. I bought this extension :
http://ecommerce.aheadworks.com/magento-extensions/layered-navigation.html
to get ajax layered navigation. It works well, but when it comes to android compatibility i get an issue on the range selector (slider selector, used for price range).
The feature works well on all device (ios included), but on android, i always got NaN instead of numbers values on the range selector. After digging the plugin's code, i found the origin in the javascript :
startDrag: function(event) {
var isLeftClick = Event.isLeftClick(event);
if (Prototype.Browser.IE) {
var ieVersion = parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5));
if (ieVersion > 8) {
isLeftClick = event.which === 1;
}
}
if (isLeftClick || event.type === 'touchstart') {
if (!this.disabled){
this.active = true;
var handle = Event.element(event);
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var track = handle;
if (track==this.track) {
var offsets = Position.cumulativeOffset(this.track);
this.event = event;
this.setValue(this.translateToValue(
(this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
));
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
} else {
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
if (this.handles.indexOf(handle)!=-1) {
this.activeHandle = handle;
this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
this.updateStyles();
var offsets = Position.cumulativeOffset(this.activeHandle);
this.offsetX = (pointer[0] - offsets[0]);
this.offsetY = (pointer[1] - offsets[1]);
}
}
}
Event.stop(event);
}
}
this line :
var pointer = [Event.pointerX(event), Event.pointerY(event)];
return a correct array of value (mouse coordinates) on all devices, except on android, where i get NaN. Is this a known bug of prototype.js, and can I bypass it ?
thanks,
Problem solved by digging the event object, then manually retrieving the X and Y pos (tested clientX, screenX and pageX) :
var pointer = [Event.pointerX(event), Event.pointerY(event)];
if(navigator.userAgent.match(/Android/i)){
pointer = [parseInt(event.targetTouches[0].clientX),parseInt(event.targetTouches[0].clientY)];
}
I had the same issue, I know this is an old thread but want to post my solution anyway. I needed to override the functions in swiper.js.
update: function(event) {
if (this.active) {
if (!this.dragging) this.dragging = true;
this.draw(event);
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
}
},
draw: function(event) {
var pointer = [Event.pointerX(event), Event.pointerY(event)];
if(navigator.userAgent.match(/Android/i)){
pointer = [parseInt(event.targetTouches[0].clientX),parseInt(event.targetTouches[0].clientY)];
}
var offsets = Position.cumulativeOffset(this.track);
pointer[0] -= this.offsetX + offsets[0];
pointer[1] -= this.offsetY + offsets[1];
this.event = event;
this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
if (this.initialized && this.options.onSlide)
this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
},
And this fixed my issue

DOM object only requires two clicks in Internet Explorer

I'm really struggling with the following bit of code. I'm still really new to using DOM with Javascript and this script is running flawlessly in FireFox, Chrome and Safari. In Internet Explorer it requires two clicks. If you visit the link in FireFox and then the same link in Internet Explorer you'll see that if you click a shape in FireFox it immediately shows the colour options if you do this in Internet Explorer it will not show the colour options until you've clicked on the shape twice or on a shape and then another shape. Can an IE, DOM, Javascript Ninja tell me what's wrong with the script that cause the need for two clicks in IE?
<?php
$swatches = $this->get_option_swatches();
?>
<script type="text/javascript">
document.observe('dom:loaded', function() {
try {
var swatches = <?php echo Mage::helper('core')->jsonEncode($swatches); ?>;
function find_swatch(key, value) {
for (var i in swatches) {
if (swatches[i].key == key && swatches[i].value == value)
return swatches[i];
}
return null;
}
function has_swatch_key(key) {
for (var i in swatches) {
if (swatches[i].key == key)
return true;
}
return false;
}
function create_swatches(label, select) {
// create swatches div, and append below the <select>
var sw = new Element('div', {'class': 'swatches-container'});
select.up().appendChild(sw);
// store these element to use later for recreate swatches
select.swatchLabel = label;
select.swatchElement = sw;
// hide select
select.setStyle({position: 'absolute', top: '-9999px'});
$A(select.options).each(function(opt, i) {
if (opt.getAttribute('value')) {
var elm;
var key = trim(opt.innerHTML);
// remove price
if (opt.getAttribute('price')) key = trim(key.replace(/\+([^+]+)$/, ''));
var item = find_swatch(label, key);
if (item)
elm = new Element('img', {
src: '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>swatches/'+item.img,
alt: opt.innerHTML,
title: opt.innerHTML,
'class': 'swatch-img'});
else {
console.debug(label, key, swatches);
elm = new Element('a', {'class': 'swatch-span'});
elm.update(opt.innerHTML);
}
elm.observe('click', function(event) {
select.selectedIndex = i;
fireEvent(select, 'change');
var cur = sw.down('.current');
if (cur) cur.removeClassName('current');
elm.addClassName('current');
});
sw.appendChild(elm);
}
});
}
// Hide Second Option's Label
function hideStuff(id) {
if (document.getElementById(id)) {
document.getElementById(id).style.display = 'none';
}
}
hideStuff("last-option-label");
function showStuff(id) {
if (document.getElementById(id)) {
document.getElementById(id).style.display = '';
}
}
function recreate_swatches_recursive(select) {
// remove the old swatches
if (select.swatchElement) {
select.up().removeChild(select.swatchElement);
select.swatchElement = null;
}
// create again
if (!select.disabled)
showStuff("last-option-label");
create_swatches(select.swatchLabel, select);
// recursively recreate swatches for the next select
if (select.nextSetting)
recreate_swatches_recursive(select.nextSetting);
}
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event, evt);
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
$$('#product-options-wrapper dt').each(function(dt) {
// get custom option's label
var label = '';
$A(dt.down('label').childNodes).each(function(node) {
if (node.nodeType == 3) label += node.nodeValue;
});
label = trim(label);
var dd = dt.next();
var select = dd.down('select');
if (select && has_swatch_key(label)) {
create_swatches(label, select);
// if configurable products, recreate swatches of the next select when the current select change
if (select.hasClassName('super-attribute-select')) {
select.observe('change', function() {
recreate_swatches_recursive(select.nextSetting);
});
}
}
});
}
catch(e) {
alert("Color Swatches javascript error. Please report this error to support#galathemes.com. Error:" + e.message);
}
});
</script>
console.debug has been deprecated. In the "function create_swatches(label, select)" where it is written "console.debug(label, key, swatches);" change it to "console.log(label, key, swatches);" or you can just delete that line of code all together....... thaterrorbegone

Categories