Skip to main content

Posts

Showing posts from April 9, 2012

JQuery Templates - too much recursion

I am using jquery templates to generate a tree structure to later display as a treeview of sections and items. The structure of data looks like this, where each section has items and sections and each item can have more sections: section items item sections item sections sections section sections items ...and so on My templates then recursively call each other: <script id="my-item-tmpl" type="text/x-jquery-tmpl"> <li> <span>${text}</span> <ul> {{each sections}} {{tmpl($value) "sectionTmpl"}} {{/each}} </ul> </li> </script> <script id="my-section-tmpl" type="text/x-jquery-tmpl"> <li> <span>${text}</span> <ul> {{each items}} {{tmpl($value) "itemTmpl"}} {{/eac

Is it possible to upload file via $.ajax(options) or xhr.send(file) only?

I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working. Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than var xhr = new XMLHttpRequest(); xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-File-Name", file.name); xhr.send(file); Which doesn't return Promise that I can use in the recursion function. My code is like this : startUpload: function() { var that = this; that.recurseSend(that.queue); }, _initProgressListener: function (options, file) { var that = this; var xhr = $.ajaxSettings.xhr(); options.contentType = 'multipart/form-da

HTML5 script element - async attribute - when (and how best) to use?

Can you confirm my understanding of HTML5's <script async> attribute? Any libraries referenced by other code in the page should not specify the async attribute. For example, my script references might appropriately look like: <script src="jquery..." /> <!-- async not used - ensure that this is loaded before JQuery UI and my code --> <script src="jquery.ui..." /> <!-- async not used - ensure that this is loaded before my code --> <script src="my_code1.js" async /> <!-- async used, for page load performance --> <script src="my_code2.js" async /> <!-- async used, for page load performance --> For any code in a $(document).ready(function () { } block, I can be assured that all async script have already loaded. Do I have this right? Source: Tips4all

problem in file upload

I have the following markup: <select multiple="multiple" id="targetFilesList" style="width:200px;height:110px;"> </select> <input type="button" value="Get" id="btnGet" /> and following javascript: $(function() { $('#btnGet').click(function() { var fileupload = $("<input type='file' name='filetoupload' style='visibility:hidden;'/>"); $('body').append(fileupload); fileupload[0].onchange = function() { $('#targetFilesList').append('<option >' + fileupload.val() + '</option>'); return false; } fileupload.click(); }); }); Scenario is that i have to upload multiple files and once user has chosen the file to be uploaded i have to show the file name to user.Then,on submitting the

How to send FormData objects with Ajax-requests in jQuery?

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests). Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in my other question ). This is how it works (example): var xhr = new XMLHttpRequest(), fd = new FormData(); fd.append( 'file', input.files[0] ); xhr.open( 'POST', 'http://example.com/script.php', true ); xhr.onreadystatechange = handler; xhr.send( fd ); where input is a <input type="file"> field, and handler is the success-handler for the Ajax-request. This works beautifully in all browsers (again, except IE). Now, I would like to make this functionality work with jQuery. I tried this: var fd = new FormData(); fd.append( 'file', input.files[0] ); $.post( 'http://example.com/script.php', fd, handler ); Unfortunately, that won't w

JQGRID: any easy way to implement undo on excel like jqGrid implementation

Just to give little update before putting my question.... I've been able to come up with some additional features on the jqgrid that I'm using (after going through many forums) including: copy-paste back and forth from Excel to jqgrid, edit cell on keypress and dblclick, copy and paste multiple cells from one block to another on the same grid using mouse selection (from here Using Javascript to 'sum selected cells' in IE6 ) Most of the copy paste features works on IE only as of now. I save all the changes together on "Save" button click so all the updates on the cells are on screen only until user hits the "Save" button. Although, things are still in flux right now, I'd like to have the implementation design on paper now than later. I'm looking for an easy way to UNDO only the LAST change. I've been thinking of using jQuery's "data()" and "removeData()" methods to implement this but if there is anything al

var x, y = "foo"; Can this be accomplished?

