0

I have a dilemma between 2 preferred methods of operations:

  1. Attaching an event listener when the body loads using jQuery:

     $(function(){ ....
    

    that will catch the form event.

  2. adding onblur / onkeyup to the HTML code and create JS function definition.

What would be better practice?

2
  • Is there a specific problem you're trying to solve by asking the question? Commented Oct 10, 2012 at 11:05
  • yes, my specific problem was which approach to take in JS/HTML development Commented Oct 10, 2012 at 11:09

2 Answers 2

2

It depends on your particular requirements, but in general I would say event listeners are better practice as this seperates your HTML from your javascript logic.

Therefore if you add a new HTML element, this will automatically use your event listener, rather than you having to explicitly set the event call each time.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly the answer i was looking for!
1

The first approach is the way I would go.

This allows you to separate the need to know JavaScript function names in the HTML or HTML generation.

That being said, you should keep the binding actions to HTML actions as loose as possible. You are essentially reversing the dependency of needing to know some attribute of your HTML element to bind to.

You may want to define your action methods and bind the events to them separately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.