Best jquery questions in October 2010

How to normalize HTML in Javascript or jQuery?

71 votes

Tags can have multiple attributes. The order in which attributes appear in the code does not matter. For example:

<a href="#" title="#">
<a title="#" href="#">

How can I "normalize" the HTML in Javascript, so the order of the attributes is always the same? I don't care which order is chosen, as long as it is always the same.

UPDATE: my original goal was to make it easier to diff (in JavaScript) 2 HTML pages with slight differences. Because users could use different software to edit the code, the order of the attributes could change. This make the diff too verbose.

ANSWER: Well, first thanks for all the answers. And YES, it is possible. Here is how I've managed to do it. This is a proof of concept, it can certainly be optimized:

function sort_attributes(a, b) {
  if( a.name == b.name) {
    return 0;
  }

  return (a.name < b.name) ? -1 : 1;
}

$("#original").find('*').each(function() {
  if (this.attributes.length > 1) {
    var attributes = this.attributes;
    var list = [];

    for(var i =0; i < attributes.length; i++) {
      list.push(attributes[i]);
    }

    list.sort(sort_attributes);

    for(var i = 0; i < list.length; i++) {
      this.removeAttribute(list[i].name, list[i].value);
    }

    for(var i = 0; i < list.length; i++) {
      this.setAttribute(list[i].name, list[i].value);
    }
  }
});

Same thing for the second element of the diff, $('#different'). Now $('#original').html() and $('#different').html() show HTML code with attributes in the same order.

This is a proof of concept, it can certainly be optimized:

function sort_attributes(a, b) {
  if( a.name == b.name) {
    return 0;
  }

  return (a.name < b.name) ? -1 : 1;
 }

$("#original").find('*').each(function() {
  if (this.attributes.length > 1) {
    var attributes = this.attributes;
    var list = [];

    for(var i =0; i < attributes.length; i++) {
      list.push(attributes[i]);
    }

     list.sort(sort_attributes);

    for(var i = 0; i < list.length; i++) {
      this.removeAttribute(list[i].name, list[i].value);
    }

     for(var i = 0; i < list.length; i++) {
       this.setAttribute(list[i].name, list[i].value);
    }
  }
 });

Same thing for the second element of the diff, $('#different'). Now $('#original').html() and $('#different').html() show HTML code with attributes in the same order.

jQuery - the good parts?

17 votes

I have embarked on a mission to start using jQuery and JavaScript properly. I'm sad to say that historically I have fallen into the class of developer that makes a lot of really terrible mistakes with jQuery (polluting the global namespace, not caching jQuery selectors, and much more fun stuff - some of which I'm sure I have yet to discover).

The fact of the matter is that jQuery allows people to easily implement some really powerful functionality. However, because everything "just works", performance concerns and best practices immediately take a back seat.

As I've been reading articles on JavaScript and jQuery performance and best practices, I've learned just enough to fully realize how inexperienced I really am. I'm left feeling frustrated because I'm unsure of when I should be using jQuery or just plain JavaScript. The main reason jQuery is so appealing to me is that it takes care of browser compatibility. From what I understand though, there are things you can do with jQuery that you can also do with regular JavaScript that aren't subject to compatibility issues. Basically I'm looking for a guide that explains when using jQuery over regular JavaScript is wise.

A few questions to recap:

Are there parts of jQuery that you shouldn't use due to performance?

What are the parts of jQuery that you should always use to avoid browser inconsistencies?

What are the parts of jQuery that you shouldn't use because there is a reliable and faster way to do the same thing natively in JavaScript?

What are the parts of jQuery that offer multiple ways to do the same thing, with one way being more efficient? For example, the :not() selector versus the .not() method.

I'm looking for existing articles, blog posts, books, videos, etc. I know where the docs are. I read them frequently. I'm hoping for more of an overview that addresses the above issues.

Thanks!

EDIT:

Check out this very similar question: When to use Vanilla Javascript vs. jQuery?

