0

jQuery quick question about event handling.

Here's simple code

<div id="txt">change me!</div>


$('#txt').click(function () {
    console.log(this);
    $(this).text('changed!');

});

this outputs

<div id="txt">changed!</div>

in console. Though console.log(this) is executed before text() method, I get result of text() method is fired. Why is that?

norixxx
  • 2,549
  • 2
  • 19
  • 26

2 Answers2

0

Console.log fires late in Chrome. If you wanted to log an element at the time of the click, you could create a clone of the element and then log the clone per this SO post.

Also, this should be inside the $(document).ready function

$(document).ready(function () {
    $('#txt').click(function () {
        var foo = $(this).text();
        console.log(this);            // Will have changed! because it's firing after everything else
        $(this).text('changed!');    
        console.log(foo);    
    });
});

Console Output

<div id="txt">changed!</div>
change me!

See Updated JsFiddle

Community
  • 1
  • 1
  • I understand. I am OK with final HTML output. But my question is the order of method(function) execution. What I was expecting to see in the console is `
    change me!
    `, not `
    changed!
    `, because `console.log` is executed before jquery `text()` method.
    – norixxx Aug 22 '14 at 03:34
  • I see now. Another stuff I did not know of. i'll be aware of that from next time. – norixxx Aug 22 '14 at 07:03
0

This happens because you are running in 'this' context. As a result what ever you changing in $(this) will get hoisted to top of the function. A simple example:

$('#txt').click(function () {
    console.log(this);
    var a = 10;
    var b = 20;
    var c = a+b;
    console.log(c);    
    $(this).text('changed!');
    $(this).attr('test','test');
});

will hoist at the top

$(this).text('changed!');
$(this).attr('test','test');

and the result will be

<div id="txt" test="test">changed!</div>
30

JSFiddle

V31
  • 7,626
  • 3
  • 26
  • 44
  • This doesn't make any sense at all. Hoisting only hoists variable declarations (not definitions) and function expressions, it doesn't rearrange lines of code like you're suggesting. `console.log(c);` will always fire before `$(this).text('changed');` in your example, regardless of hoisting. – Alex McMillan Aug 22 '14 at 02:26