locked
Separating Functions And Listeners RRS feed

  • Question

  • User1928065626 posted

    I have a couple of questions about removing jQuery scripts from the head section of an HTML document and putting the functions in one file and function calls and event listeners in another. 

    1 - Should the functions be placed inside document ready in the new file?

    2 - Should mouse event listeners(click( ), hover( ), etc.) and function calls be placed inside document ready in the new file?

    3 - Where should I place variables if both the functions and event listeners require the same variables?

    4 - If I place the same variables in both external script files wouldn't that cause conflicts?

    Friday, October 28, 2016 1:42 AM

Answers

  • User527778624 posted

    Hi,

    1 - Should the functions be placed inside document ready in the new file?

    No

    2 - Should mouse event listeners(click( ), hover( ), etc.) and function calls be placed inside document ready in the new file?

    Yes

    3 - Where should I place variables if both the functions and event listeners require the same variables?

    at the top, without var keyword

    4 - If I place the same variables in both external script files wouldn't that cause conflicts?

    No, as you are not declaring with var. It becomes part of window obj.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 29, 2016 6:06 PM

All replies

  • User-474980206 posted

    1) no, not necessary. also because they would be in the ready scope, they would not be callable

    2) optional if the script is after all the elements referenced. 

    3) before the above two in a separate file. but in general its a bad practice to share variables, you should pass by closure.

    4) yes. 

        var a =1;
        var a;  // a still == 1

    is valid javascript and defines the same variable.

    Friday, October 28, 2016 3:17 PM
  • User527778624 posted

    Hi,

    1 - Should the functions be placed inside document ready in the new file?

    No

    2 - Should mouse event listeners(click( ), hover( ), etc.) and function calls be placed inside document ready in the new file?

    Yes

    3 - Where should I place variables if both the functions and event listeners require the same variables?

    at the top, without var keyword

    4 - If I place the same variables in both external script files wouldn't that cause conflicts?

    No, as you are not declaring with var. It becomes part of window obj.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 29, 2016 6:06 PM
  • User1928065626 posted

    Thank you all for replying. I will apply what you have shared to my work.

    Sunday, October 30, 2016 6:48 AM