I definitely say

  • use the event model as it abstracts the differences across browsers and also provides a means to raise your own custom events too.

  • don't use .each() or $.each() unneccessarily. Sometimes it can help as it introduces a closure, but often a simple loop will suffice.

  • the only way to know whether a complicated selector string or a bunch of chained function calls is going to be faster is to benchmark all approaches.

  • use event delegation when binding the same event handler to more than three elements (I'll see if I can dig out the resource for more than three elements, I seem to remember an article that benchmarked direct binding versus delegation on a number of different factors and found more than three to be the magic numbers).

  • Above all else, don't worry about performance unless it's a problem. 200ms compared to 300ms, who'll know the difference? 200ms compared to 1000ms, maybe time to look at optimizing something :)

  • be as specific as possible with your selectors and help those poor older versions of IE out.

jQuery: but what about all the children!?

16 votes

I feel like I have to use way too many .children() in some of my jQuery functions.

alt text

Here's my HTML:

<div class="goal-small-container">
  <div class="goal-content">
    <div class="goal-row">
      <span class="goal-actions">

And here's my jQuery:

$('.goal-small-container').hover(function() {
  $(this).children('.goal-content').children('.goal-row').children('.goal-actions').css({visibility: "visible"});
}, function () {
  $(this).children('.goal-content').children('.goal-row').children('.goal-actions').css({visibility: "hidden"});
});

Is there a better way? Tell me for the kids.

.find('.goal-content .goal-row .goal-action').whatever()

or more simply:

.find('.goal-action').whatever()

Why are my particles drifting? ( aka Is Math.random() broken or is it my algorithm? )

16 votes

Using Javascript I'm crudely simulating Brownian motion of particles, but for some reason I don't understand my particles are drifting up and to the left.

The algorithm is pretty straight forward. Each particle is a div and I simply add or subtract a random number from each div's top and left position each round.

I read up on Math.random() a little, and I've tried to use a function that returns a random number from min to max inclussive:

// Returns a random integer between min and max  
// Using Math.round() will give you a non-uniform distribution!  
function ran(min, max)  
{  
    return Math.floor(Math.random() * (max - min + 1)) + min;  
} 

Here is the function for the movement of the particles:

var x, y, $elie, pos, nowX, nowY, i, $that;    

function moveIt()
{
    $("div.spec").each(function(i, v) {
        x = ran(-5, 5);
        y = ran(-5, 5);
        $elie = $(v);
        pos = $elie.position();
        nowX = pos.left;
        nowY = pos.top;

          // The min and abs are to keep the particles within a box
          // The drift occurs even if I remove min and abs
        $elie.css("left", Math.min(Math.abs(nowX + x), 515));
        $elie.css("top",  Math.min(Math.abs(nowY + y), 515)); 
    });
}

And here is how the particles are initially set up an the setInterval started.

$(function() {
    $("body").append("<div/>").attr("id","box");
    $elie = $("<div/>").attr("class","spec");
    // Note that math random is inclussive for 0 and exclussive for Max
    for (i = 0; i < 25; ++i)
    {
        $that = $elie.clone();  
        $that.css("top", ran(0, 495));
        $that.css("left", ran(0, 495));            
        $("#box").append($that);            
    }          
    timer = setInterval(moveIt, 60);
    $("input").toggle(function() {
        clearInterval(timer);
        this.value = " Start ";
    }, function() {
        timer = setInterval(moveIt, 60);        
        this.value = " Stop ";            
    });        
});

My problem is that using the min and max from above ( -5, 5 ), all the particles drift up and to the left very fast.

jsFiddle example of drift (-5, 5)

Example of drift even with the removal of .min() and .abs().

To counteract this, I have to use a min and max of -1, 5.

jsFiddle example of no drift (-1, 5)


Here is the CSS for the div all the particles are contained in:

#box {
    width:500px;
    height:500px;
    border:2px #000 solid;
    position: relative; }

Here is the default CSS for each particle:

div.spec {
    width:5px;
    height:5px;
    background-color:#00DDAA;
    position:absolute; }

What is going on? Why does a min and max of -5 and 5 cause an upward and leftward drift?

