Skip to main content

Posts

Showing posts from April 5, 2012

How to create PDFs in Android SDK?

is there any way to create create PDF Files from an android application? So far I've found nothing short of writing all the code from scratch. Is there any API I can use, that works on android? Thanks in advance. Source: Tips4all

How to register some URL namespace (myapp://app.start/) for accessing your program by calling a URL in browser in Android OS?

So I want to create an Android app so it would be registered somewhere in android OS (or just would start on system start) and when phone user clicks on special button on a web page inside a web browser a la: <a href="myapp://mysettings">Foo</a> my app would pop up and run using the params sent in that URL. So how do I do such thing? I need a tutorial with code! Source: Tips4all

ASP.NET MVC and AJAX

I have a view which is composed of top, left and bottom headers and a main contents pane. Suppose that during an AJAX request I need to update the HTML of the top, bottom and main panels (the left header should stay the same). I was wondering what would be the best way to accomplish this. The first thought was to put the main contents panel into a partial and have a controller action that would return PartialView. This wouldn't work because as the action returns only the HTML of the main pane I cannot update the top and bottom headers. So if I put the top and bottom headers into their own respective partial views I would need my controller action to return multiple partial views. Is this possible at all or I am doing something completely off the track? I saw that it is possible to render a partial view to a string so I thought that I could use this technique in the action to return a JSON object with 3 properties representing the HTML of the 3 partials that I need to updat

jQuery - filter element based on .data() key/value

Say I have 4 div elements with class .navlink , which, when clicked, use .data() to set a key called 'selected' , to a value of true : $('.navlink')click(function() { $(this).data('selected', true); }) Every time a new navlink is clicked, I would like to store the previously selected navlink for later manipulation. Is there a quick and easy way to select an element based on what was stored using .data() ? There don't seem to be any jQuery :filters that fit the bill, and I tried the following (within the same click event), but for some reason it doesn't work: var $previous = $('.navlink').filter( function() { $(this).data("selected") == true } ); I know that there are other ways to accomplish this, but right now I'm mostly just curious if it can be done via .data() . Thanks. Source: Tips4all

Detect application heap size in Android

How do you programmatically detect the application heap size available to an Android app? I heard there's a function that does this in later versions of the SDK. In any case, I'm looking for solution that works for 1.5 and upwards. Source: Tips4all

Android JSON HttpClient to send data to PHP server with HttpResponse

I am currently trying to send some data from and Android application to a php server (both are controlled by me). There is alot of data collected on a form in the app, this is written to the database. This all works. In my main code, firstly I create a JSONObject (I have cut it down here for this example): JSONObject j = new JSONObject(); j.put("engineer", "me"); j.put("date", "today"); j.put("fuel", "full"); j.put("car", "mine"); j.put("distance", "miles"); Next I pass the object over for sending, and receive the response: String url = "http://www.server.com/thisfile.php"; HttpResponse re = HTTPPoster.doPost(url, j); String temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS")==0) { Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show(); } The HTTPPoster class: public static HttpResponse doPost(String url, JSO

Convert String to XML Document in JavaScript

Saw this example on the jQuery examples page for Ajax: var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: someFunction }); How do I take a string like: var t = '<foo><bar>something</bar></foo>'; And convert that to a XML DOM object? cross-browser? UPDATE : Please see comments to karim79's answer. Source: Tips4all

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

