Suppose I have a div and I want to make a certain code run when a user clicks on that div. I can accomplish that in 2 ways.
HTML
<div id="clickme">Click Me</div>
Javascript
$(document).ready(function(){
$('#clickme').click(function(){
//Other code here doing abc.
});
});
the 2nd way is calling a function which does exactly that but it is called by a function
<div id="clickme" onclick="clickme()">Click Me</div>
Javascript
function clickme(){
//Other code doing abc.
}
My question is that are both these codes doing the same thing? and which is more efficient and recommended?
It depends. Usuaslly if it's something quite simple I prefer to use onlick="".
On the other hand, if it's more complex and you want to execute a lot of code, I prefer to use bind events for the sake of readability.
I honestly believe that onclick="" is better in terms of performance/memory usage etc. The bind events you're using are in the layer of jquery and with onclick the event is directly invoked from your element.
It's a matter of choice, really.
Something which I like in bind events is that you have endless possibilities on what to bind and capture clicks or keystrokes. There are also jquery plugins to enhance the bind events, such as bind with delay etc (bind with delay is when you press a key and the code is executed x amount of seconds after you press it, which is great when doing search as you type over ajax as it prevents a request on each key press)
Let me know if you require further info.
Hope I gave you a good insight :)