Programmatically firing a click handler - javascript

I'm using dojo. I've got something like this:
<a id="fooBar" onclick="foo();bar();">Foo then Bar</a>
I want to trigger fooBar's click handler from another button. Something like:
<a onclick="dojo.query('#fooBar')[0].click()">Do FooBar</a>
Can I do that?

dojo.byId('fooBar').onclick();
or
dojo.query('#fooBar')[0].onclick();
See examples.
I haven't used Dojo before, but can safely say that you can do better than inline events :). Moreover, these will not be managed by Dojo as they were added inline. The onclick method here is a native DOM method for triggering the function attached to the onclick property of the element.
dojo.byId is a shortcut to document.getElementById, and honestly you can easily do without Dojo here:
document.getElementById("fooBar").onclick();
Here's the three methods with a comparison of character savings (9 and 14):
document.getElementById('fooBar').onclick();
dojo.query('#fooBar')[0].onclick();123456789
dojo.byId('fooBar').onclick();12345678901234
See a couple of good reasons for not using inline click handlers.

Related

What's the difference between .click(function () { and javascript:myfunction()?

Consider the simple link below:
Link
I understand there are two ways to run a function when a user clicks this element:
$(".mylink").click(function () {
and
Link
Is there a performance difference between the two, or any other practical reason I should use one over the other?
Using $('.mylink').click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent).
Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.
Read jQuery.click() vs onClick
and How does inline Javascript (in HTML) work?
https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting
They have the same functional behavior, there is no difference whatsoever.
The difference is in code modularity and maintainability.
Using the first method is preferred and more appropriate because it doesn't mix between HTML and JavaScript, a concept called Unobtrusive JavaScript.
If you have worked in the early days of HTML, then you should remember when there were all those attributes like background, color, font ... etc.
Then CSS came in, and everybody told us not to use those old attributes anymore because they mix presentation with document structure, instead we should use CSS to control layout and look of the document.
This is similar to that idea but it is now used for code, separate functionality from document structure.
Edit: Quoting from #mplungjan comment in order to be more accurate:
That there is no difference is not true. href="javascript:myFunction()" does not have the ability to cancel the actual click with a preventDefault or return false. Hence animated gifs will stop running in some browsers and older browsers would even partially unload the page. Also if the function returned a value, the page would be replaced with that value, seen when beginners try href="javascript:window.open..." and get [object object] on the page
Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.
I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.
I definitely recommend JQuery!
The first one is JQuery convention of an event listener. You need to include jquery library in order to use it. The second one is a Javascript convention. You don't need to include any library or extra code to run. There are no differences in terms of performance, but as I told if you do not want to include any kind of library you should use the second example.

onclick attribute vs eventListeners

I'm re-writing the code of a website I created a few years ago, and I was wondering what was the most efficient way to handle the click event on an element?
I have a list of items with links to edit them, and they're all written with the onclick="..." HTML attribute. Is it better that way or I should use $.bind() or addEventListener to handle it? What's the best practice?
It is considered best practice to utilize what is called unobtrusive javascript. What this means is you separate the layout of your HTML from the behavior of the elements. So instead of using the onclick attribute, which mixes up element structure and behaviour, you layout your DOM structure in markup and then attached event handlers via javascript.
What this means is that is considered best practice to use javascript to attached event handlers, as follows:
<html>
<script>
... bind event handlers to your DOM and set behaviours here
</script>
<body>
.... layout your DOM here
</body>
<html>
This has advantages for long-term code maintainability and extensibility. This approach works very nicely with javascript libraries such as jQuery.
In terms of performance, you may be able to achieve performance gains via an unobtrusive javascript approach by using an intelligent caching strategy.
For more information on unobtrusive javascript, see here
addEventListener or it's jQuery version on \ bind is the best practice as it separates the visual part-HTML from the functional part- javascript.
Separates of concerns.
If the code is written already, I wouldn't change it, it's not that important.
Many people will discourage the use of onclick because "what if you want to add another onclick event?" - personally I have never had this issue, but I can sort of understand.
If you're not using the links for anything other than a single click event, then onclick is perfectly fine. However, if you want it to be bulletproof, you probably want addEventListener. I actually have my own addEvent/fireEvent/removeEvent trio of functions that keep track of events and handle browser inconsistencies for me (bringing in window.event, for instance) and this works quite well.

Onclick vs addEventListener [duplicate]

This question already has answers here:
addEventListener vs onclick
(21 answers)
Closed 3 years ago.
I'm little confusing by using "onclick" "onmousedown" as a property of HTML elements.
Such as:
<button onclick="my_JS_function()"></button>
or
<div onmousedown="my_another_JS_funciton"></div>
But some people tell that only "proper" way of adding "listeners" are by
document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);
What is the more "proper" more supported way of doing that?
if you already know function and element is part of html i.e. not get added dynamically than its good that you add function inline rather than using extra method call like "addEventListener"
Another thing to note
While onclick works in all browsers, addEventListener does not work in older versions of Internet Explorer, which uses attachEvent instead.
OnClick is a DOM Level 0 property. AddEventListener is part of the DOM Level 2 definition. Read about this : http://www.w3.org/TR/DOM-Level-2-Events/events.html
inline event handlers added as HTML tag attributes, for example:
Click me!
The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element. In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup.
document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);
Advatange of this : you can add multiple event handler. also separte html and javascript code
For more detail you can read this : Adding an Event Handler
The latter (addEventListener()) is the best way, as you can attach multiple events of the same type to the same element.
By assigning to onclick, etc, you will overwrite existing handlers.

How we can find attach function in a html tag in javascript

Suppose we have a html tag and some javascript function is attached on that by addEvenetListner or attachEvent (with tag id or name but not inline), and if we need find out that which function is attach on that tag, then what is good way for find that.
Please suggest me.
If don't need to do it programmatically you can use visual event. If you need to do it programmatically i only have a jquery solution ($('#element').data('events');)
There is no native API to get event handler that was attached by addEventListener/attachEvent. jQuery store internal this handlers in some object. If you use jQuery you can done this by:
$('#someID').data('events');
Or you can write wrapper for addEventListener/attachEvent and store handlers manualy.

How to use Sly (or any other selector engine) to set event handlers?

Supposing I've got multiple div's with the same class, I could do something like :
$('.className').click(f) in Jquery or other frameworks
However, I was trying to use Sly as my selector engine and wanted to do something like :
Sly.search('.className').click(f)
I'm not sure as to how the binding in Jquery works :
If I use the above JQuery, does an eventhandler get attached to all of the found divs individually? Or does it do something else to optimize and "tell" the browser specifically to link this function f to the onclick for the className (instead of manually telling the browser to attach the same function to each of the found divs)
Is there a way to achieve the above in Sly (or other Selector Engines) without using iteration over the elements returned ?
It will add a handler to each object currently in the set.
With the default Sizzle engine, you can call .live to add a single handler to <body> which catches all bubbled events and forwards them to any register events for matching selectors (what you're asking for).
You should not worry about performance issues; the point of .live is to affect elements that are created later.

Categories

Resources