If I have the following in my html: <div style="height:300px; width:300px; background-color:#ffffff;"></div> And this in my css style sheet: div { width:100px; height:100px; background-color:#000000; } Is there any way, with javascript/jquery, to remove all of the inline styles and leave only the styles specified by the css style sheet? Source: Tips4all

jQuery / Ajax - $.ajax() Passing Parameters to Callback - Good Pattern to Use?

JavaScript code I'm starting with: function doSomething(url) { $.ajax({ type: "GET", url: url, dataType: "xml", success: rssToTarget }); } Pattern I would like to use: //where elem is the target that should receive new items via DOM (appendChild) function doSomething(url, elem) { $.ajax({ type: "GET", url: url, dataType: "xml", success: rssToTarget(elem) }); } I don't think I can get the callback to work this way, right? What is the proper pattern? I don't want to use global variables necessarily to temporarily hold the elem or elem name. Source: Tips4all

Cannot properly set the Accept HTTP header with jQuery

I'm trying to set the Accept HTTP header to "text/xml" with this jquery code: $.ajax({ beforeSend: function(req) { req.setRequestHeader("Accept", "text/xml"); }, type: "GET", url: "[proper url]", contentType: "text/plain; charset=utf-8", dataType: ($.browser.msie) ? "text" : "xml", username: '---', password: '-------', success: function(data) { var xml; if (typeof data == "string") { alert("Data is string:" + data); xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = false; xml.loadXML(data); } else { xml = data; alert("Data is not string:" + $(xml).text()); } // Returned data available in object "xml" //alert("Status is: " + xml.

get root URL in javascript

is there a really easy way to turn document.location.href=="http://aaa.bbb.ccc.ddd.com/asdf/sadf/asdf/asdf/asdf/sadf.aspx?blah" into 'aaa.bbb.ccc.ddd.com'? There's gotta be a JS function that does this reliably, but I can't find it. Source: Tips4all

Is $(document).ready() also CSS ready?

I've got a script executing on $(document).ready() that's supposed to vertically align block element in my layout. 90% of the time, it works without issue. However, for that extra 10% one of two things happens: There's an obvious lag in the time it takes to do the centering, and the block elements jump into position. This could simply be performance related - as the page size is often large and there is a fair amount of javascript that is executing at once. The centering will completely mess up, and the block element will either pushed down too far or not far enough. It appears as if it tried to calculate the height, but was getting improper measurements. Is there any reason why executing a script on DOM-ready would not have all the correct CSS values injected into the DOM yet? (all CSS is in the <head> via a <link> ). Also, here's the script that's causing the issue (yes, it's been taken straight from here

Download File Using jQuery

How can I prompt a download for a user when they click a link. For example, instead of: <a href="uploads/file.doc">Download Here</a> I could use: <a href="#">Download Here</a> $('a').click... //Some jquery to download the file This way, Google does not index my HREF's and private files. Can this be done with jQuery, if so, how? Or should this be done with PHP or something instead? Thanks! Source: Tips4all

jQuery - Get Width of Element when Not Visible (Display: None)

It seems like in jQuery when an element is not visible width() returns 0. Makes sense, but I need to get the width of a table in order to set the width of the parent before I show the parent. As noted below, there is text in the parent, that makes the parent skew and look nasty. I want the parent to be only as wide as the table and have the text wrap. <div id="parent"> Text here ... Can get very long and skew the parent <table> ... </table> Text here too ... which is why I want to shrink the parent based on the table </div> CSS: #parent { display: none; } Javascript: var tableWidth = $('#parent').children('table').outerWidth(); if (tableWidth > $('#parent').width()) { $('#parent').width() = tableWidth; } tableWidth always returns 0 since it is not visible (is my guess since it gives me a number when visible). Is there a way to get the width of the table without making the parent visible?

Attaching an event to multiple elements at one go

Say I have the following : var a = $("#a"); var b = $("#b"); //I want to do something as such as the following : $(a,b).click(function () {/* */}); // <= does not work //instead of attaching the handler to each one separately Obviously the above does not work because in the $ function, the second argument is the context , not another element. So how can I attach the event to both the elements at one go ? [Update] peirix posted an interesting snippet in which he combines elements with the & sign; But something I noticed this : $(a & b).click(function () { /* */ }); // <= works (event is attached to both) $(a & b).attr("disabled", true); // <= doesn't work (nothing happens) From what you can see above, apparently, the combination with the & sign works only when attaching events...? Source: Tips4all

Disable grey border on anchor (<a>) elements on focus

I am trying to make the ugly grey border that appears around anchor tags go away. The CSS property " outline:none; " works for Firefox, but how can I do it in IE. Preferably using CSS expressions or jquery. I'm not worried about accessibility BTW. Based on your suggestions I found these to be the best solutions... The jquery(for IE browsers): $('a').focus(function(){ $(this).blur(); }); Another jquery option(for IE browsers only): $('a').focus(function(){ $(this).attr("hideFocus", "hidefocus"); }); The CSS(For all other browsers that force an outline): a{ outline: none; } Note: Some browsers such as Google Chrome don't force an outline on focus. Source: Tips4all

jQuery using append with effects

How can I use .append() with effects like show('slow') Having effects on append doesn't seem to work at all, and it give the same result as normal show() . No transitions, no animations. How can I append one div to another, and have a slideDown or show('slow') effect on it? Source: Tips4all

Flash on top of jQuery dialog

I know many have asked this question, but I think my situation is a little bit different. I have a site where I have some ads which is Flash hidden in a because of xhtml/html compatibility issues. But the flash elements is on top of my jQuery dialogs which is not ideal. Some solutions have suggested setting wmode to opaque but I can't because my ads are scripts which outputs flash elements. Another solution suggested hiding ads when a dialog is shown. So my question is: Is there a way to put flash content behind my jQuery dialogs while they are visible and without altering the flash code? Best regards, Lasse Espeholt Update: I have now reopned the question with a bounty. As for now, I hide every Flash ad on "show dialog". But this is still not an optimal solution. So, I'm looking for a script which can make every Flash animation to opaque (a jQuery solution would be nicest, but a plain JavaScript solution will do). Or if there should be another solution n

how to set a value for a span using JQuery

How to set a value for a span using JQuery.. For example… Below is my span <span id="submittername"></span> in my JQuery code… <script type="text/javascript"> jQuery.noConflict(); jQuery(document).ready(function($){ var invitee = $.ajax({ type: "GET", url: "http://localhost/FormBuilder/index.php/reports/getInvitee/<?=$submitterid;?>", async: false }).responseText; var invitee_email=eval('(' + invitee + ')'); var submitter_name=$.map(invitee_email.invites, function(j){ return j.submitter; }); alert(submitter_name); // alerts correctly $("#submittername").text(submitter_name); //but here it is not working WHy so?????? }); Source: Tips4all

jQuery: Move Table Row?

Say I had to links with up/down arrows for moving a table row up or down in order. What would be the most straightforward way to move that row up or down one position (using jQuery)? There doesn't seem to be any direct way to do this using jQuery's built in methods, and after selecting the row with jQuery, I haven't found a way to then move it. Also, in my case, making the rows draggable (which I have done with a plugin previously) isn't an option. Source: Tips4all

jQuery how to bind onclick event to dynamically added HTML element

I want to bind an onclick event to an element I insert dynamically with jQuery But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da"> <head> <title>test of click binding</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> jQuery(function(){ close_link = $('<a class="" href="#">Click here to see an alert</a>'); close_link.bind("click", function(){ alert('hello from binde

jquery-min version?

i noticed that there is always a min version (stands for mini?) to most of the js libraries eg jquery. what is the difference? less functions but smaller size? is this someone should consider to use? (there are a lot of min versions out there) Source: Tips4all

Hide select option in IE using jQuery

Currently I am using jQuery to hide/show select options using following code. $("#custcol7 option[value=" + sizeValue + "]").hide(); This works fine in Firefox, but doesnt do any good in other browsers. How to I hide options from select in Chrome, Opera and IE? Source: Tips4all

jQuery Plugins vs UI vs some alternative

I've been building a web app using jQuery as much as possible. Every time I need to add some new feature, I usually search for a jQuery plugin that does what I need, then I integrated it into my web app. Of course after a while this application becomes very cluttered with all these "random" plugins from different authors, each one having different coding style, naming convention, etc. I would really prefer to use one uniform UI library or framework. I am looking at jQuery UI, but frankly I am not impressed. Although jQuery Tools ( http://flowplayer.org/tools/download.html ) looks kind of nice. Does anyone have any experience with any of these? Do you have any other suggestions? Not just regarding what UI frameworks to use, but your thoughts regarding dealing with cluttering web applications with different UI plugins in general. Thanks Source: Tips4all

How to wait 5 seconds with jQuery?

I'm trying to create an effect where the page loads, and after 5 seconds, the success message on the screen fades out, or slides up. How can I achieve this? Solution: There are a few different ways to achieve this: Javascript's built-in setTimeout method jQuery's delay method (available in jQuery 1.4+) Example: $(document).ready(function(){ setTimeout(function(){ $('.my-element').fadeIn(); }, 5000); // or... $('.my-element').delay(5000).fadeIn(); }); Source: Tips4all

How to clear Jquery validation error messages?

I am using jquery validation plugin for client side validation. but i want to clear error mesages on my form clear button editUser() is called on click of Edit User button. clear button having separated function clearUser(){ // Need to clear previous errors here } function editUser(){ var validator = $("#editUserForm").validate({ rules: { userName: "required" }, errorElement: "span" , messages: { userName: errorMessages.E2 } }); if(validator.form()){ // form submition code } } Thanks Source: Tips4all

What are good PHP and MySQL type Blogs to read?

I searched and found many topics similar to this on Stackoverflow, but they were all for languages that I do not use. I am interested in reading good blogs with an RSS feed in topics related to PHP , MySQL , Javascript , jQuery . I have a few listed below so far, please share with me any blogs worth reading and subscribing to with any of these web related topics. Here are some I enjoy now... http://buildinternet.com http://davidwalsh.name http://www.9lessons.info http://blog.perplexedlabs.com http://blog.agilephp.com http://www.barattalo.it http://papermashup.com Source: Tips4all

Why am I finding Javascript/jQuery so difficult to get right?

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue. But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why? It seems to violate a number of traditional programming principles (e.g. variable scope) Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs): $("a").click(function(event) { event.preventDefault(); $('<div/>') .append('default ' + event.type + ' prevented') .appendTo('#log'); }); What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API ? There seems to be bunch of random rules (e.g. return false to stop a default action, but s

Why is JavaScript prototyping?

That may strike you as a grammatically incorrect and possibly insane question, but here's what I mean: When trying to understand the concept of prototype in JavaScript, I came upon examples that were slightly more or less complicated versions of the following: //Guitar function constructor function Guitar(color, strings) { this.color = color; this.strings = strings; } //Create a new instance of a Guitar var myGuitar = new Guitar('Black', ['D', 'A', 'D', 'F', 'A', 'E']); //Adding a new method to Guitar via prototype Guitar.prototype.play = function (chord) { alert('Playing chord: ' + chord); }; //Now make use of this new method in a pre-declared instance myGuitar.play('D5'); So, on to my problem: Why the hell would you want to do this? Why would you not just put the play function in Guitar to begin with? Why declare an instance and then start adding methods later? The only reason I can see is

How can I make the Facebook Like button"s width automatically resize?

I'm implementing the Facebook Like Button , but I'm running into some trouble with the width. I'm using the JavaScript SDK implementation, not the direct iframe. According to the documentation, the default width is 450 . That's fine, and I understand that the width can be changed by way of the width attribute on the <fb:like> tag. However, my problem is that I really cannot specify a fixed width. Due to the nature of the button, the width is not constant in all states. For example, if no one has liked the page yet it displays "Be the first of your friends to like this"; if someone has, it displays "XXX people like this. Be the first of your friends"; and still if you have liked it, it displays "You like this" or "You and XXX people like this." In other words, there are many states of the button, none of which share a constant width. This wouldn't be much of a problem if it weren't for the fact that I want

How can I combine objects in the Raphael javascript library?

Sorry for a long question but here goes. I am trying to modify the drag shapes around demo here: http://raphaeljs.com/graffle.html The demo works fine. What I want to do is put words inside the shapes and move the shape and text around as a composite single object. Here is the code for creating the objects: window.onload = function () { var dragger = function () { this.ox = this.type == "rect" ? this.attr("x") : this.attr("cx"); this.oy = this.type == "rect" ? this.attr("y") : this.attr("cy"); this.animate({"fill-opacity": .2}, 500); }, move = function (dx, dy) { var att = this.type == "rect" ? {x: this.ox + dx, y: this.oy + dy} : {cx: this.ox + dx, cy: this.oy + dy}; this.attr(att); for (var i = connections.length; i--;) { r.connection(connections[i]); } r.safari(); },

Design Patterns used in the jQuery library

jQuery is highly focused on the DOM and provides a nice abstraction around it. In doing so, it makes use of various well known design patterns which just hit me yesterday. One obvious example would be the Decorator pattern. The jQuery object provides new and additional functionality around a regular DOM object. For example, the DOM has a native insertBefore method but there is no corresponding insertAfter method. There are various implementations available to fill this gap, and jQuery is one such library that provides this functionality: $(selector).after(..) $(selector).insertAfter(..) There are many other examples of the Decorator pattern being heavily used in jQuery. What other examples, big or small, of design patterns have you noticed that are part of the library itself? Also, please provide an example of the usage of the pattern. Making this a community wiki as I believe that various things people love about jQuery can be traced back to well known design patterns, j

How to detect when facebook"s FB.init is complete

The old JS SDK had a function called FB.ensureInit. The new SDK does not seem to have such function... how can I ensure that I do not make api calls until it is fully initiated? I include this in the top of every page: <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $conf['fb']['appid']; ?>', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); FB.Canvas.setAutoResize(); }; (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }()); </script> Source: Tips4all

Why am I finding Javascript/jQuery so difficult to get right?

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue. But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why? It seems to violate a number of traditional programming principles (e.g. variable scope) Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs): $("a").click(function(event) { event.preventDefault(); $('<div/>') .append('default ' + event.type + ' prevented') .appendTo('#log'); }); What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API ? There seems to be bunch of random rules (e.g. return false to stop a default action, but s

What does ~~ do in Javascript?

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would give back the same value, wouldn't it? Thanks, Shane Source: Tips4all

what is a lambda language?

I was reading "javascript good parts" author mentions that javascript is first of the lambda languages to be launched. JavaScript's functions are first class objects with (mostly) lexical scoping. JavaScript is the first lambda language to go mainstream. Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C's clothing. This makes JavaScript is remarkably powerful language. I didn't get what is a lambda language. What are the properties of such a language and how is it different from languages like java c c++ php? Source: Tips4all

How can I combine objects in the Raphael javascript library?

Sorry for a long question but here goes. I am trying to modify the drag shapes around demo here: http://raphaeljs.com/graffle.html The demo works fine. What I want to do is put words inside the shapes and move the shape and text around as a composite single object. Here is the code for creating the objects: window.onload = function () { var dragger = function () { this.ox = this.type == "rect" ? this.attr("x") : this.attr("cx"); this.oy = this.type == "rect" ? this.attr("y") : this.attr("cy"); this.animate({"fill-opacity": .2}, 500); }, move = function (dx, dy) { var att = this.type == "rect" ? {x: this.ox + dx, y: this.oy + dy} : {cx: this.ox + dx, cy: this.oy + dy}; this.attr(att); for (var i = connections.length; i--;) { r.connection(connections[i]); } r.safari(); },

Why do people use jQuery for basic operations?

I am a JS programmer and I have been experimenting with jQuery a lot but have run into a couple puzzling aspects. I feel like people use jQuery for much more than necessary. I really just want to know why picking jQuery may be better than using just pure JS. I know it makes sense for webfx like the animate and fades but for things like adding event listeners it seems just as easy to use obj = document.getElementByID(_ID_); obj.addEventListener("mousedown"...); An example of this is the answer I found on StackOverflow earlier today about performing an action for highlighted text. jQuery: get the highlighted text In the example linked in the answer at http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html The guy uses the bind function to the document. Why use bind rather than addEventListener. Also with jQuery everything needs to be included in the .ready() method how is this better than (or why choose it over) document.addEventListene

How to detect when facebook"s FB.init is complete

The old JS SDK had a function called FB.ensureInit. The new SDK does not seem to have such function... how can I ensure that I do not make api calls until it is fully initiated? I include this in the top of every page: <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $conf['fb']['appid']; ?>', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); FB.Canvas.setAutoResize(); }; (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }()); </script> Source: Tips4all