I want to create a div with an onclick event handler like
element.innerHTML = '<div onclick="somefunction(e, 10)"></div>';
where e would be the event object and 10 is some other random argument. I can't seem to find a way to do this. Is it possible?
Note that I do not want to create and then append the child to the parent element separately.
For inline handlers like that you should be able to pass the event object directly if you spell it out in full rather than e (in your actual function definition you can call the corresponding parameter anything you like):
element.innerHTML = '<div onclick="somefunction(event, 10)"></div>';
For other event registration techniques there are other ways to get access to the event object, but inline is kind of a special case that should be the same in all browsers.
For more detail see this page: http://www.quirksmode.org/js/events_access.html
Related
I am attempting to fire off an AJAX call based on the onclick event for a google map integration. The info_window_content function seen here: http://jsfiddle.net/6xw2y/ is the call to create the divs that reside within the map itself.
The "v" variable does in fact contain a store_id. So in the opening line of that function, it has the following:
var info_window_string = "<div class='maps_popup' id="+v.id+">";
Now I have an onclick event that I have duplicated and modified. The first onclick event works just fine and refreshes the panel as it should. The second onclick event doesn't work and the code for that is below:
$("#div").click(function(){
var store_id = $(this).find("div").attr("id");
var pathname = "ajax=1&store_id="+store_id+"&action=get_nearby_stores&distance="+distance+"&lat="+lat+"&lng="+lng+"&products="+$('#edit-products').val();
$("#pocp_content").load("file1.php?" + pathname);
});
That doesn't seem to work. I've also tried changing the div tag to be like this:
$("div").click(function(){
Which still doesn't work. As an added side hint. At one point I was able to get it to refresh but it was passing map-container as the store_id, instead of the id itself.
What am I missing here?
I agree with Joke_Sense10,
but I think you're probably not binding the event to the right DOM element.
Try to open up the developer console in your browser (while being on the side you develop this code for), and enter $("#div") to see if the element it returns is the one you expect. You can also use console.log($("#div")) in the code for that.
answer in comments
For a larger number of elements, always use .on() method as the latter will bind an single event listener on one of the topmost nodes in the DOM tree.
$(document).on("click","#"+v.id, function(){
I have a difficult question.
events = $._data( element[0], 'events');
$.each(events, function(_event_name, _event_handler){
var _handlers=[];
for(var i= 0 ;i < _event_handler.length;i ++)
_handlers.push(_event_handler[i].handler);
event_handler.push(_handlers);
event_name.push(_event_name);
});
element.off();
I have above code to successfully read all what event name and its handler assigned for a element.
Then I save each of them into event_name and event_handler before I turn the events off;
However, this method is only work on when the events are directly assigned for the element.
When the events are delegated assigned, how can I develop the code to do that?
$(document).on('click', '#id', handler);
Above code will only show the event name click and its handler handler, but no the name or selector of the delegate assigned element #id.
I want to know how can I read the name of delegate assigned element out that I can do delegate off or all the events on parent will be off.
Thank you very much for your advice.
The selector is stored in the object within the array of click events under selector as seen below.
It seems that the selector field is empty when you look at click events bound directly to the element.
I would assume you can build a check into your code somehow. Mind you, the selector property is apparently only intended for internal use as I had a question myself in the past about it, when I found it contained occasionally strange values.
To that end, though it might work for you, I do not know how reliable it is or even if it is going to be used in future versions of jQuery.
However, if you only use it for delegate events you might find it contains useful values but keep an eye on it.
If you take a look at this fiddle in Chrome and click the Trigger text with the js console open you will see this:
What is the reason of all those with blocks and what is it's value?
It looks to me as if it's how the browser creates a function for the event handler when it's specified as an HTML "onclick" attribute. I think what that does is:
make an event handler function with a single parameter for the event object and your supplied code;
make properties of the element (the <a> tag), an empty object (?), and the document object appear to be available symbols for the code in that function.
That is, this[0] is the <a> element itself, this[1] looks like an empty Object instance, and this[2] is the document object. What this means is that in code you write as part of an "onfoo" event handler attribute (and not code in any ordinary event handler bound from straight JavaScript code), it's possible to refer to the properties of the target element (the element for which you're setting the attribute) and the properties of the document element as if they were present in the scope chain.
If you change the code a little:
$('<a href=# onclick="console.log(baseURI);"> ...
then you get the value of the "baseURI" property of the <a> element. No need to prefix "baseURI" with anything that explicitly refers to the DOM node for the <a> element; it's just "there" as if it were declared with var in some enclosing scope.
(checking w3c specs now ...) edit — I haven't found anything that stipulates what symbols are supposed to be available to the script code in event handlers. This is really weird.
edit again — Firefox seems to do the same thing, though I don't see the explicit with statements anywhere.
with moves it's argument on top of scope stack. So it's even higher than global object, function params, etc. No idea why they use it. Perhaps it is a generated code.
If I have some HTML like this:
<a onmouseover='SetTopLeft(this);'href='#'>Click me!</a>
Can I get both the object AND the event in the function? So, for example, can I have a method signature like this?
function SetTopLeft(e, o)
...where e is the event and o is 'this'? I may actually not need the object, but I think I probably DO need the event. I wouldn't mind understanding a little better how this works in JavaScript - i.e., when/how can I pass an event and when/how can I pass the calling object? Can I choose which to pass? Can I pass both?
Basically, what I really need to do is get the mouse coordinates within the DIV within which the anchor is located (even if that DIV is only a portion of a web page and whether or not the browser is full-screen) and I'm having a terrible time getting it done. Most of the examples I have seen for getting these coordinates within some element use the event and the pageX and pageY properties of that event.
By the way, this must work in IE 6 onward. Firefox would be good, too. Others are not necessary.
Yes, in the inline code this refers to the HTML DOM object for the element, and event refers to the event object. So you could do the following:
HTML
<a onmouseover='SetTopLeft(event, this);' href='#'>Click me!</a>
JavaScript
function SetTopLeft(e, obj) {...}
In general you should avoid using inline event handlers. It mixes representation (HTML) with logic (JavaScript). quirksmode.org offers a nice collection of articles of all there is to know about event handling.
Since inside an event handler, this typically refers to element the handler is bound to, you can also explicitly set this to the element and pass the event object as first argument:
<a onmouseover='SetTopLeft.call(this, event);'href='#'>Click me!</a>
See .call() [MDN] for more information.
Besides that, if your link is not linking to anything, better use a simple span element or a button and style it accordingly.
I am doing browser automation using C#, and I would like to modify or possibly just eliminate event handlers on some of the html elements in webpages that I am looking at. E.g., suppose there is a button there which might (or might not) have an attached onClick event. How do I go about:
- finding out if there are any event handlers attached to onClick for it?
- removing them?
Replacing element with its own clone should effectively discard all of its event listeners (well, technically listeners are still on an element, but since an element is replaced with its own clone, it looks as if listeners were simply removed):
el.parentNode.replaceChild(el.cloneNode(true), el);
Unfortunately, this won't work in IE, since IE erroneously transfers event listeners of an element on clone. To work around that you can reassign innerHTML of element's parentNode:
el.parentNode.innerHTML = el.parentNode.innerHTML;
Note that this will not only remove event listeners of an element, but also listeners of all of element's siblings.
Alternatively, you can work around IE issue by reassigning outerHTML of an element:
el.outerHTML = el.outerHTML;
This depends on how the event handlers have been attached to the element.
If they are attached using addEventListener or one of the proprietary addWhatever listener methods, there is no way to list them.
If they are attached by modifying the event property, ie. node.onclick = whatever, then you can read the value of the property to get the function and it'll work the same as any other JS func.
There is a third way too:
You can override the default addEventHandler/addListener behavior if the code you automate uses those. By doing this, you can replace the default behavior by one which pushes each handler into an array, which you can then loop over yourself.
The following code might work:
var oldAddEventListener = HTMLElement.prototype.addEventListener;
HTMLElement.prototype.addEventListener = function(event, handler, bubbling) {
/* do whatever you want with event parameters */
oldAddEventListener.call(this, event, handler, bubbling);
}
As far as I know, it's not currently possible to use javascript to get all the event handlers attached to an element.
See this link for more info:
http://www.howtocreate.co.uk/tutorials/javascript/domevents