Grow your CSS skills. Land your dream job.

Learning jQuery…Have a few questions

  • # July 5, 2013 at 5:02 pm

    Hello everyone,

    I’m in the beginning stages of learning jQuery and have a couple questions regarding best practices. For those who are well versed with the framework, I welcome any suggestions or tips you can offer regarding the following. Thank you in advance.

    **Question #1**

    Which of the following methods for storing functions _(for later use + multiple times)_ is the best approach?

    _Method A_

    function something() {
    //Do Something
    }

    _Method B_

    var something = function() {
    // Do Something
    }

    _Method C_

    $.fn.something = function () {
    return this.show(0);
    };

    **Question #2**

    What is the difference between the following extension syntax?

    $.fn.something = function () {
    return this.show(0);
    };

    _And_

    $.fn.something = function () {
    this.show(0);
    return this;
    };

    # July 5, 2013 at 6:46 pm

    question #1
    a and b are generally the same but the second one has to be defined before it gets called the first one can be called before declaring it
    so

    one();
    function one(){
    console.log(‘yes’);
    }
    //will log yes

    two();
    var two = function(){
    console.log(‘no’);
    }
    typeerror two is not a function

    in general the second case is used in objects when you want a method handler

    Question #1 three you are declaring a function to the jquery prototype so you can use it with a jquery constructor

    $(‘.my_selector’).my_custom_function();

    question 2

    the first one is a shorthand of the second one they are the same

    # July 6, 2013 at 8:33 am

    @pixelgrid

    Thanks for the information…very helpful! There are two additional matters I wanted to touch on while I still have them fresh in my mind.

    **Question #3**

    When working with multiple **if/else** conditions which of the following syntax is preferred ? I’ve tested both structures…resulting in the same output.

    The first example, uses an else if for any true condition after the original if statement. In the second example, however, you’ll notice all true conditions use the if statement.

    if (condition1) {

    execute if true

    }

    else if (condition2) {

    execute if true

    }

    else {

    execute if false

    }

    _or_

    if (condition1) {

    execute if true

    }

    if (condition2) {

    execute if true

    }

    else {

    execute if false

    }

    Question #4

    Of the two methods below, which is considered the better approach for working with click functions?

    Method A

    $(‘#element’).on(‘click’, function (e) {
    // Do Something
    });

    Method B

    $(‘#element’).click(function (e) {
    // Do Something
    });

    # July 6, 2013 at 8:44 am

    @Rugg

    Be careful there. For question #3, the first version will only execute one piece of code since the if, else if, and else are connected. However, the second version can possibly execute two pieces of code as the second if isn’t an if else. This means that if the first condition evaluates to true, it’s code will be run. Then, if the second condition evaluates to true, it will also run.

    > I’ve tested both structures…resulting in the same output.

    In your case, both versions are ideal for this situation. However, in the future, it may be better to use version #1 as it will avoid the possible error of executing unwanted code. For example, let’s take a look at a simple grade checker:

    **Version #1**

    var grade = 70; //We can get this from the user.
    var letter = ”; //Letter grade
    if (grade > 90)
    letter = ‘A’;
    if (grade > 80)
    letter = ‘B’;
    if (grade > 70)
    letter = ‘C’;

    With this version, notice the use of only if’s. Because of this, if the grade is a 100, the letter will become A, then B, then C. This isn’t what we expected correct?

    **Version #2**

    var grade = 70; //We can get this from the user.
    var letter = ”; //Letter grade
    if (grade > 90)
    letter = ‘A’;
    else if (grade > 80)
    letter = ‘B’;
    else if (grade > 70)
    letter = ‘C’;

    This will work correctly because if the grade is 100, it will go into the first if and then break out since the first condition evaluates to true.

    Clearly, both versions may work for certain situations, but it is best to go with the first one if possible.

    # July 6, 2013 at 8:54 am

    just for the trivia , javascript doesnt handle if else if the way you might be used to.

    if(condition1){}
    else if(condition2){}
    else{}

    what it does is checks the first if and then makes ever else if a if else in the else statement.
    yeah i know its a bit to much, but just internals of javascript.
    so what it does is

    if(condition1){}
    else{
    if(condition2){}
    else{}
    }

    you can have a look here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if…else

    # July 6, 2013 at 9:15 am

    @srig99
    @pixelgrid

    Thank you for the suggestions! I updated the post with a **Question #4**. If you have a chance, I would appreciate your input. Cheers.

    # July 6, 2013 at 9:26 am

    $(‘my_selector’).click();

    is a shorthand for

    $(‘my_selector’).on(‘click’,function(){})

    they are practically the same. you can avoid a function call by using directly .on

    # July 6, 2013 at 9:40 am

    @pixelgrid

    Ok…good to know. I just thought of a related question regarding the same subject…

    **Question #5**

    To prevent default event behavior, is it better to include e.preventDefault(); just inside the click event, before the function? Or after the function just before the closing tag?

    $(‘#element’).click(function (e) {
    e.preventDefault();
    // Do Something
    });

    or

    $(‘#element’).click(function (e) {
    // Do Something
    e.preventDefault();
    });

    # July 6, 2013 at 10:28 am

    **Question 5**

    Well, I use the first version but I’m not sure if using the second version will make a big difference or any at all…

    # July 6, 2013 at 10:42 am

    It makes a difference if the function somehow returns before the end (for example a return statement or an error). Using it in the beginning is fool-proof.

    # July 6, 2013 at 6:18 pm

    Great! Thanks for all the information…helped a lot.

    # July 7, 2013 at 5:41 pm

    I just heard a pretty good reasoning why you should do it at the end recently and can’t remember exactly what it was. Something about error handling I think and not being able to see certain errors.

    # July 7, 2013 at 6:11 pm

    It depends. If you want default behavior (following a link, submitting a form) as a fallback, put it at the end. If you don’t want that, put it at the beginning.

    That’s why I said using it in the beginning is fool-proof. Default behavior as fallback takes planning and probably additional coding (for example a regular form feedback page instead of handling some Ajax response).

    During development it’s easier to debug if it’s at the beginning (it’s harder to catch errors if default behavior is to (re-)load another page).

    See: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/#top_bottom_or_somewhere_in_the_middle

    # July 8, 2013 at 2:26 pm

    @chriscoyier
    @crocodillon

    Interesting tidbit…I’ll have to look into this further.

    Cheers

Viewing 14 posts - 1 through 14 (of 14 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".