Since it is possible to do: var x = 'foo', y = 'foo'; Would this also be possible? var x, y = 'foo'; I tried it, however x becomes undefined. I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope . That is not the point of the question. I'm just curious. Source: Tips4all

jQuery leaks solved, but why?

I am working on a large enterprise application with a LOT of JavaScript. Enough that I can't possibly go through and fix all the small circular references that have been created over its past 5 years of development. While researching solutions I came across this small jQuery hack/patch: http://kossovsky.net/index.php/2009/07/ie-memory-leak-jquery-garbage-collector/ and decided to try it. Amazingly, it works! sIEVE shows no leaks in the places I had previously identified them and the iexplore task is maintaining a more manageable memory footprint. My question is, why does this work? jQuery.remove calls .removeChild, which should get rid of the element, but apparently does not. The patch instead appends the target element onto a new garbage collector div, which it then clears. Why does the patch method of removal completely free up the memory but jQuery's remove function does not? I'm hoping to understand why this works in order to possibly improve the solution before

How does Backbone.js keep track of DOM elements without using IDs?

Background I have been using Backbone.js for some time and one aspect of it that impresses me is how it allows me to simplify, abstract and reuse DOM elements as 'views' . I have tried to read through some of the annotated source and am familiar with JQuery, but have little knowledge of how the DOM works on a deeper level. Question How does Backbone.JS tie DOM elements to views without assigning an id, class or other attribute to them? i.e. <ul> <li>Item one</li> <li>Item two</li> <li>Item three</li> </ul> I love that Backbone does this and would like to know how it does it! Source: Tips4all

Dialog Click listener not triggering in IE8 or Firefox with jQuery

I have this click listener and for some reason it's not triggering in IE8 or Firefox: console.log("listener attached"); jQuery(".ui-button-text").click(function() { console.log("this should have triggered"); var ajaxUrl = '/ajax.php?popup=true'; var dataString = "param="+param+"&param2="+param2; // contruct the ajax request jQuery.ajax({ url: ajaxUrl, dataType: 'json', data: dataString, beforeSend: function() { jQuery(".ui-button-text").html("Saving..."); }, complete: function() { jQuery(".ui-dialog-content").dialog("close"); }, success:function(response){ } }); }); So I can see the "listener attached" in the console, but I don't see the click trigger, this works in

DOM Mutation event in JQuery or vanilla Javascript

Are there any DOM mutation events in JQuery or in vanilla Javascript that fire cross browser? To clarify, say I have a script on my page which inserts a div into the body. I don't have access to the script and I don't know when the div has been inserted. I was wondering if there's a DOM mutation event that I can add a listener for to know when the div has been inserted. I know I can use some kind of timer to periodically check for the div but I don't really like the overhead that this would impose. Source: Tips4all

Showing a demo of my CSS on any website

I have developed a small component which can be put in to any website. Now, I want to develop a code that could demonstrate how would my component look like on any website. So, the person would come to my page and put in his URL and then my code should embed my custom JS/CSS in to the downloaded HTML and display it. Something like this . Here, like the feedback tab, I want to show my component any where on that page. Source: Tips4all

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()

jquery newsletter submit - loading message

i have a newsletter form i use on my site using ajax with jquery. i want to show to a user a wait message. what is the best option? heres what i have so far: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#submit').click(function(e) { $.ajax({ type: "POST", url: '/save.php', data: $('#form').serialize(), cache: false, success: function(result) { // my code when success } }); }); }); </script> <div id="newsletter"> <form id="form"> <label for="email">Your Email*:</label> <input name="email" value="" type="text" id="email" size="30" maxlength="255" /> <span id="submit">Sub

I want to show list items as 2 or more columns (dynamic alignment)

I am able to do the list using float:left; like this But I would like to show it like this (as 2 or more columns) How can I do that? @sandeep gave good solution. Unfortunately does not work in IE(need ie7 and above). any help? Source: Tips4all

jQuery Validation custom validation adding no space validation

