views:

3633

answers:

4

I've just started looking at JQuery. I don't have any AJAX in my web application at present.

My existing JavaScript in my HTML looks like:

<form ...>
<p>Find what? <input ...></p>
<div class="ButtonArray">
  <a href="AddRecord.ASP&amp;Action=ADD">ADD</a>
  <a href="#" onClick="return MyFormSubmit();">FIND</a>
</div>
</form>

This displays Buttons for [Add] and [Find]. For Find it is necessary to Submit the form, and I use MyFormSubmit() which validates the data, adds a visual effect to the page, and then POSTs the data.

I could add a CLASS or ID to the for the Find button and in JQuery I could write something like:

$(function() {
  $(".MySearchButtonClass").click(function() {
    // validate and process form here
  });
});

At my "novice" stage of understanding with JQuery I don't get why I would do it this way

My old way identifies the Method near the object. There may be a risk that the JS has not loaded before the user presses the button (is there? The LOAD for the JS is right at the top of the page).

The JQuery Document Ready method won't be activated until the document is loaded (which I assume guarantees that the JS is all present and ready to be run?), but it moves the code to a separate part of my HTML file - so when I see the MyButtonArray DIV in the HTML source it isn't obvious to me which objects have methods, and which do not.

Can you please help me understand what my options are and the benefits / gotchas that I should look out for?

Edit: I'm comfortable that DOM manipulation - such as a LightBox that can appear when any thumbnail with class "LightBoxThumb" is clicked - would use Unobtrusive Javascript.

However I am struggling to persuade myself that a button that has a specific action should have its method applied in that way. (I certainly wouldn't put any code on the button other than a single function call to something "elsewhere", but to my mind that is my best clue as to what that button does, and layers of Unobtrusive Javascript may make that much harder to determine.)

Edit2 - Accepted Answer

I've taken Russ Cams answer. It describes Unobtrusive Javascript in a way that has been helpful to me in understanding more about how & when that should be used.

For the moment (may change when I have more experience!) I'll stick with an OnClick event for a single, non-changing, action on an object as I feel that will be easier for me to debug - and diagnose if problems arise. For ZebraStripes on a table that allows click on heading column to sort (and situations of that type) I can see the benefits of the Unobtrusive Javascript approach

Russ's final comment was particularly helpful, repeated here:

"@Kristen - You're right, like a lot of programming topics, there is more than one approach and people will vehemently stand by their beliefs! If we're talking about a single method for a single button, I totally understand where you're coming from...

If we're talking about lots of JavaScript, with same function calls for more than one element, different function calls for different methods, etc. I think that it would be more difficult for oneself to mix inline and unobtrusive approaches, and it would be better to adopt one or the other approach"

A: 

You do it this way to seperate the UI logic from the actual HTML design.

Thomas Stock
Thanks, yes I can see that, but all I have on my HTML is a single call "MyFormSubmit()". My actual code for MyFormSubmit() is in a separate include file - I just think it helps me to see the Method on the HTML Tag, rather than having to look elsewhere to see if there MAY be a method
Kristen
I have to confess that I agree with Kristen: I find it easier to maintain/troubleshoot an onclick attribute tied to a single func, rather than an assigned event listener which may or may not have been attached at some point.
Luke Dennis
perhaps, but do you really need to see the onClick event to know that btnSubmit is going to do something? If I need to change the function executes on a submit button click, I just go in my .js file to the region "key events" and search for function btnSubmit_click().
Thomas Stock
I also assign event listeners in a script block because they work well with dynamically created DOM objects. I put my binding in a BindEmployeeEvents() javascript function which I call whenever the user adds an employee. Not really needed for a static button tho, I agree.
Thomas Stock
+11  A: 

Unobtrusive JavaScript is the main driver for separating JS code from markup

  • Separation of functionality (the "behavior layer") from a Web page's
    structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support
    advanced JavaScript functionality

With the code in document.ready, it will not execute until the DOM has loaded and before the page contents are loaded

From Learning jQuery

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads.

You may want to take a look at jQuery in Action, I'd highly recommend it. You can sample Chapter 1 and Chapter 5 on the book's homepage. I think doing so may provide further insight into why separation can work well.

Finally, have a look at this question which has answers that detail how you would find the event listeners on a DOM node.

EDIT:

Some thoughts which may persuade you why unobtrusive JavaScript can be a good idea.

Imagine that you have a function bound as an event handler for the same event raised on each of a number of elements -

  • Would it be easier to find out which elements call that function to handle an event when the declaration is inline in each element, or the declaration is in one place, outside of the markup?

  • What if you want to add to the elements that call that function when the event is raised on each of them? Would it be easier/better to add the event handler inline to each element or to change the code in one place?

Russ Cam
Thanks; the reference to Unobtrusive JavaScript is very helpful; I've seen "jQuery in Action" recommended before and its on my shopping list! I'll have a read of the sample chapters.
Kristen
PS Links to sample chanters look correct, but didn't work for me direct from this page - but they are available on that site at on this page: http://www.manning.com/bibeault/
Kristen
"same event raised on each of a number of elements" no problem with that - Zebra Strips on a table that allowed click-column-heading for Sort, for example. What I'm struggling with the case of this single-method submit button.
Kristen
Kevink suggests class="MyFormSubmit" to replace onClick="return MyFormSubmit(); - which seems no less Unobtrusive to me! in fact I don't see how using a Styling Class to identify an OnClick Action is anything other than a kludge!
Kristen
I think there are either two-schools-of-thought here (like many of the coding "religions"), or I just need more JQuery experience before I "get" it.
Kristen
@Kristen - You're right, like a lot of programming topics, there is more than one approach and people will vehemently stand by their beliefs! If we're talking about a single method for a single button, I totally understand where you're coming from...
Russ Cam
If we're talking about lots of JavaScript, with same function calls for more than one element, different function calls for different methods, etc. I think that it would be more difficult for oneself to mix inline and unobtrusive approaches, and it would be better to adopt one or the other approach
Russ Cam
Great, that's a relief! Thanks for your help and patience.
Kristen
+2  A: 

Hi,

the document ready event is well before the document load event. document ready occurs once the DOM is loaded which is so that all the elements exist before you start working on them.

So yes the JS will be ready as the document is rendered. The other point about binding is that it is useful for changing bindings to elements when cetain actions occur.

You can still declare the action on the element if you prefer though.

Richard
Very helpful, thank you.
Kristen
+1  A: 

Over time I think you get used to the jQuery syntax and reading:

class="MyFormSubmit" becomes as informative as reading onClick="return MyFormSubmit();

Where the power really starts to kick in (aside from all the benefits mentioned by other posters) is the ease with which you could change the onClick binding via selectors tied to other actions on the web page in ways that never seem to present themselves initially.

One question I ask myself is how deep I plan on going with any new tool, if I am planning to make extensive use of a framework or library then writing my code in it's "more native" coding style will become a lot more natural and other developers that know the tool will find the code a lot cleaner and more understandable.

kevink