A test of the random function ran() doesn't seem to show such a persistent negative drift.

jsFiddle example of testing ran()



The ran() function was taken from the MDC Math.random() page.

Your mistake is to use

pos = $elie.position();

rather than

pos = $elie.offset();

This wouldn't have made a difference had they been added to parent div, but your elements aren't properly added to a parent div, they're appended directly to the document body. So your other mistake is this:

$("body").append("<div/>").attr("id","box");

If you want the div to have id of 'box', the line should read:

$box = $("<div/>").attr("id","box");
$("body").append($box)

Otherwise you're actually giving "body" the id of "box"

EDIT:

The most efficient way to append the div would be the following (as noted by this post):

$(document.createElement('div')).appendTo('body').attr('id', 'box')

Options for ASP.NET page with matching client-side and server-side markup?

12 votes

Suppose I'm building a StackOverflow clone using webforms ASP.NET and jQuery. The Question page has a question, several answers, and comments under each. Requirements:

  1. Users can post new answers and comments, and edit existing ones, without postbacks.
  2. No UpdatePanels; the AJAX calls retrieve just the JSON they need, not HTML fragments.
  3. The page loads with all existing answers and comments in place (no javascript needs to run to read the page).

What I'm trying to figure out is how to do this without having to maintain two sets of markup (one that's bound on the client using some form of jQuery templating, and one that's bound on the server using traditional WebForms).

What are my options?

While it is not exactly what you asked for you may want to consider rendering the HTML on the server via a service (not using update panel) and sending it to the client instead of using client templates. It couldn't be that bad because Facebook are doing it: http://www.facebook.com/video/video.php?v=596368660334 If it is suitable in your situation depends on how rich your markup is and what percentage of the data sent over the wire will be markup as opposed to content.

Using Knockout.js with newest jQuery Files and ASP.NET MVC

10 votes