I have a form where the user can update his name and last name. I use jQuery validation to validate the form. How can I validate if the user put spaces? here's what i have: <script> $(document).ready(function(){ $('#submit').click(function() { var valid = $("#myform").valid(); if(!valid) { return false; } $.ajax({ type: "POST", url: 'save', data: $('#myform').serialize(), dataType: 'json', cache: false, success: function(result) { // redirect to another page } }); }); }); </script> </head> <body> <form id="myform" method="post" action=""> <fieldset> <legend>update name</legend> <p> <label for="fname">Name</label> <em>*</em><input id="fname" name="fname" size="25" class="required" minlength="2" /> &

jQuery ajax this.id undefined

I have a list of items I delete using AJAX. This list is a simple list with divs and each div as an id so when the item is removed from the database I return true and then it removes the line. Here my code: HTML <div id="row1"> <div>item1</div> <div><a href="...">view</a></div> <div><a id="1">delete</a></div> </div> JS $('.delete').click(function () { if (!confirm('Are you sure you want to delete?')) { return false; } $.ajax({ type: "POST", url: '/delete_record', data: 'id=' + this.id, cache: false, success: function (result) { if (result == 'good') { $('#row' + this.id).remove(); } } }); }); For some reason the this.id does not work because this.id is undefined ... why? I have id="1" on my a h

Best way to play sound with HTML5 and Javascript

I'm trying to play a sound and i have found two ways that works for me. Which is the better way and why? is a good idea add a "load" event listener? First way: $(document).ready(function() { var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'sound.ogg'); audioElement.addEventListener("load", function(){ audioElement.play(); }, true); audioElement.play(); }); Second way: $(document).ready(function() { audioElement = new Audio('sound.ogg'); audioElement.play(); }); Source: Tips4all

zoom on webpage

i would like to create a zoom effect for my site for visually impaired people. i currently have the font that adjust based on a user preferences: i use this script: http://dev-tips.com/demo/jquery_font_size_change.html that works great, but the images remains the same size and if the text is too big it mess up the visual aspect of my site. ideally, a loop will pop and then the user can move over the site and see a zoomed version of it. is it possible to create a zoom effect using jquery? Source: Tips4all

require()"ing a CoffeeScript file from a JavaScript file or REPL

I'm using Node.js and wanting to incorporate CoffeeScript into my workflow. I have two use-cases: I want to be able to write JavaScript files which require() CoffeeScript modules I want to be able to load CoffeeScript modules from within the node REPL For case #1 I can just compile from .coffee to .js and require() the .js module, as a workaround. For case #2 right now I'm eval()'ing the output of coffee-script.compile(). Is there a better, more unified way to do this? Source: Tips4all

Jquery - Check: If scrollbar visible (div with overflow:auto)

is it possible to check the overflow:auto from a div? for example HTML <div id="my_div" style="width: 100px; height:100px; overflow:auto;" class="my_class"> * content </div> JQUERY $('.my_class').live('hover', function (event) { if (event.type == 'mouseenter') { if( ... if scrollbar visible ? ... ) { alert('true'): } else { alert('false'): } } }); Sometimes is the content short (no scrollbar) and sometimes long (scrollbar visible). Thanks in advance! Peter Source: Tips4all

Backbone.js: `extend` undefined?

Just getting started with Backbone.js. Simply including Backbone (either dev/production versions) causes the error: Uncaught TypeError: Cannot call method 'extend' of undefined on Line 128: // Attach all inheritable methods to the Model prototype. _.extend(Backbone.Model.prototype, Backbone.Events, { Source: Tips4all

How can I tell if a particular CSS property is inherited with jQuery?

This is a very simple question, so I'll keep it really brief: How can I tell if a particular DOM element's CSS property is inherited? Reason why I'm asking is because with jQuery 's css method it will return the computed style, which inherits the parent object's CSS properties. Is there a way to retrieve the properties set on the object itself? An example might explain what I'm getting at a bit better: CSS: div#container { color:#fff; } HTML: <div id="container"> Something that should be interesting <div class="black"> Some other thing that should be interesting </div> </div> So, in the instance of div.black , which inherits color , how can I tell if it is inherited? $('div.black:eq(0)').css('color') will obviously give me #fff , but I want to retrieve the style of the element itself , not its parents. EDIT : To clarify, my question is how can I detect if a given CS

Differences between node.js and Tornado

