0

1st: Adding onClick with a reference to a function.

<button id="click" onclick="click()">1.click me</button>
<script>
function click(){
    alert("ok");
}
</script>

2nd: using jQuery to check the click event.

<button id="click">2.click me</button>
<script>
$(function(){
    $('#click').click(function(){
      alert("ok");
    });
});
</script>

Which works better?

code
  • 2,115
  • 1
  • 22
  • 46
W.sn0w
  • 3
  • 2
  • 4
    Keep JS separate from HTML – Tushar Jan 26 '16 at 08:10
  • It's always better to keep Javascript apart of HTML code. In reference to your question, in this code I think it's not very difference between them, because the function is very simply and the result it's exactly the same in both cases. When you use a more elaborated code, I'ts better to use function to keep your code more clean and understandable – Ferran Buireu Jan 26 '16 at 08:16

3 Answers3

1

Selectors works using Jquery.js . If your project is small then including Jquery in documents may not a good idea and makes your page loads heavily (not much). But selectors (and specially JQuery) makes coding easy and provides professional features for website. So every web designers most to learn how to use that.

if your designing page[s] going to be complex, I suggest you to use JQuery but if your page is just like that you'll better to use simple Java Script.

And i am agree with @Tushar.

Rancbar
  • 184
  • 12
0

The most important thing is to keep html js css and all the other files separated. In that way it will be easy for you to keep your code clean. For this main reason i prefer to use the second way. In fact in that way you can manage your events directly from js code and you don't have to check all around the HTML file in order to find your functions.

Alex95
  • 52
  • 7
-1

As far as your example is concerned, both work well. But if you are only concerned with which way is better, then it depends on what you are trying to achieve.

An ecommerce website:

They already have tons of images to load, and if they added an onclick on every element they wanted clickable, it would significantly increase their load time beccause the html is actually renedered on the webpage and that uses bandwidth.

However, if there is only one button, like a Hire Me on a portfolio website, then both work without any significant time delay.

code
  • 2,115
  • 1
  • 22
  • 46