How to execute a function when clicking an area inside an object? - javascript

I created an object with map Areas by using DOM-Elements. Now I want to execute a function when clicked on an area(coordinates). I think I also Need to check the area if it is clicked or not ? Also I think I'm missing something on the DOM-Element.
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
onclick: doSomething, // ???
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
areaElem.onclick = doSomething; ? ? ?
if (element.captureEvents) element.captureEvents(Event.CLICK); ? ? ?
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
if (!e) var e = window.event
e.target = ... ? ?
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}

See the comments I added to your code ;)
var _images = { //Object-MapArea
start: {
path: 'start.jpg',
areas: [{
coords: '18,131,113,140',
text: 'Homepage',
clickHandler: doSomething // I changed the name to avoid confusion but you can keep onclick
}]
},
}
// ..... there is more code not shown here
//Creating DOM-Elements
var areaElem = document.createElement('AREA');
// Set attributes
areaElem.coords = area.coords;
areaElem.setAttribute('link', area.goto);
areaElem.setAttribute("title", area.text);
areaElem.setAttribute("shape", "rect");
// Add a listener on click event (using the function you defined in the area object above)
areaElem.addEventListener('click', area.clickHandler);
// Add your other click handler
areaElem.addEventListener('click', onArea_click);
_map.appendChild(areaElem);
function doSomething(e) {
// Get the area clicked
var areaClicked = e.target;
// I dont understand the following code...
var r = confirm("Data will get lost!");
if (r == true) {
window.open("homepage.html", "_parent");
} else {
window.open(" ", "_parent"); // here I want to stay in the current pictures. I mean the current object map area. But how can I refer to it so it stays there ?
}
}
Hope it helps ;)

I think I also Need to check the area if it is clicked or not
You are creating an element areaElem and attaching event to the same dom.
So there may not be need of any more check
You may not need to add both onclick & addEventListner on same element and for same event. Either onclick function or addEventListener will be sufficient to handle the event.
areaElem.onclick = function(event){
// Rest of the code
// put an alert to validate if this function is responding onclick
}
areaElem.addEventListener('click', onArea_click);
function onArea_click(){
// Rest of the code
}

Related

Pass JS variable across mouseenter event from jquery in angular2 app