Besides the fact that node.js is written in JS and Tornado in Python, what are some of the differences between the two? They're both non-blocking asynchronous web servers, right? Why choose one over the other besides the language? Source: Tips4all

When Profiling Javascript in Chrome how do I know I"ve handled Memory Leaks?

I've been working on a game in for HTML 5 using the canvas tag, and I've build up quite a code base to cover my requirements. I also want to make sure I'm covering up all my memory leaks. I have doubts I'm doing it correctly because the feedback I'm getting from Chrome's task manager and profiling tools seem to suggest my cleanup is having no effect in the end. Here's an image so you can see what I mean: So as you can see, once I do my cleanup memory usage just freezes and doesn't drop. Is this a memory leak? When I ran my webpage in the Profiler and checked the heap before and after cleanup it does appear to remove all the references to my objects (and they disappear) but my usage only drops by only a few kilobytes leaving about 1.3mb of arrays, strings, and other objects behind. Is it impossible to catch all this or is there something majorly wrong? Thanks. Source: Tips4all

Why is using onClick() in HTML a bad practice?

I have heard many times that using JavaScript events, such as onClick() , in HTML is a bad practice, because it's not good for semantics. I would like to know what the downsides are and how to fix the following code? <a href="#" onclick="popup('/map/', 300, 300, 'map'); return false;">link</a> Source: Tips4all

Html5 Canvas vs SVG vs div

What is the best way for element creation on the fly and being able to move it around? Let's say I want to create rectangle, circle and polygon then I want to select the objects and move it around And how is the performance of those three while in use for showing a web page? Let's say I want to create three visually identical web page and have header, footer, widget and text content in them. The first one is created using full canvas, the second is created using svg, and the third is created using plain div html and css. Thanks in advance Source: Tips4all

javascript data structures library

I'd like to ask for recommendation of JavaScript library/libraries that supply an implementation of some basic data structures such as a priority queue, map with arbitrary keys, tries, graphs, etc. along with some algorithms that operate on them. I'm mostly interested in: The set of features covered, Flexibility of the solution - this mostly applies to graphs. For example do I have to use a supplied graph implementation, Use of functional features of the language - again it sometimes gives greater flexibility, Performance of the implementation EDIT Ok, I'd like to point out that I'm aware that it's possible to implement using js the following data structures: A map, if key values are either strings or numbers, A set, (using a map implementation), A queue, although as was pointed out below, it's inefficient on some browsers, At the moment I'm mostly interested in priority queues (not to confuse with regular queues), graph

Adding favicon to javascript Bookmarklet (uses window.open)