I am attempting to use Knockout.js with ASP.NET MVC 3.0 (Title gave it away, didn't it?!)

http://knockout.js.com

I am running into some problems (more related to the new jQuery Tmpl Engine than ASP.NET MVC 3.0).

I am using Steve Sanderson's Example Program in my test, and have mostly replicated his results with the new Razor View Engine (I do not believe Razor has anything to do with my problem).

http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/

However I want to do more with the natural jquery binding, instead of the HTML binding attributes. This is described in detail on knockout's tutorial. http://knockoutjs.com/documentation/template-binding.html

However I am unable to reproduce this as it explains. I will show below my View Code. My problem is coming from the fact that {{foreach (i, gift) gifts}} doesn't work. I have tried many variants ( {{foreach (i, gift) gifts()}} as I have seen in other examples).

I am using the latest knockout.js file. I am using jQuery 1.4.3. I am using http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js for templating engine. However, I have also tried this using the same tmpl.js file that is included on knockous.js's website, and I get the same results.

When using jQuery Templating, Per the current specification, the template does not render.

The jQuery Template Tags Documentation is found Here : http://api.jquery.com/category/plugins/templates/template-tags/

In case anyone was confused about my exact model. If I replace {{foreach (i, gift) gifts}} with {{foreach gift}}, then the model renders and behaves correctly, but I cannot use the jQuery native ${property} declarations for anything.

HTML

@model IEnumerable<Knockout.GiftModel>
@using System.Web.Script.Serialization;

@{
    View.Title = "Index";
    Layout = "~/Views/Shared/_Site.cshtml";
}

    <h2>Gift list editor</h2>

    <form class="giftListEditor" action="/home/index" method="post" >
        <table> 
            <tbody data-bind="template:'giftRowTemplate'"></tbody> 
        </table>

        <button data-bind="click: addGift">Add Gift</button>
        <button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
    </form>

    <script type="text/html" id="giftRowTemplate">
        {{each (i, gift) gifts}}
        <tr> 
            <td>Gift name: <input class="required" data-bind="value: Title, uniqueName: true" /> ${Title} </td> 
            <td>Price: $ <input class="required number" data-bind="value: Price, uniqueName: true"/></td> 
            <td><a href="#" data-bind="click: function() { viewModel.removeGift( $value ) }">Delete</a></td> 
        </tr>
        {{/each}}
    </script>

    <script type="text/javascript">
        var initialData = @(new HtmlString(Model.ToJson()));
        var viewModel = {
            gifts: ko.observableArray(initialData),
            addGift: function () {
                this.gifts.push({ Title: "", Price: "" });
            },

            removeGift: function (gift) {
                this.gifts.remove(gift);
            },

            save: function () {
                ko.utils.postJson(location.href, { gifts: this.gifts });
            }
        };

        ko.applyBindings(viewModel);
        $("form").validate({ submitHandler: function() { viewModel.save() } });
    </script>

I would approach this differently. I would use the following line:

<tbody data-bind='template: { name: "giftRowTemplate", foreach: gifts }'></tbody>

instead of:

<tbody data-bind="template:'giftRowTemplate'"></tbody>

That way you dont need to use the {{each (i, gift) gifts}} line in the template that is giving you trouble.

Why Doesn't jQuery use JSDoc?

10 votes

Or do they and it's just not in the source? I'd really like to get something that will stop js-doc-toolkit from freaking out each time it parses jQuery. It also means I can't properly document any code using jQuery as a dependency without at least putting some boilerplate js-doc blocks, which fail to properly document jQuery's structure. Is there a common solution I'm not aware of? I have tried googling, btw.

I'll take a shot in the dark here since I can't speak for the jQuery team of why I wouldn't use JSDoc. JSDoc, at least the last time I checked, didn't have any clean way to support method overloading (or parameter shifting...whatever name you want to give it here) and jQuery uses this all over the place. Let's take a simple common example with .animate():

.animate({ height: 5 })
.animate({ height: 5 }, 100)
.animate({ height: 5 }, 100, "linear")
.animate({ height: 5 }, 100, "linear", func)
.animate({ height: 5 }, 100, func)
.animate({ height: 5 }, func)
.animate({ height: 5 }, { duration: 100, queue: false })
.animate({ height: 5 }, { duration: 100, easing: "linear" })
.animate({ height: 5 }, { duration: 100, easing: "linear", complete: func })

All of these are valid, since parameter types are checked and shifted as needed to support as any overload scenarios as possible...this just confuses the hell out of JSDoc, there's no clean way to add these optional parameters to the documentation. Please correct me if this has changed, but last I looked (and probably the last time the team took a look) this was still the case.

Another potential consideration is how some methods are generated when jQuery runs, for example (one of many) almost all then event handler shortcuts are generated in a loop, similar behavior for other methods...how would you document these? JSDoc generation just really doesn't work well here.

can any one explain me what is JSONP in layman terms

9 votes

I known JSONP is (JSON padding) . I Know what is JSON and using it in $.getjson in jquery is also known But using jsoncallback cannot be understood and what is JSONP

JSONP is a method commonly used to bypass the cross-domain policies in web browsers (You are not allowed to make AJAX requests to a webpage perceived to be on a different server by the browser).

JSON and JSONP behave differently on both the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest (and the associated browser methods), instead a <script> tag is created, which source is set to the target URL. This script tag is then added to the DOM (normally the <head>).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

The difference between a JSON response and a JSONP response, is that the JSONP response is formulated such that the response object is passed as an argument to a callback function.

JSON:

{
    "foo": "bar"
}

JSONP:

yourCallbackFunction({
    "foo": "bar"
});

This is why you see JSONP requests containing the "callback" parameter; so the server knows the name of the function to wrap the response around.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).