I have trouble witch function below:
inactive() {
let target = $('.album__item--cover-container');
var leave:boolean;
target.mouseleave(function() {
leave = true;
console.log("LEAVE MOUSEENTER: ", leave);
});
console.log("LEAVE: ", leave);
if (leave) {
console.log("LEAVE CONDITION: ", leave);
this.flyOut = 'inactive';
}
console.log(this.flyOut);
}
I don't know wht log "LEAVE MOUSEENTER" is true, and after exit from mouse event log "LEAVE" is undefined. I can't declate this.flyOut = true in this event function. Please someone helop me, and explain why this behaviour goes that way?
Regards
Greg
I think your issue is because you are not doing anything inside the callback of the mouse leave event.
This is only run once when inactive() is invoked.
if (leave) {
console.log("LEAVE CONDITION: ", leave);
this.flyOut = 'inactive';
}
I'm assuming you are trying to set some state on mouseleave, and you then want to check if this.flyOut is inactive?
(function ($) {// just some wrapper
let flyOut = 'inactive'
const target = $('.album__item--cover-container'); // Use const if you know it wont change
const check = $('.check-button-class-thing');
target.mouseleave(function() {
flyOut = 'inactive'
});
target.mouseenter(function() {
flyOut = 'active'
});
check.click(function() {
console.log(inactive()); // Is it inactive or not
});
function inactive() {
return flyOut === 'inactive' ? true : false;
}
})(jQuery);
I'm making assumptions here on your use case but I hope this helps. The code itself is not very useful as it depends on where the .check-button-class-thing is nested but its just an example.
The
if (leave) {
is out of the mouseleave function callback. So when inactive() is called the first time, leave has been declared without any default value (it's undefined). And the if is called.
It will only be true when the mouseleave event is called.

How to assign event handlers to multiple elements (colorPicker)

I'm trying to find a way to assign event handlers to each box that I create dynamically. At the moment the user can click "Add above" or "Add below" and 2 rows of boxes will appear wherever they clicked.
I'm trying to make it so that when the user clicks on a specific square, a colorPicker will pop up and that specific square's color can be changed.
However, my program is a bit buggy, it only works for the first square that the user clicks on and the colorPicker never pops up again.
Does anyone know how I can go about fixing this or if there is a better alternative?
My code:
http://codepen.io/anon/pen/bwBRmw
var theParent = document.querySelector(".container");
theParent.addEventListener("click", doSomething, false)
//var picker = new Picker()
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
var picker = new Picker(k)
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}
I noticed in your CodePen that you didn't post the full code for doSomething. You have a problem because the picker variable is local to the function. If the code execution doesn't land inside the IF-statement, the picker variable is never created. Simply uncomment the code declaring the picker variable outside the function, and remove the var directive from in front of the line of code where you instantiate a new picker. Furthermore, you need to reset the "parent" element of the picker, since there is only one picker on the page: picker.settings.parent = k;
var picker = null; // Initialize global variable
function doSomething(e) {
console.log("gets inside doSomething")
console.log(e.target)
console.log(e.currentTarget)
if (e.target !== e.currentTarget) {
var clickedItem = e.target.id;
console.log("Hello " + clickedItem);
var k = document.getElementById(clickedItem)
// Reference the global "picker" variable
if (!picker) {
picker = new Picker(k)
} else {
// Set the "parent" element of the picker to the newly clicked element
picker.settings.parent = k;
}
picker.show();
}
picker.on_done = function(colour) {
$(k).css('background-color',colour.rgba().toString());
picker.hide()
}
//e.stopPropagation();
}

OpenLayers - how to use single and double click event on feature

I am using Opnelayers control for selection of feature
OpenLayers.Control.SelectFeature
when I triggered the single click event then feature get selected and its working fine for me. Now I want to use double click event for another operation.
I have get the idea from this link feature to have both a single click and double click event?
I have used the same code and both click events working fine but I cannot get the feature on which click event performed. This is the code
handler = new OpenLayers.Handler.Click(
select,
{
click: function(evt)
{
var feature = this.layer.getFeatureFromEvent(evt);
console.log(feature); // output null
if(this.layer.selectedFeatures){
this.unselect(this.layer.selectedFeatures[0]);
}
},
dblclick: function(evt)
{
// some other operation
}
},
{
single: true,
double: true,
stopDouble: true,
stopSingle: true
}
);
handler.activate();
Any idea which thing is missing in this code?
Thank you
For The Above Question this might solve your answer with few changes
var handler = new OpenLayers.Handler.Click(
layerName, {
click: function(evt) {
console.log('click has triggered');
var feature = layerName.getFeatureFromEvent(evt);
}
,dblclick: function(evt) {
console.log('dblclick has triggered');
}
},{
single: true
,double: true
,stopSingle: true
,stopDouble: true
}
);
handler.activate();
I have been in a similar situation and used the getClosestFeatureToCoordinate method of the layer source. The code would be something like:
click: function(evt) {
var coord = evt.coordinate;
var source = this.layer.getSource();
var feature = source.getClosestFeatureToCoordinate(coord);
// do something with feature
}
I have done in this way.
click: function(evt) {
var pos = map.getLonLatFromPixel(xy);
var point = new OpenLayers.Geometry.Point(pos.lon, pos.lat);
var list = $.map(this.layer.features, function(v) {
return v.geometry.distanceTo(point);
}); // get distance of all features
var min = (Math.min.apply(null, list)); // minimum distance
var closest = $.map(this.layer.features, function(v) {
if (v.geometry.distanceTo(point) == min)
return v;
});
feature = closest[0];
}

implementing a callback in TimelineJS

In TimelineJS I want to implement a callback that would be fired every time the slide (the main panel in the center) changes whether that change happens by clicking on the "right" or "left" buttons on the sides, or by clicking on an event in the timeline in the bottom time panel. I could not find any information on such a callback other than a reference to it in Issue 82 from a year ago.
Suggestions on how to start with this? (In other words, I have no idea even where to begin).
Timeline JS fires an event whenever it is updated, the code is at line 5274 of the latest version:
function upDate() {
config.current_slide = current_slide;
VMM.fireEvent(layout, "UPDATE");
};
The code for fireEvent is:
VMM.fireEvent = function(element, the_event_type, the_data) {
var e;
var _event_type = "click";
var _data = [];
if (the_event_type != null && the_event_type != "") {
_event_type = the_event_type;
}
if (the_data != null && the_data != "") {
_data = the_data;
}
if( typeof( jQuery ) != 'undefined' ){
jQuery(element).trigger(_event_type, _data);
//return e;
}
};
Then important part there is:
jQuery(element).trigger(_event_type, _data);
So, all you need to do is figure out what element layout is, so I would temporatily edit the upDate function to:
function upDate() {
console.log($(layout).attr('id') + ' : ' + $(layout).attr('class'));
config.current_slide = current_slide;
VMM.fireEvent(layout, "UPDATE");
};
And see what it logs for the class / id of the element. Then, say it comes back with the class being 'timeline', for example, you would write something like this:
$('.timeline').on("UPDATE", function() {
your_function_that_does_whatever_you_need();
});

Detect element style change in chrome

I'm trying to find a way to detect changes to the element style but I haven't had much luck. The code below works on a new property I define like tempBgColor but I cannot override/shadow an existing property like color. I know jquery has a watch function, but it only detects changes from the jquery api but not directly changing the value of a style something like elem.style.color.
var e = document.getElementById('element');
e.style.__defineGetter__("color", function() {
return "A property";
});
e.style.__defineSetter__("color", function(val) {
alert("Setting " + val + "!");
});
Any pointers?
You should be able to do this with a MutationObserver - see demo (Webkit only), which is the new, shiny way of getting notified about changes in the DOM. The older, now deprecated, way was Mutation events.
Demo simply logs in the console the old and new values when the paragraph is clicked. Note that the old value will not be available if it was set via a non-inline CSS rule, but the change will still be detected.
HTML
<p id="observable" style="color: red">Lorem ipsum</p>​
JavaScript
var MutationObserver = window.WebKitMutationObserver;
var target = document.querySelector('#observable');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log('old', mutation.oldValue);
console.log('new', mutation.target.style.cssText);
});
});
var config = { attributes: true, attributeOldValue: true }
observer.observe(target, config);
// click event to change colour of the thing we are observing
target.addEventListener('click', function(ev) {
observable.style.color = 'green';
return false;
}, false);
Credit to this blog post, for some of the code above.
With Chrome's Developer Tools open, you can find the element whose style's change you're interested in, right click it, select "Break on..." and "Attributes modifications".
here is a naive implementation using setTimeout with undescorejs.
The only way to find out which change was made is to iterate through the style object properties.
Here is the live example
$( function () {
var ele = document.getElementById('ele'),
oldStyle = {};
function checkEquality() {
style = _.clone(ele.style);
if (!_.isEqual(style, oldStyle)) {
console.log('Not equal');
oldStyle = _.clone(style);
} else {
console.log('Equal');
}
_.delay(checkEquality, 2000);
}
checkEquality();
$('a#add_prop').on('click', function () {
var props = $('#prop').val().replace(/ /g, '').split(':');
console.log(props);
$(ele).css(props[0], props[1]);
});
$('#prop').on('keydown', function (e) {
if (e.keyCode == 13) {
$('a#add_prop').trigger('click');
}
});
});

Categories

Resources