overstack
overstack

Reputation: 109

What is the difference of jquery click and focus?

$('#birthday_y').focus(function() {
    if (!$(this).val()){
        $(this).val('1980');
    }
});

the above code can set a select box to '1980 year' with highlight, whereas, the following code did not workk? can you give a explain?

$('#birthday_y').click(function() {
    if (!$(this).val()){
        $(this).val('1980');
    }
});

Upvotes: 1

Views: 6564

Answers (3)

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

Difference between focus and click

The focus event occurs when the field gets focus. Whether it is focused by clicking on that element, or focused by pressing tab button.

Click event occurs when you click using mouse on that event. Focusing that element after clicking is browsers behavior.

In your code,

1st example.

In the first example.The focus event gets fired only when the field gets focused. No matter how many times you click on that element.

$('#birthday_y').focus(function() {
  console.log("clicked")
  if (!$(this).val()) {
    $(this).val('1980');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="birthday_y">

2nd example.

In the second example. The click event gets fired when you click on it, no matter whether element is focused or not.

$('#birthday_y').focus(function() {
    console.log("focused")
    if (!$(this).val()){
        $(this).val('1980');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="birthday_y">

As the question of highlighting, it is totally depend on browser behavior, if you want uniform behavior, you can use your own script to select all on focused.

Upvotes: 2

Sateesh Pagolu
Sateesh Pagolu

Reputation: 9606

If you have both handlers in code at a time, when you are about to click, focus handler is already executed, so it doesnt go into if (!$(this).val()){ block.

Upvotes: 2

Cacho Santa
Cacho Santa

Reputation: 6914

When you click on the input both of them work perfectly. Take a look at this jsfiddle.

Unless if you birthday_y element is an input.

$('#birthday_y').click(function() {
    if (!$(this).val()){
        $(this).val('1980');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<input id="birthday_y" />    

Take a look at this post, for details about the difference between click and focus.

Upvotes: -1

Related Questions