Another difference to be aware of between the handling of a JSON response and a JSONP response, is that any parse errors in a JSON response can potentially be caught (by wrapping the attempt to evaluate the responseText in a try/catch statement). Because of the nature of a JSONP response however, parse errors in the response will yield an uncatchable JS Parse error. Both formats however, can implement timeout errors (by setting a timeout before initiating the request, and clearing the timeout in the response handler.


The usefulness of using jQuery to make JSONP requests, is that jQuery does alllllllll of the work for you in the background.

jQuery requires (by default), for you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name and publish it in the global scope. It will then replace the ? in &callback=? with the name it's just assigned the function.


Comparable JSON/ JSONP Implementations (assuming response object is {"foo":"bar"}:

JSON

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("foo").innerHTML = eval('(' + this.responseText + ')').foo;
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP:

function foo(response) {
  document.getElementById("foo").innerHTML = response.foo;
};

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

Drupal behaviours

9 votes
  • What are Drupal behaviours at all?

  • What type of service layer it offers to module developers?

  • What type of relation it maps to jQuery.ready function?

Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.

Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).

Short version: it's more modular, though the documentation could be improved.


Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.

For example:

Drupal.behaviors.changeLinks = function(context, settings){
    if (!settings) settings = Drupal.settings.changeLinks;
    $("a", context).hover(function() {
        $(this).css('color', settings.color);
    });
};

And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:

var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');

Drupal.attachBehaviors(newNodes);

What libraries does Google host (other than jQuery) ?

9 votes

First, I apology if I used the wrong term in the question (Please feel free to edit if I'm wrong).

I know Google hosts (almost) all version of jQuery, jQuery UI (js and css)

For example :

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>

or for CSS :

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" type="text/css" />

My question is : Does it host other library? Useful plugin as jQuery UI? Other templace or CSS?

Available Libraries:

  • Chrome Frame
  • Dojo
  • Ext Core
  • jQuery
  • jQuery UI
  • MooTools
  • Prototype
  • script_aculo_us
  • SWFObject
  • Yahoo! User Interface Library (YUI)
  • WebFont Loader

CSS files:

The new jQuery Templates from Microsoft and SEO

8 votes

Scott Guthrie just blogged about the new jQuery Templates that his team has been working on, and I must say... this looks really sweet. I have a multi-part question however, where the answer will influence my decision to use them.

I'm currently working on a project whereby the home page displays a list of upcoming events in your region. The event listing is much the same as that in http://nerddinner.com (but I'm not using any of their code).

I'm thinking about using the new jQuery Templates to format the information sent from my Controller (MVC). The current way I'm doing this is to send the ViewModel Object to the view (with all of the needed content), but to ALSO serialize the same ViewModel Object into JSON (passed using ViewData) that is used by the Bing Maps. Now I'm assuming that there's a performance hit in sending the same content twice, and therefore I think that sending JSON only and using it for both the Bing Maps and the content (using jQuery Templates) is a great idea.

In walks my question. Can search engines read the JSON in the page (and if so, will they use it for indexing), or are my pages going to be "blank" to the search engine because I'm displaying the content AFTER the page renders? The second part of this question is that, IF SEO will be affected, is there a better way of accomplishing what I need, or am I stuck sending the content twice? (remember, the map info and the content info will be exactly the same).

The templates are all JavaScript at the moment, something a crawler isn't going to execute. Google support AJAX enabled sites in a certain format...but no you won't see crawler support for this, at least not in the new future.

If anything, it'll hurt SEO...the price you pay for using newer technologies/formats the crawlers aren't designed to handle yet.

Warning: This answer has a shelf-life (hopefully) and should be invalid at some point (current date - Oct 05, 2010)...someone please edit me when this happens (and search engines handle this well).

Get *all* CSS attributes with jQuery

8 votes

Here's how you get one css attribute using jQuery:

$('someObject').css('attribute')

How do you get them all? (without specifying and preferably in the following format so it can be reapplied with jQuery later):

    cssObj = {
        'overflow':'hidden',
        'height':'100%',
        'position':'absolute',
    }

Thanks!!

EDIT

The methods I'm trying to get are declared in a style sheet (they are not inline). Sorry for not specifying.

What about something like this:

http://stackoverflow.com/questions/1004475/jquery-css-plugin-that-returns-computed-style-of-element-to-pseudo-clone-that-ele

It is ugly, but it appeared to work for the poster...

This also may be of interest: https://developer.mozilla.org/en/DOM:window.getComputedStyle

Why do people call the jQuery $ alias a 'factory'?

8 votes

On various sites, jQuery's $ variable is referred to as an alias, and on others, it is referred to as a factory. I took a look at the source code, and I think the former is correct. As far as I can see, the dollar symbol is being defined here:

// Expose jQuery to the global object
return (window.jQuery = window.$ = jQuery);

This is setting both $ and jQuery to the SAME alias; there is no 'factory' for jQuery objects. Are the sites referring to $ as a 'factory' simply wrong?

I think either is an okay term. The dollar sign is certainly an alias for the jQuery function, specifically to be used as a shorthand. If someone refers to the function as a factory, I don't think that's specific to the $ alias, but just describing what the jQuery function does in general, which is create objects from various different types of input.

using slick upload with mvc 2 and jquery / ajax

7 votes

i'm trying to get slick upload working inside a jquery ui dialog. I've got it uploading the file just fine, and i've checked out the samples, and they all end up with the entire page re-loading. i've managed to make it so it doesn't do it's final postback to deal with the files after it uploads by setting the AutoPostBackAfterUpload="false"

so it now puts the files on the server, with the random guid name. and it get's a response that looks like this:

{
state : "Complete",
reason : "NotTerminated",
percentComplete : 100.00,
percentCompleteText : "100.00 %",
contentLengthText : "826 KB",
transferredLengthText : "826 KB",
remainingLengthText : "0 bytes",
currentFileName : "Desert.jpg",
currentFileIndex : "1",
timeElapsedText : "1 second",
timeElapsedShortText : "00:01",
timeRemainingText : "",
timeRemainingShortText : "00:00",speedText : "596 KB/sec"
}

so what i need to know is: how do i ajaxly post what slick upload does automatically when you have the AutoPostBackAfterUpload set to true.

here's my code: <% Html.BeginForm("OrganizationMemberEditContactSectionChangePhoto", "OrganizationMember", FormMethod.Post, New With {.id = "uploadForm", .enctype = "multipart/form-data"})%>

    <kw:SlickUpload ID="SlickUpload1" runat="server" AutoPostBackAfterUpload="false"  UploadFormId="uploadForm" ShowDuringUploadElements="cancelButton" HideDuringUploadElements="uploadButton" MaxFiles="1" AutoUploadOnPostBack="false" ProgressInterval="200">
        <DownlevelSelectorTemplate>
            <input type="file" />
        </DownlevelSelectorTemplate>
        <UplevelSelectorTemplate>
            <input type="button" value="Add File" />
        </UplevelSelectorTemplate>
        <FileTemplate>
            <kw:FileListRemoveLink runat="server">[x] remove</kw:FileListRemoveLink>
            <kw:FileListFileName runat="server" />
            <kw:FileListValidationMessage runat="server" ForeColor="Red" />
        </FileTemplate>
        <ProgressTemplate>
            <table width="99%">
                <tr>
                    <td>
                        Uploading <kw:UploadProgressElement ID="UploadProgressElement1" runat="server" Element="FileCountText" />,
                        <kw:UploadProgressElement ID="UploadProgressElement2" runat="server" Element="ContentLengthText">(calculating)</kw:UploadProgressElement>.
                    </td>
                </tr>
                <tr>
                    <td>
                        Currently uploading:
                        <kw:UploadProgressElement ID="UploadProgressElement3" runat="server" Element="CurrentFileName" />,
                        file <kw:UploadProgressElement ID="UploadProgressElement4" runat="server" Element="CurrentFileIndex">&nbsp;</kw:UploadProgressElement>
                        of
                        <kw:UploadProgressElement ID="UploadProgressElement5" runat="server" Element="FileCount" />.
                    </td>
                </tr>
                <tr>
                    <td>
                        Speed:
                        <kw:UploadProgressElement ID="UploadProgressElement6" runat="server" Element="SpeedText">(calculating)</kw:UploadProgressElement>.
                    </td>
                </tr>
                <tr>
                    <td>
                        About
                        <kw:UploadProgressElement ID="UploadProgressElement7" runat="server" Element="TimeRemainingText">(calculating)</kw:UploadProgressElement> remaining.
                    </td>
                </tr>
                <tr>
                    <td>
                        <div style="border: 1px solid #008800; height: 1.5em; position: relative">
                            <kw:UploadProgressBarElement ID="UploadProgressBarElement1" runat="server" Style="background-color: #00ee00; width: 0; height: 1.5em" />
                            <div style="text-align: center; position: absolute; top: .15em; width: 100%">
                                <kw:UploadProgressElement ID="UploadProgressElement8" runat="server" Element="PercentCompleteText">(calculating)</kw:UploadProgressElement>
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
        </ProgressTemplate>
    </kw:SlickUpload>
    <p>
        <input type="button" value="Upload" id="uploadButton" />
        <a href="javascript:kw.get('<%=SlickUpload1.ClientID %>').cancel()" id="cancelButton" style="display:none">Cancel</a>
    </p>            
<%Html.EndForm()%>
<script type="text/javascript">
    var theThing;
    var urlToPost = "theUrlThatHandlesThePostBack";
    function v2SetUpPhotoDialog() {

        theThing = kw.get("<%=SlickUpload1.ClientID %>");
        theThing.add_OnUploadEnded(function (status) {
            var data = $('#uploadForm').serialize();
            $.ajax({
                type: 'POST',
                url: urlToPost,
                data: data,
                success: function () {
                    v2RegularNotice('success');
                },
                error: function () {
                    v2RegularNotice('fail');
                }
            });
        });

        $('#uploadButton').live('click', function () {
            theThing = kw.get("<%=SlickUpload1.ClientID %>");
            theThing.submit();
            return false;
            //  kw.get("<%=SlickUpload1.ClientID %>").submit();
        });
    }
</script>

as you can see, i tried having the OnUploadEnded take the status as a parameter, but it doesn't fill it with any of the useful information that the status parameter for the action needs. It currently serializes the form and sends that, but it only populates 1 field. kw_uploadId.

the controller action doesn't do anything yet, it just tries to take a UploadStatus as a parameter. but it's empty if i just serialize the form.

i'm sure i'm missing something obvious. but i can't figure it out. i'm finding the documentation kind of hard to follow and not to helpful in this case.

thanks!

After working with Patrica, this issue has been solved. We ran into a couple more snags, but the basics are as follows:

The main thing at work here is a limitation in SlickUpload's design: you can't remove a SlickUpload control from the DOM once it's been added and then readd it again later. This will be solved in SlickUpload6, but is unfortunately a limitation with the current version. To solve this, we hid the control when the tab or dialog was invisible, instead of actually removing it.

There is also a SlickUpload minor version release (5.5.9) that adds a get_UploadId() method, to make getting the upload id for the current upload easier.

This code (from above):

kw_uploadId: document.getElementById("kw_uploadId").value,

becomes:

kw_uploadId: theThing.get_UploadId(),

You can get the latest version here: SlickUpload 5.5.9

jQuery: Detecting pressed mouse button during mousemove event.

7 votes

I tried to detect which mouse button -if any- is the user pressing during a mousemove event under jQuery, but I'm getting ambiguous results:

no button pressed:      e.which = 1   e.button = 0
left button pressed:    e.which = 1   e.button = 0
middle button pressed:  e.which = 2   e.button = 1
right button pressed:   e.which = 3   e.button = 2

Code:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>

<input id="whichkey" value="type something">
<div id="log"></div>
<script>$('#whichkey').bind('mousemove',function(e){ 
  $('#log').html(e.which + ' : ' +  e.button );
});  </script>

</body>
</html>

How can I tell the difference between left mouse button pressed and no button at all?

You can write a bit of code to keep track of the state of the left mouse button, and with a little function you can pre-process the event variable in the mousemove event.

To keep track of the state of the LMB, bind an event to document level for mousedown and mouseup and check for e.which to set or clear the flag.

The pre-processing is done by the tweakMouseMoveEvent() function in my code. To support IE versions < 9, you have to check if mouse buttons were released outside the window and clear the flag if so. Then you can change the passed event variable. If e.which was originally 1 (no button or LMB) and the current state of the left button is not pressed, just set e.which to 0, and use that in the rest of your mousemove event to check for no buttons pressed.

The mousemove handler in my example just calls the tweak function passing the current event variable through, then outputs the value of e.which.

$(function() {
    var leftButtonDown = false;
    $(document).mousedown(function(e){
        // Left mouse button was pressed, set flag
        if(e.which === 1) leftButtonDown = true;
    });
    $(document).mouseup(function(e){
        // Left mouse button was released, clear flag
        if(e.which === 1) leftButtonDown = false;
    });

    function tweakMouseMoveEvent(e){
        // Check from jQuery UI for IE versions < 9
        if ($.browser.msie && !(document.documentMode >= 9) && !event.button) {
            leftButtonDown = false;
        }

        // If left button is not set, set which to 0
        // This indicates no buttons pressed
        if(e.which === 1 && !leftButtonDown) e.which = 0;
    }

    $(document).mousemove(function(e) {
        // Call the tweak function to check for LMB and set correct e.which
        tweakMouseMoveEvent(e);

        $('body').text('which: ' + e.which);
    });
});

Try a live demo here: http://jsfiddle.net/G5Xr2/

Rails tutorial for the dumbest person in the world (me)?

6 votes

It is very difficult for me to find Rails tutorials (or books are also great) for my requirements:

  1. Stupidity
  2. Ruby 1.9 or lastest 1.8
  3. MySQL
  4. A Game (simple roll play)
  5. JQuery front

Thanks you!

The Rails Guides are great and easy on the eyes too.

Implementing a random chat among people

6 votes

My idea is to make a website, where people could registry and search for a people to talk. They can choose people from certain country, genre, with certain age and so on.

Yeah, I know there is a lot of websites like this, but I want to implement this, because it looks really challenging.

Can you give me ideas how could I implement this using PHP + MYSQL + Jquery(Ajax)? I am neither a beginner nor advanced with these things.

So, how should this work? One person clicks search button, this person is put in database that he searches for somebody to talk, so what's next? I also want to be able to allow people to talk with a few people at the same moment.

I am not asking for a code or something, just ideas how to code it, no code needed.

Thank you.

I don't think that a synchronous, blocking programming language like PHP is the right platform for such an application. It were much wiser to choose an asynchronous, non-blocking language like JavaScript. This has the great advantage that you may use Long Polling which will improve the chatting experience in your application.

Thus I recommend implementing this using NodeJS. You may want to look at an implementation of a simple chat in node.

HTML formatter/tidy/beautifier for JavaScript

6 votes

Is there any HTML formatter/tidy/beautifier out there written in JavaScript?

I have made a content editor (CMS) which has both WYSIWYG and source code views. The problem the code written by the WYSIWYG editor is normally a single line. So I would like a JavaScript that could format this into a more readable form on demand.

You may find this to be useful:

http://github.com/einars/js-beautify

It is the source code powering the site http://jsbeautifier.org/

How to make facebook like private message

6 votes

When you send a private message to someone on FB in the TO field when typing the first letter a suggestion appears then it becomes a little box with the name of the user you selected which can be deleted, anyone got a tutorial on this? thanks

This looks like it'll do the trick.

Load local JSON files via file:// triggers cross-domain null origin violation, solution? (jQuery)

5 votes

I have a webpage I'd like to use locally, without a web server, by simply opening the local HTML file in my browser. This webpage in question loads data via jQuery's getJson() method, as in:

$.getJSON("mydata.json", function(j) { 
...

The JSON files are also local, and are stored in the same directory as the webpage. When I attempt to use the page, I get:

Origin null is not allowed by Access-Control-Allow-Origin.

(Chrome 6 OS X, similar errors in Firefox and Safari).

Is there any way around this? Is it possible to load JSON from local files? Thanks!

Try running Chrome with --allow-file-access-from-files.