I have a bookmarklet that launches a window.open javascript function to open a small window with my bookmarklet -- an external feature used to communicate between any visted site and my server. I'd like for a favicon to show up when the bookmarklet is added to the bookmark toolbar. I realize that the bookmarklet is javascript, there is no domain tied to it so it's going to be either difficult or impossible to achieve this goal. My understanding of the problem: Favicons are easy to understand, a link within the head of an HTML doc. The browser can pull this when bookmarking an actual site by reference. However, as you see my bookmarklet is ran off a javascript launch code where there exists no HTML, therefor no link to a favicon . I'm not ready to give up yet though, I feel that there's some injection that can be made... As of now, the bookmarklet launch code looks like this: Current Script -- bookmarklet, no favicon (note all code is formated with line break

What"s the point of the Boolean Object?

I am reading through the Mozilla Manual on JavaScript and I come to this point in my reading, Boolean Object and I can't see a single use for them. What's their point? Why would'nt you use just true and false ? By the way, I don't know Java at all and I'm not afraid of learning new things that consequently why I'm trying to learn JavaScript. I'm a PHP programmer, a back end guy, and I'd like to learn how to do some front end work, so I'm reading the Mozilla JavaScript Guide . Source: Tips4all

Javascript: How to make sense of all the frameworks and design philosophies?

I have been a user of jQuery (and some of its minor plugins) for a while. The Javascript code I've developed over the years could be described best as... messy. It used a ton of global variables and functions here and there, didn't use standard ways of organizing the code, nor any design patterns whatsoever. I am currently building the new version of a website, and I have completed doing the backend with PEAR::MDB2 and Smarty templates. The rest is just homebrew PHP with some classes. Now I am at the point where I'll add the Javascript layer on top of the website to improve the user-friendliness of some features. (while making sure everything degrades gracefully) I want to write better, cleaner, more organized Javascript than I used to, so I did a little research. I read Stefanov's Object-Oriented Javascript to have a better grasp on some concepts I knew only loosely about (prototypes, constructors, etc.) as well. Now I'm stuck at a point where I wonder wh

Should I use window.variable or var?

We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files. Typically, we do something like: grid.js var myGrid = ..... combos.js var myCombo = ..... Then, in our application code, we: application.js function blah() { myGrid.someMethod() } someother.js function foo() { myCombo.someMethod(); myGrid.someMethod(); } So, should we be using the var myGrid or is better to use window.myGrid What's the difference? Source: Tips4all

Why do browsers allow onmousedown JS to change href?

I've noticed for a very long time that when you try to copy a link location or open a link on Facebook, it modifies the link and passes it through l.php . For example, I can be sent to http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.google.com%2F&h=DKVUritNDJDJLDLVbldoDLFKBLOD5dlfDJY_-d3fgDUaA9b even though my browser render the link preview as http://www.google.com/ . Today, I took a closer look using Firebug and found that Facebook puts onmousedown="UntrustedLink.bootstrap($(this)[...] in the <a> tag. The second I right clicked the link, I saw the href attribute change in Firebug. This worries me. The advice many of us have given to less tech-savvy people (check where the link is taking you before you click so that you don't become a victim of phishing) now seems to have become useless. Isn't this a security risk? Can't phishing websites misuse this? Why don't browsers prevent this behavior either by disallowing onmousedown to c

What does | in this code mean?

function foo() {} var bar = foo <| function() {}; This is the first time I've seen something like this. What does <| mean? Source: https://github.com/allenwb/ESnext-experiments/blob/master/ST80collections-exp1.js Source: Tips4all

How are JavaScript host objects implemented?

I was thinking about this today and I realized I don't have a clear picture here. Here are some statements I think to be true (please correct me if I'm wrong): the DOM is a collection of interfaces specified by W3C. when parsing HTML source code, the browser creates a DOM tree which has nodes that implement DOM interfaces. the ECMAScript spec has no reference of browser host objects (DOM, BOM, HTML5 APIs etc.). how the DOM is actually implemented depends on browser internals and is probably different among most of them. modern JS interpreters use JIT to improve the code performance and translate it to bytecode I am curious about what happens behind the scenes when I call document.getElementById('foo') . Does the call get delegated to browser native code by the interpreter or does the browser have JS implementations of all host objects? Do you know about any optimizations they do in regard to this? I read this overview of browser internals b

Javascript Funky array mishap

function a() { var b = ["b"]; console.log(b); //console.log(b.slice()); b = b.push("bb"); } a(); In a "perfect" world you would think that the console.log would show ["b"] , but wildly enough it shows ["b", "bb"] even though "bb" isn't pushed on until afterword . *wtf* If you do console.log(b.slice()); Then you will get the desired result of ["b"] . What gives? What's the reason behind this complication? I just want to understand this better so I can better avoid it from happening. *note I hit on this same point in a recent question of mine, but this is a much more concise example. @RightSaidFred has led me to this point and has been a HUGE help so far (big thanks). ** EDIT ** Runnable example on JSFiddle ** POST-ANSWER ** This is all due to a problem where console.log messes up sometimes. Thanks to everyone for all the help in figuring this out. Source: Tips4all

JavaScript: Is a member defined?

It seems to me that there are four different ways I can determine whether a given object (e.g. foo ) has a given property (e.g. bar ) defined: if (foo.hasOwnProperty(bar)) { if ('bar' in foo) { if (typeof foo.bar !== 'undefined') { if (foo.bar === undefined) { To determine if there is a property named " bar " in the object foo , are all three of those statements equivalent? Are there any sublte semantics I don't know that makes any of these three statements different? Source: Tips4all

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex