What is the difference between on("click",function()) and onclick="function();"? - javascript

So if I want something to happen when I click a button I can either do:
<!-- EXAMPLE A-->
<input type="button" onclick="alert('hello world');">
or I can do
<!-- EXAMPLE B-->
<input type="button" id="clickme">
<script>
$('#clickme').on("click",function(){alert('hello world');});
</script>
Or of course any variations (on change, on hover) and shortcuts (.click() .change()) are possible...
Besides the fact that A is shorter, what are the differences? Which is better and why?
I noticed, that when I use .html() to dynamically add an element to the site (like a button) B doesn't work for this newly created button, and I need to use A...
Any insights would be helpful!

<input type="button" onclick="alert('hello world');">
This is the way how inline events are handled. The main reason this is a bad idea is to clearly define the separation of concerns.
HTML - Structure of your page
JS - Your page functionality
This will cause less maintenance issues in the long run and when the system scales in size.
What happens if you have 100 buttons on your page and you want to remove the click event or change it for all of them. It would definitely be a nightmare.
Also you can only define a single event if you bind it inline.
By moving out to a separate file you have a lot of flexibility and you can just make a small change that will affect all the elements on the page.
So the 2nd approach is always better. and the way to go.
By defining the events like below
$('#clickme').on("click",function(){alert('hello world');});
you HTML looks clean sans of any functionality and removes the tight coupling.
In the cases you have a dynamically added, it is true inline events always work but there is a concept called Event Delegation . You attach the event to a parent container that is always present on the page and bind the event to it. When the event occurs at a later time on the element , the event bubbles to the parent which handles the event for you.
For such cases you bind the events using .on passing in a selector
$(document).on('click', '#clickme', function() {
Keep in mind that binding multiple events to a document is a bad idea. You can always use the closestStaticAncestor to bind the events.

The first approach only lets you register one click listener whereas the second approach lets you register as many as you want.
If you want clicks on dynamically added elements to be heard as well, you should use .on(). Here's some code that demonstrates this (jsfiddle):
HTML
<div id="mainDiv">
<span class="span1">hello</span>
</div>
JS
$(document).on("click", ".span1", function () {
$( "#mainDiv" ).append("<span class=\"span1\">hello</span>");
});
$(".span1").click( function () {
console.log( "first listener" );
});
$(".span1").click( function () {
console.log( "second listener" );
});
Notice that first listener and second listener is only printed when clicking on the first hello, whereas a new span gets added when clicking on any of the spans.

Guessing this is your real question:
I noticed, that when I use .html() to dynamically add an element to
the site (like a button) B doesn't work for this newly created button,
and I need to use A...
Simply use the selector in the .on() function, AND USE A CLASS instead of DUPLICATE IDs for multiple elements:
$('document').on("click", ".myButtons", function(){
alert('hello world');
});
Button(s) - change to class (if you use IDs, only the FIRST will be selected):
<input type="button" class="myButtons" />
<input type="button" class="myButtons" />
This is how you should use .on() to attach event handlers to new elements:
https://stackoverflow.com/a/14354091/584192

Difference in works, if you use click() you can add several fn, but if you use attribute only one function will be executed - the last one
HTML-
<span id="JQueryClick">Click #JQuery</span> </br>
<span id="JQueryAttrClick">Click #Attr</span> </br>
Js-
$('#JQueryClick').on("click", function(){alert('1')});
$('#JQueryClick').on("click", function(){alert('2')});
$('#JQueryAttrClick').attr('onClick'," alert('1')" );//this doesn't work
$('#JQueryAttrClick').attr('onClick'," alert('2')" );
If we are talking about performance, in any case directly using is always faster, but using of attribute you will be able to assign only one function.
Try This
Reference

Related

Cloning a Bootstrap element but not all of the event listeners

In this question Cloning a bootstrap element with an event listener I asked how to clone an element without copying the bootstrap-supplied event listener. And the answer is to not pass true to the clone() command.
As it turns out, I see now that my problem is a bit more complicated than that. What I actually have is a div containing several buttons, one of which controls the expand/collapse of an associated div, and others of which provide other specialized functionality, which are provided by complex click listeners added within the javascript when creating the original. I need to keep the click() listeners on those other buttons. If I call clone() without the true argument, I lose all those listeners as well.
So is there some way I can clone(true) with listeners, but remove the bootstrap-provided cloned listener from the expand/contract button, change the IDs to be unique IDs, and then somehow still get bootstrap provide that collapse functionality (add the listener again, I guess, based on the new changed IDs in the cloned div)?
I am creating a bunch of different collapsible objects, and then cloning some of them (into another tab pane).
A simplified version of my code:
<div class="container">
<button aria-expanded="false" data-target="#collapsible_obj_0" data-toggle="collapse" class="btn btn-link collapsed">click here</button>
<div style="height: 0px;" aria-expanded="false" id="collapsible_obj_0" class="collapse">
<span>foo</span>
<button class="btn bar-btn">bar</button>
</div>
</div>
And a snippet from the javascript:
$("#collapsible-obj-0 .bar-btn").click(function () {
// do a bunch of stuff
});
this.collapsibleObjCounter = 15; // really this will be one more than the number of exiting objects
// objectContainer is the jquery object representing the top level div (passed into this method)
var header = objectContainer.clone(true); // or not true, that is the question....
var counter = this.collapsibleObjCounter++;
var collapseId = "collapsible_obj_" + counter;
header.find(".collapse").attr("id", collapseId);
header.find("button[data-toggle='collapse']").attr("data-target", "#"+collapseId);
What I need here is to remove the event handler on the "click here" button and have bootstrap add a fresh one based on the changed IDs. If I clone without the true flag that seems to work correctly but I lose the click() functionality of the "bar" button. In reality I have a lot of "bar" buttons whose functionality I need to keep. So manually copying the click() behaviors to the cloned versions would be messy, but possible. But ideally I think what I want is a way to just remove the one event handler when I change the IDs on the collapse button and associated div, and get bootstrap to put a new one on automagically.
I apologize that this isn't runnable code - there's so much context that it's hard to pull out a streamlined runnable example.
You should try to delegate those events handlers with the use of .on() method.
$('body').on('click', '.bar-btn', someFunc);
Added a Jsfiddle with added delegated handler.
Benefits of event delegation:
You may not need to copy/clone those handlers at all
It will work just fine for the nodes added dynamically in the DOM at a later time as well (via bubbling).
So, the above code will trigger the event handler someFunc on click of bar-btn even if it is after cloning and pasting an instance of objectContainer.
To learn more, check out these links about event delegation and bubbling.

What is the proper way to unbind event listeners and remove child elements in single page applications?

I've been building a large single page application and recently got into exploring memory leaks in JS. And I think I've got a memory leak because - as I use the Profiles (Snapshot) function in Chrome - I see that I have a lot of detached DOM elements.
Here is a simplified view of my setup:
<div id="container">
<div class="buttons">
<a class=".btn" href="/someurl/"> Button A</a>
<a class=".btn" href="/someurl/"> Button B</a>
<a class=".btn" href="/someurl/"> Button C</a>
</div>
<div class="ajaxHolder"></div>
</div>
So if a user clicks Button A, for example, I would use an AJAX call to load content into the .ajaxHolder. Something like this:
//This is the content...
<div class="contentA">
<p>some text...</p>
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
</div>
I also have two functions inside my MAIN script file. One would be like this:
//Click event bound to a.btn which tigger the ajax call
$(.buttons).on('click', '.btn', function(){
//Do ajax here...
//on success...
var holder = $(".ajaxHolder");
holder.children().off().remove(); // Is this the way to do this??
holder.off().empty(); //I don't think I need .off() here, but I guess it can't hurt...
holder.append(ajaxSuccessData);
});
So far so good. But now with the content loaded, I also have this function inside my MAIN script file:
//So here, I am binding an event to the checkboxes...
$(".ajaxHolder").on('change', '.checkbox', function(){
//Do something...
});
So now if the user presses button B, for example, .ajaxHolder is emptied, but all those events tied to my checkboxes seem to stick around, because they are showing up in my detached DOM tree.
What am I missing here? How can I make sure I don't have any detached DOM elements, in a single page application running like this?
BONUS QUESTION: I have A LOT of events tied like this:
$(".ajaxHolder").on('someEvent...','.someClass....', someFunction());
That is to say, everything is always attached to my .ajaxHolder, because I have to use event delegation since .ajaxHolder will always exist - whereas other items that are loaded will not always exist, so I cannot simply do $(button).on('click')..., etc.
So is this the correct way to do this as well? Is there a limit to how many things I can attach to this .ajaxHolder or are there no issues with doing this?
EDIT: Here is an image of my console, if that helps at all.
Not sure this is still relevant, but from the console image I gather you are using bootstrap tooltips, and they seem to be holding the reference to the DOM node. I suggest you call the destroy method via the API
jQuery event unbinding and removing of elements can be dong with the following methods:
$.off()
$.remove()
The best method to do this would be to unbind all the event listeners by using $(selector).off(); method and then removing the element by using $(selector).remove();
It would stop all the memory leaks happening because of the event handlers.

jQuery: last doesn't work with mixed tags

I am having html look like below:
<td id="sample">
<select>
<option>
</select>
<br/>
<select>
<option>
</select>
<br/>
//...
</td>
I know we should be using div instead of table but our whole webpage is designed this way and it is kind of time-consuming to change it.
What I am trying to do is add a event handler to the change of last select tag. I have tried:
$("#sample > select:last") and $("#sample").find("select).last() but both of them tend to find the last select before br tag which means the first one. I can probably solve this issue with adding an attribute in my code but that will result in adding a global variable and an amount of code. Is there a cleaner solution?
Edit:
Sorry that I didn't understand my issue correctly and many thanks to all the comments. I guess my issue actually is I put the event handler in my document ready section and append more <select> in that event handler. So every time when I am trying to trigger the event, it always come to the original last element.
My code looks like:
$('#sample > select:last').on('change', function() {
$('#sample > select:first').clone().show().appendTo('#sample');
$("<br/>").appendTo('#sample');
});
But although I kind of find the reason, I am still confused in solving it. Is there any solutions around this?
You're dynamically creating your elements, therefore you need a dynamic event delegation:
Dynamic Delegation works like:
$("staticElement").on("someevent", "dynamicElement", function)
and it's used to attach an event to the parent with a renewal look for recently appended child Elements.
To explain, on execution time if you attach an event to some elements directly like: $(".foo").click(fn) or $(".foo").on("click", fn) it will not account for .foo elements added in a later time cause they were not in the .foo collection at the time.
By assigning the event to the static parent, the event Delegation will bubble inversely searching for children (that match the selector argument and are the initiators of the same event trough event.target) that received that event.
In your example:
// static Parent // evt , dynamic
$("#sample").on("change", "> select:last", function() {
$('#sample > select:first').clone().show().appendTo('#sample');
$("<br/>").appendTo('#sample');
});
More details to your question here: http://api.jquery.com/on/#direct-and-delegated-events

Event.observe inefficient with prototype Javascript, alternatives?

We have a table with a lot of checkboxes, onchange of a checkbox we want to call some Javascript.
We use something similar to this snippet:
addEventObserver(elementId){
// ($= means 'ends with') this is required for elementIds which are in a table and get prepended with some id
$$('[id$=:'+elementId+']').each(function(e) {
Event.observe(e, 'change', function(event) {
submitAction(something);
});
});
}
So below an input checkbox we add a Javascript function call:
<input type="checkbox" name="somename" id="somePrependedIdsomeId">
<script type="text/javascript" language="javascript">
addEventObserver('someId');
</script>
this works fine with our test environment settings. In production though we have tables with ~700 checkboxes and this makes the browser/cpu get stuck.
We use jsf
I would scrap adding an event listener to every single checkbox in favour of writing a single "smart" event handler attached to a container element. Here is a simple example:
var theDiv = document.getElementById("foo");
theDiv.onchange = function(e) {
if (e.target.tagName.toLowerCase() == "input"
&& e.target.type.toLowerCase() == "checkbox") {
alert("do something");
}
}
Demo: http://jsfiddle.net/xFC3A/
The onchange event is thus captured by the container div which is bubbles up to. The event attached to the div can test for the type of element that triggered the event (the source/target element depending on the browser) and react accordingly. Main advantages are:
Only one event handler - no time wasted binding handlers to hundreds of elements.
It will continue to work on dynamically added elements (via AJAX, JS etc.).
Read more about Event Delegation.
Some useful reference: http://www.quirksmode.org/js/events_properties.html
I'm not much of a Prototype jockey (much more of a jQuery guy), but generally speaking, any selector using an attribute selector is going to be slow. If you're running that selector on 700+ items, you're going to hit a massive slowdown for sure.
You're also using Prototype's each() method... could you re-write things to use a native javascript for() loop instead? Again, referring to jQuery here, but I've gotten INCREDIBLE performance gains by using native JS rather than library methods whenever possible. I've sped a web app by 20x by removing a bunch of jQuery .each() methods and replacing them with native for() loops.
I think Event Delegation should help you, simple attach die EventHandler to the Parent of all Checkboxes
$('container').observe("change", changeBy);
function changeBy(e){
if (e.element().identify() != "container") {
doChange(e.element());
}
}
function doChange(elem){
submitAction(something);
}
Markup:
<div id="container"> <input type="checkbox" > ... </div>
You doesn't need to do the foreach and you doesn't have hundreds of eventhandler, you simple have one EventHandler, this is pretty fast.
Prototype already provides event delegation by way of Event.on:
$('id_of_table').on('change', 'input[type=checkbox]', some_handler_function);

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Categories