Onclick or Onclick

onclick or onClick?

Because some browsers (depending on the DOCTYPE) are tolerant of the inline onClick="something();" attribute...it seems to have spread a bit, even into JavaScript questions where it doesn't work, since case matters.

Also, specifically to stackoverflow...people using it in questions...well, most of the time they wouldn't be asking a question if their code worked :)

What's the difference between onClick ={ () = function()} and onClick = {function()}?

In first one:

<button onClick={()=>props.submitHandler(searchInputValue)}>Submit</button>

This is arrow function and it will trigger only onClick of the button.

In second one:

<button onClick={props.submitHandler(searchInputValue)}>Submit</button>

This is a normal function call , which calls the method as soon the rendering of the component happens.

I don't understand onClick={() = onClick()} (beginner question)

As a useful example to that notation, let's say you have two buttons (primary and regular) with the same onClick handler but you want to pass a parameter regarding which button you clicked:

onClick={e => onClick(e, primary)}

So your onClick handler could behave differently depending on which button you click.

Difference between v-on:click=... and using onclick=... in Vue.js

One of the chief differences is scope access. onclick's bound scope is global so the functions that you want it to call have to be accessible from the global scope. v-on's scope is the Vue model.

Another thing is that Vue provides a very easy API to define custom events through vm.$emit(). It's also very easy to listen for those events using v-on:customevent="callback" which can be easily cognitively mapped to a hypothetical onfizz="callback()".

With that in mind, it makes sense to also provide v-on:click for a consistent API as well as the other extensions v-on provides.

/* * This pollutes scope.  You would have to start * making very verbose function names or namespace your  * callbacks so as not collide with other handlers that * you need throughout your application. */function onClickGlobal() {  console.log("global");}
const fizzbuzz = { template: "<button @click='onClick'>FizzBuzz</button>", methods: { onClick() { this.$emit("fizz"); } }};
const app = new Vue({ el: "#app", components: { fizzbuzz }, methods: { onClickModel() { console.log("model"); }, onFizz() { console.log("heard fizz"); } }});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app"> <section> <h2>Buttons and Clicks</h2>
<!-- Calling function of the bound scope --> <button @click="onClickModel">v-on Model</button> <!-- Works as well, but calls the global --> <button @click="onClickGlobal">v-on Global</button>
<!-- You need to explicitly invoke the function from onclick -->
<!-- This won't work because onClickModel isn't global --> <button onclick="onClickModel()">onclick Model</button> <!-- Works because onClickGlobal is global --> <button onclick="onClickGlobal()">onclick Global</button>
<!-- You can technically call onClickModel through the global app --> <!-- but you really shouldn't -->
<!-- Works because app.onClickModel is technically global --> <button onclick="app.onClickModel()">onclick Global through app.onClickModel</button>
</section> <section> <h2>Custom Events</h2> <fizzbuzz @fizz="onFizz"></fizzbuzz> <!-- The element below doesn't work --> <button onfizz="onClickGlobal">Hypothetical Fizz</button> </section></div>

The difference between html onclick attribute and react cnClick attribute

From the HTML specification:

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion.

From the React documentation:

With JSX you pass a function as the event handler, rather than a string.



They are different though it does the same work.

Yes. HTML and JSX are different languages used to construct a DOM.

addEventListener vs onclick

Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

Event Listeners (addEventListener and IE's attachEvent)

Earlier versions of Internet Explorer implement JavaScript differently from pretty much every other browser. With versions less than 9, you use the attachEvent[doc] method, like this:

element.attachEvent('onclick', function() { /* do stuff here*/ });

In most other browsers (including IE 9 and above), you use addEventListener[doc], like this:

element.addEventListener('click', function() { /* do stuff here*/ }, false);

Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser.

The examples above represent using an anonymous function[doc]. You can also add an event listener using a function reference[doc] or a closure[doc]:

var myFunctionReference = function() { /* do stuff here*/ }

element.attachEvent('onclick', myFunctionReference);
element.addEventListener('click', myFunctionReference , false);

Another important feature of addEventListener is the final parameter, which controls how the listener reacts to bubbling events[doc]. I've been passing false in the examples, which is standard for probably 95% of use cases. There is no equivalent argument for attachEvent, or when using inline events.

Inline events (HTML onclick="" property and element.onclick)

In all browsers that support javascript, you can put an event listener inline, meaning right in the HTML code. You've probably seen this:

<a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>

Most experienced developers shun this method, but it does get the job done; it is simple and direct. You may not use closures or anonymous functions here (though the handler itself is an anonymous function of sorts), and your control of scope is limited.

The other method you mention:

element.onclick = function () { /*do stuff here */ };

... is the equivalent of inline javascript except that you have more control of the scope (since you're writing a script rather than HTML) and can use anonymous functions, function references, and/or closures.

The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[doc], meaning that it can be overwritten.

Using the example <a> from the HTML above:

var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); };
element.onclick = function () { alert('did stuff #2'); };

... when you clicked the element, you'd only see "Did stuff #2" - you overwrote the first assigned of the onclick property with the second value, and you overwrote the original inline HTML onclick property too. Check it out here: http://jsfiddle.net/jpgah/.

Broadly speaking, do not use inline events. There may be specific use cases for it, but if you are not 100% sure you have that use case, then you do not and should not use inline events.

Modern Javascript (Angular and the like)

Since this answer was originally posted, javascript frameworks like Angular have become far more popular. You will see code like this in an Angular template:

<button (click)="doSomething()">Do Something</button>

This looks like an inline event, but it isn't. This type of template will be transpiled into more complex code which uses event listeners behind the scenes. Everything I've written about events here still applies, but you are removed from the nitty gritty by at least one layer. You should understand the nuts and bolts, but if your modern JS framework best practices involve writing this kind of code in a template, don't feel like you're using an inline event -- you aren't.

Which is Best?

The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.

jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:

$(element).on('click', function () { /* do stuff */ });

Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:

function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}

// example
addEvent(
document.getElementById('myElement'),
'click',
function () { alert('hi!'); }
);

Try it: http://jsfiddle.net/bmArj/

Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.

Documentation and Related Reading

  • W3 HTML specification, element Event Handler Attributes
  • element.addEventListener on MDN
  • element.attachEvent on MSDN
  • Jquery.on
  • quirksmode blog "Introduction to Events"
  • CDN-hosted javascript libraries at Google

Appending button onclick function runs when appended

As per your codebase, the button.onclick needs to be asigned as a function.

But in the code it is button.onclick=removeUser(button.innerHTML), due to this line removeUser would be directly executed when creating the button.

You might have to update your code as follow:

button.onclick = () => removeUser(button.innerHTML)

This way, the removeUser is wrapped inside a function and that function is only called when user clicks on the button. Hope this helps. :)



Related Topics



Leave a reply



Submit