Can we name an event handler in Javascript? - javascript

I was messing around with jQuery and event handlers, when I noticed this:
That uses jQuery, and without it:
How does the popup get a bar saying jQuery? Do browsers have integrated jQuery support to detect that? Or is there some way to name event handlers? I want to have my event display some other text, like how jQuery does.
NOTE: I don't want to use jQuery, as I want to know how jQuery does it.

I am not sure about what you are trying to do, but in Javascript you can always name functions
Example:
function myEventHandler(event) {
alert('event handler');
}
myEventHandler is the name of the function.
Hope this helps a little,
best,
Carsten

You can have custom names for your events if you want. We can use the trigger function for the same purpose.
Suppose you want to raise myEvent on <div id="my_div">.
We can simply
$("#my_div").trigger('myEvent');
and have a listener for the event:
$("#my_div").on('myEvent', function(event){
//Event handler
});
You can find some good documentation here -
https://learn.jquery.com/events/introduction-to-custom-events/
And this SO answer covers it thoroughly -
Custom events in jQuery?

Related

Bind event to element using pure Javascript

I'm writing an API and unfortunately need to avoid any jQuery or 3rd party libraries. How exactly are the events bound to elements through jQuery?
jQuery example:
$('#anchor').click(function(){
console.log('anchor');
});
I'm close to writing a onClick attribute on the element out of frustration, but I would like to understand the link between the jQuery event and DOM element.
How exactly does the element know to fire a jQuery event when the markup itself is not changed? How are they catching the DOM event and overriding it?
I have created my own Observer handler but cant quite understand how to link the element to the Observer events.
Here's a quick answer:
document.getElementById('anchor').addEventListener('click', function() {
console.log('anchor');
});
Every modern browser supports an entire API for interacting with the DOM through JavaScript without having to modify your HTML. See here for a pretty good bird's eye view: http://overapi.com/javascript
You identify the element by id, in this case anchor, by:
var el = document.getElementById('anchor');
Then you need to assign your click event:
el[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);
And finally, the event's function would be something like:
function myClickFunc()
{
console.log('anchor');
}
You could simplify it or turn it into a one-liner if you do not need compatibility with older browsers and and a range of browsers, but jQuery does cross-browser compatibility and does its best to give you the functionality you are looking for in as many older browsers as it can.

How attach a click event with chaining method JavaScript

How does the click event work in JQuery?
I mean, I learned how to make chaining method but I have no idea of how make the click event like this:
MyLibrary("selector").click(function(){
console.log("hello");
});
I guest that if I learned this, i'll know how does blur, mouseover, etc etc, works as well.
Please I hope you help me learn, I searched for answer but i could not find any or maybe I was asking in the wrong way.
UPDATE
I know how to use jQuery, BUT WHAT I ASKED WAS how can I make it? I mean, I want to create a library and I want to add a click event like jQuery does.
I did chaining method like this:
Find().UserByName("Bob").Write("DivOrInputObject's ID").UserByPass("pass").Write("DivOrInputObject's ID");
But while writing the code, It came to my mind how can I make a click event? In simple words, I want to imitate click() event like jQuery does and add it to my library.
I am assuming that you are writing your own jQuery. So if your MyLibrary object have selected element under MyLibrary.el then you can have chainable click handler like this:
click: function(handler){
this.el.addEventListener('click', handler.bind(this.el));
return this;
},
This will bind this inside the handler to the element itself. Just like jQuery
Here is this code in action: http://jsbin.com/ahinow/1/

Is there any way to use javascript (jquery) to make an element behave **exactly** as if it was clicked (a unique situation)

I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.

How to attach behaviour to a document

I am trying to bind the KeyDown event to all "Input type=text" controls in the document.
I can't rely on CSS selectors because the page change dynamically, so I only know that when
there is an "Input type=text" in the page, I must catch the keydown event and do something with it....
I heard about document.addEventListener() but I am not sure if this is the good approach and how to use it.
I am newbie with Javascript and DOM, help please.
ok guys, I found by myself the answer so I will share it.
my objective is catch all keydown events so I use addEventListener with the 3 parameters you can see below, first: event type name, second:function event handler,third: boolean Required that specifies whether the event needs to be captured or not.
window.onload = function () {
if (document.addEventListener)
{
//attach the event listener which acts globally to the document:
document.addEventListener("keydown",justDoIt,true);
}
}
function justDoIt(){ alert("hobbes");}
Finally, one more thing is missing, I dont know how to detect the id of the element where the event was triggered....if someone knows please reply.
That's all :P BTW just tested on Safari.ยก but it would work over IE and FireFox....

Adding Javascript EventListener only if no other listener is present?

I'm a relative tyro in the Javascript programming arena, so please go easy on me. :-)
I am trying to add an eventListener to various DOM elements on a page. However, some of the elements I'm adding my event to already have an eventListener, and I don't want to supersede that one; I only want to add my event to an element that doesn't already have an event associated with it.
I've looked through a bunch of stuff relating to addEventListener, event.StopPropagation, event bubbling, and so forth, but haven't figured out any way to accomplish this yet.
Is there a way to detect other event listeners on a given element, or some other way to get where I want?
You can check if the on[event] property of that given element is set by using:
if (typeof(document.getElementById("element-id").onclick) == "undefined") {
// event undefined
}
if (typeof(document.getElementById("element-id").onclick) == "function") {
// event defined
}
Notice that this won't work if a javascript library such as jQuery were used to define the event (e.g. by using $("#element-id").click()). I'd recommend you to use jQuery, you can handle events easily with it.
edit: uh, well, afaik it doesn't work if you're using addEventHandler too. It only works if you set your event by using yourElement.onclick = anyFunction

Categories

Resources