Onclick="" VS Event Handler

Difference between using ID and onClick

If you think about it similarly to how CSS works,

onclick= : id= :: style= : class=

By that, I mean the first of each is mixing the actual functionality of what you're trying to do with the declaration and presentation of the page. The "cleaner" approach is to take the approach of separation of concerns -- allowing the HTML to be the presenter and the JavaScript to handle the functionality, in the same way a CSS stylesheet takes care of the styling aspects, as opposed to declaring styles in-line.

The result, with few exceptions, is generally more portable and maintainable. It's also saves you from little headaches in the future. For example, if you were to rename the function foo to bar, and you declare onclick='foo()' in 50 places on your website, well, that's 50 changes to onclick attributes. If you use the alternative (binding the element to javascript via the ID), you have a one-line change.

Also, note that you are not restricted to matching on IDs. You can attach javascript methods to classes as well, or a combination of both, so you have great flexibility there with no additional markup to your HTML.

For additional details on the overall concept relevant to your question, see:
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Separation_of_behavior_from_markup

onclick= vs event handler

Basically it has to do with the whole keep everything separate I believe. So keep HTML/CSS/JS all separate. It makes your HTML tidier and, I think, easier to navigate without.

Then when/if you need to make large changes, you have ample space with having to shift the inline JS to an external file anyway OR if you want to apply the same function to more than one button, then it's less code. And less code is a happier place

If you have your JS files properly, and thoroughly documented then navigating them by an outside person is made eaiser

jQuery.click() vs onClick

Using $('#myDiv').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.

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
alert('Hello world again!!!');
}, false);

http://jsfiddle.net/aj55x/1/

Why use addEventListener? (From MDN)

addEventListener is the way to register an event listener as specified
in W3C DOM. Its benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that
    need to work well even if other libraries/extensions are used.
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements.

More about Modern event registration -> http://www.quirksmode.org/js/events_advanced.html

Other methods such as setting the HTML attributes, example:

<button onclick="alert('Hello world!')">

Or DOM element properties, example:

myEl.onclick = function(event){alert('Hello world');}; 

are old and they can be over written easily.

HTML attribute should be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

The problem with the DOM element properties method is that only one event handler can be bound to an element per event.

More about Traditional event handling -> http://www.quirksmode.org/js/events_tradmod.html

MDN Reference: https://developer.mozilla.org/en-US/docs/DOM/event

Adding an onclick event to a button with a button that has an onclick event?

You should use displayDate instead of displayDate(). Because displayDate() directly calls the function.

<!DOCTYPE html>

<html>

<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn2" onclick="addfunc();">Trigger</button>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>

function addfunc(){

document.getElementById("myBtn").onclick = displayDate;

}

function displayDate() {

document.getElementById("demo").innerHTML = Date();

}

</script>

</body>

</html>

JQuery link onClick event sends image - how to get the link object instead?

The issue is because the target of the event is always the element at the bottom of the DOM tree which raised the event, not the element which listened for the event.

To achieve what you require you can either use event.currentTarget or the this reference within the jQuery event handler function, as both of these refer to the element which the listener is attached to. Try this:

jQuery($ => {
$('#languagelist a').on('click', function(e) {
e.preventDefault();

// when clicking on the <img />
console.log(this); // = <a />
console.log(event.currentTarget); // = <a />
console.log(event.target) // = <img />
});
});
img {
display: inline-block;
width: 20px;
height: 20px;
background-color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="languagelist">
<a class="dropdown-item" href="/i18n/setlang/" data-nextpage="/ca" data-languagecode="ca">
<img src="/static/ca.png" class="d-inline-block align-middle pb-1" alt="Sample Image" loading="lazy">  Català
</a>
</div>

onClick event firing off after render in React

onClick={funx(1)} the code inside the brackets is evaluated at render, so you're actually calling the function. You want to pass a function reference. If you need to pass the 1 you could do:

 <MenuItem onClick={() => funx(1)} ...>


Related Topics



Leave a reply



Submit