Search Results

Search found 23708 results on 949 pages for 'javascript'.

Page 15/949 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Choosing a JavaScript Asynch-Loader

    - by Prisoner ZERO
    I’ve been looking at various asynchronous resource-loaders and I’m not sure which one to use yet. Where I work we have disparate group-efforts whose class-modules may use different versions of jQuery (etc). As such, nested dependencies may differ, as well. I have no control over this, so this means I need to dynamically load resources which may use alternate versions of the same library. As such, here are my requirements: Load JavaScript and CSS resource files asynchronously. Manage dependency-order and nested-dependencies across versions. Detect if a resource is already loaded. Must allow for cross-domain loading (CDN's) (optional) Allow us to unload a resource. I’ve been looking at: Curl RequireJS JavaScriptMVC LABjs I might be able to fake these requirements myself by loading versions into properly-namespaced variables & using an array to track what is already loaded...but (hopefully) someone has already invented this. So my questions are: Which ones do you use? And why? Are there others that my satisfy my requirements fully? Which do you find most eloquent and easiest to work with? And why?

    Read the article

  • Unable to debug javascript?

    - by linkme69
    I’m having some problems debugging an encoded javacscript. This script I’m referring to given in this link over here. The encoding here is simple and it works by shifting the unicodes values to whatever Codekey was use during encoding. The code that does the decoding is given here in plain English below:- <script language="javascript"> function dF(s){ var s1=unescape(s.substr(0,s.length-1)); var t=''; for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1)); document.write(unescape(t)); } I’m interested in knowing or understanding the values (e.g s1,t). Like for example when the value of i=0 what values would the following attributes / method would hold s1.charCodeAt(i) and s.substr(s.length-1,1) The reason I’m doing this is to understand as to how a CodeKey function really works. I don’t see anything in the code above which tells it to decode on the basis of codekey value. The only thing I can point in the encoding text is the last character which is set to 1 , 2 ,3 or 4 depending upon the codekey selected during encoding process. One can verify using the link I have given above. However, to debug, I’m using firebug addon with the script running as localhost on my wamp server. I’m able to put a breakpoint on the js using firebug but I’m unable to retrieve any of the user defined parameters or functions I mentioned above. I want to know under this context what would be best way to debug this encoded js.

    Read the article

  • Slow Firefox Javascript Canvas Performance?

    - by jujumbura
    As a followup from a previous post, I have been trying to track down some slowdown I am having when drawing a scene using Javascript and the canvas element. I decided to narrow down my focus to a REALLY barebones animation that only clears the canvas and draws a single image, once per-frame. This of course runs silky smooth in Chrome, but it still stutters in Firefox. I added a simple FPS calculator, and indeed it appears that my page is typically getting an FPS in the 50's when running Firefox. This doesn't seem right to me, I must be doing something wrong here. Can anybody see anything I might be doing that is causing this drop in FPS? <!DOCTYPE HTML> <html> <head> </head> <body bgcolor=silver> <canvas id="myCanvas" width="600" height="400"></canvas> <img id="myHexagon" src="Images/Hexagon.png" style="display: none;"> <script> window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); var animX = 0; var frameCounter = 0; var fps = 0; var time = new Date(); function animate() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); animX += 1; if (animX == canvas.width) { animX = 0; } var image = document.getElementById("myHexagon"); context.drawImage(image, animX, 128); context.lineWidth=1; context.fillStyle="#000000"; context.lineStyle="#ffffff"; context.font="18px sans-serif"; context.fillText("fps: " + fps, 20, 20); ++frameCounter; var currentTime = new Date(); var elapsedTimeMS = currentTime - time; if (elapsedTimeMS >= 1000) { fps = frameCounter; frameCounter = 0; time = currentTime; } // request new frame requestAnimFrame(function() { animate(); }); } window.onload = function() { animate(); }; </script> </body> </html>

    Read the article

  • Extending Currying: Partial Functions in Javascript

    - by kerry
    Last week I posted about function currying in javascript.  This week I am taking it a step further by adding the ability to call partial functions. Suppose we have a graphing application that will pull data via Ajax and perform some calculation to update a graph.  Using a method with the signature ‘updateGraph(id,value)’. To do this, we have do something like this: 1: for(var i=0;i<objects.length;i++) { 2: Ajax.request('/some/data',{id:objects[i].id},function(json) { 3: updateGraph(json.id, json.value); 4: } 5: } This works fine.  But, using this method we need to return the id in the json response from the server.  This works fine, but is not that elegant and increase network traffic. Using partial function currying we can bind the id parameter and add the second parameter later (when returning from the asynchronous call).  To do this, we will need the updated curry method.  I have added support for sending additional parameters at runtime for curried methods. 1: Function.prototype.curry = function(scope) { 2: scope = scope || window 3: var args = []; 4: for (var i=1, len = arguments.length; i < len; ++i) { 5: args.push(arguments[i]); 6: } 7: var m = this; 8: return function() { 9: for (var i=0, len = arguments.length; i < len; ++i) { 10: args.push(arguments[i]); 11: } 12: return m.apply(scope, args); 13: }; 14: } To partially curry this method we will call the curry method with the id parameter, then the request will callback on it with just the value.  Any additional parameters are appended to the method call. 1: for(var i=0;i<objects.length;i++) { 2: var id=objects[i].id; 3: Ajax.request('/some/data',{id: id}, updateGraph.curry(id)); 4: } As you can see, partial currying gives is a very useful tool and this simple method should be a part of every developer’s toolbox.

    Read the article

  • How to Enable JavaScript file API in IE8 [closed]

    - by saeed
    i have developed a web application in asp.net , there is a page in this project which user should choose a file in picture format (jpeg,jpg,bmp,...) and i want to preview image in the page but i don't want to post file to server i want to handle it in client i have done it with java scripts functions via file API but it only works in IE9 but most of costumers use IE8 the reason is that IE8 doesn't support file API is there any way to make IE8 upgrade or some patches in code behind i mean that check if the browser is IE and not support file API call a function which upgrades IE8 to IE9 automatically. i don't want to ask user to do it in message i want to do it programmatic !! even if it is possible install a special patch that is required for file API because customers thought it is a bug in my application and their computer knowledge is low what am i supposed to do with this? i also use Async File Upload Ajax Control But it post the file to server any way with ajax solution and http handler but java scripts do it all in client browser!!! following script checks the browser supports API or not <script> if (window.File && window.FileReader && window.FileList && window.Blob) document.write("<b>File API supported.</b>"); else document.write('<i>File API not supported by this browser.</i>'); </script> following scripts do the read and Load Image function readfile(e1) { var filename = e1.target.files[0]; var fr = new FileReader(); fr.onload = readerHandler; fr.readAsText(filename); } HTML code: <input type="file" id="getimage"> <fieldset><legend>Your image here</legend> <div id="imgstore"></div> </fieldset> JavaScript code: <script> function imageHandler(e2) { var store = document.getElementById('imgstore'); store.innerHTML='<img src="' + e2.target.result +'">'; } function loadimage(e1) { var filename = e1.target.files[0]; var fr = new FileReader(); fr.onload = imageHandler; fr.readAsDataURL(filename); } window.onload=function() { var x = document.getElementById("filebrowsed"); x.addEventListener('change', readfile, false); var y = document.getElementById("getimage"); y.addEventListener('change', loadimage, false); } </script>

    Read the article

  • efficient collision detection - tile based html5/javascript game

    - by Tom Burman
    Im building a basic rpg game and onto collisions/pickups etc now. Its tile based and im using html5 and javascript. i use a 2d array to create my tilemap. Im currently using a switch statement for whatever key has been pressed to move the player, inside the switch statement. I have if statements to stop the player going off the edge of the map and viewport and also if they player is about to land on a tile with tileID 3 then the player stops. Here is the statement: canvas.addEventListener('keydown', function(e) { console.log(e); var key = null; switch (e.which) { case 37: // Left if (playerX > 0) { playerX--; } if(board[playerX][playerY] == 3){ playerX++; } break; case 38: // Up if (playerY > 0) playerY--; if(board[playerX][playerY] == 3){ playerY++; } break; case 39: // Right if (playerX < worldWidth) { playerX++; } if(board[playerX][playerY] == 3){ playerX--; } break; case 40: // Down if (playerY < worldHeight) playerY++; if(board[playerX][playerY] == 3){ playerY--; } break; } viewX = playerX - Math.floor(0.5 * viewWidth); if (viewX < 0) viewX = 0; if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth; viewY = playerY - Math.floor(0.5 * viewHeight); if (viewY < 0) viewY = 0; if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight; }, false); My question is, is there a more efficient way of handling collisions, then loads of if statements for each key? The reason i ask is because i plan on having many items that the player will need to be able to pickup or not walk through like walls cliffs etc. Thanks for your time and help Tom

    Read the article

  • Creating smooth lighting transitions using tiles in HTML5/JavaScript game

    - by user12098
    I am trying to implement a lighting effect in an HTML5/JavaScript game using tile replacement. What I have now is kind of working, but the transitions do not look smooth/natural enough as the light source moves around. Here's where I am now: Right now I have a background map that has a light/shadow spectrum PNG tilesheet applied to it - going from darkest tile to completely transparent. By default the darkest tile is drawn across the entire level on launch, covering all other layers etc. I am using my predetermined tile sizes (40 x 40px) to calculate the position of each tile and store its x and y coordinates in an array. I am then spawning a transparent 40 x 40px "grid block" entity at each position in the array The engine I'm using (ImpactJS) then allows me to calculate the distance from my light source entity to every instance of this grid block entity. I can then replace the tile underneath each of those grid block tiles with a tile of the appropriate transparency. Currently I'm doing the calculation like this in each instance of the grid block entity that is spawned on the map: var dist = this.distanceTo( ig.game.player ); var percentage = 100 * dist / 960; if (percentage < 2) { // Spawns tile 64 of the shadow spectrum tilesheet at the specified position ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 64 ); } else if (percentage < 4) { ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 63 ); } else if (percentage < 6) { ig.game.backgroundMaps[2].setTile( this.pos.x, this.pos.y, 62 ); } // etc... (sorry about the weird spacing, I still haven't gotten the hang of pasting code in here properly) The problem is that like I said, this type of calculation does not make the light source look very natural. Tile switching looks too sharp whereas ideally they would fade in and out smoothly using the spectrum tilesheet (I copied the tilesheet from another game that manages to do this, so I know it's not a problem with the tile shades. I'm just not sure how the other game is doing it). I'm thinking that perhaps my method of using percentages to switch out tiles could be replaced with a better/more dynamic proximity forumla of some sort that would allow for smoother transitions? Might anyone have any ideas for what I can do to improve the visuals here, or a better way of calculating proximity with the information I'm collecting about each tile? (PS: I'm reposting this from Stack Overflow at someone's suggestion, sorry about the duplicate!)

    Read the article

  • Practices for domain models in Javascript (with frameworks)

    - by AndyBursh
    This is a question I've to-and-fro'd with for a while, and searched for and found nothing on: what're the accepted practices surrounding duplicating domain models in Javascript for a web application, when using a framework like Backbone or Knockout? Given a web application of a non-trivial size with a set of domain models on the server side, should we duplicate these models in the web application (see the example at the bottom)? Or should we use the dynamic nature to load these models from the server? To my mind, the arguments for duplicating the models are in easing validation of fields, ensuring that fields that expected to be present are in fact present etc. My approach is to treat the client-side code like an almost separate application, doing trivial things itself and only relying on the server for data and complex operations (which require data the client-side doesn't have). I think treating the client-side code like this is akin to separation between entities from an ORM and the models used with the view in the UI layer: they may have the same fields and relate to the same domain concept, but they're distinct things. On the other hand, it seems to me that duplicating these models on the server side is a clear violation of DRY and likely to lead to differing results on the client- and server-side (where one piece gets updated but the other doesn't). To avoid this violation of DRY we can simply use Javascripts dynamism to get the field names and data from the server as and when they're neeed. So: are there any accepted guidelines around when (and when not) to repeat yourself in these situations? Or this a purely subjective thing, based on the project and developer(s)? Example Server-side model class M { int A DateTime B int C int D = (A*C) double SomeComplexCalculation = ServiceLayer.Call(); } Client-side model function M(){ this.A = ko.observable(); this.B = ko.observable(); this.C = ko.observable(); this.D = function() { return A() * C(); } this.SomeComplexCalculation = ko.observalbe(); return this; }l M.GetComplexValue = function(){ this.SomeComplexCalculation(Ajax.CallBackToServer()); }; I realise this question is quite similar to this one, but I think this is more about almost wholly untying the web application from the server, where that question is about doing this only in the case of complex calculation.

    Read the article

  • export web page data to excel using javascript [on hold]

    - by Sreevani sri
    I have created web page using html.When i clicked on submit button it will export to excel. using javascript i wnt to export thadt data to excel. my html code is 1. Please give your Name:<input type="text" name="Name" /><br /> 2. Area where you reside:<input type="text" name="Res" /><br /> 3. Specify your age group<br /> (a)15-25<input type="text" name="age" /> (b)26-35<input type="text" name="age" /> (c)36-45<input type="text" name="age" /> (d) Above 46<input type="text" name="age" /><br /> 4. Specify your occupation<br /> (a) Student<input type="checkbox" name="occ" value="student" /> (b) Home maker<input type="checkbox" name="occ" value="home" /> (c) Employee<input type="checkbox" name="occ" value="emp" /> (d) Businesswoman <input type="checkbox" name="occ" value="buss" /> (e) Retired<input type="checkbox" name="occ" value="retired" /> (f) others (please specify)<input type="text" name="others" /><br /> 5. Specify the nature of your family<br /> (a) Joint family<input type="checkbox" name="family" value="jfamily" /> (b) Nuclear family<input type="checkbox" name="family" value="nfamily" /><br /> 6. Please give the Number of female members in your family and their average age approximately<br /> Members Age 1 2 3 4 5<br /> 8. Please give your highest level of education (a)SSC or below<input type="checkbox" name="edu" value="ssc" /> (b) Intermediate<input type="checkbox" name="edu" value="int" /> (c) Diploma <input type="checkbox" name="edu" value="dip" /> (d)UG degree <input type="checkbox" name="edu" value="deg" /> (e) PG <input type="checkbox" name="edu" value="pg" /> (g) Doctorial degree<input type="checkbox" name="edu" value="doc" /><br /> 9. Specify your monthly income approximately in RS <input type="text" name="income" /><br /> 10. Specify your time spent in making a purchase decision at the outlet<br /> (a)0-15 min <input type="checkbox" name="dis" value="0-15 min" /> (b)16-30 min <input type="checkbox" name="dis" value="16-30 min" /> (c) 30-45 min<input type="checkbox" name="dis" value="30-45 min" /> (d) 46-60 min<input type="checkbox" name="dis" value="46-60 min" /><br /> <input type="submit" onclick="exportToExcel()" value="Submit" /> </div> </form>

    Read the article

  • Best Way to automatically compress and minimize JavaScript files in an ASP.NET MVC app

    - by wgpubs
    So I have an ASP.NET MVC app that references a number of javascript files in various places (in the site master and additional references in several views as well). I'd like to know if there is an automated way, and if so what is the recommended approach, for compressing and minimizing such references into a single .js file where possible. Such that this ... <script src="<%= ResolveUrl("~") %>Content/ExtJS/Ext.ux.grid.GridSummary/Ext.ux.grid.GridSummary.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.rating/ext.ux.ratingplugin.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext-starslider/ext-starslider.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.dollarfield.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.combobox.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/ext.ux.datepickerplus/ext.ux.datepickerplus-min.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/SessionProvider.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ExtJS/TabCloseMenu.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/ActivityForm.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/UserForm.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/SwappedGrid.js" type="text/javascript"></script> <script src="<%= ResolveUrl("~") %>Content/ActivityViewer/Tree.js" type="text/javascript"></script> ... could be reduced to something like this ... <script src="<%= ResolveUrl("~") %>Content/MyViewPage-min.js" type="text/javascript"></script> Thanks

    Read the article

  • ASP.NET/JavaScript: How to surround an auto generated JavaScript block with try/catch statement

    - by Rami Shareef
    In the Script documents that asp.net automatically generates how can I surround the whole generated scripts with try/catch statement to avoid 'Microsoft JScript Compilation error' My issue is: i got a DevExpress control (ASPxGridView) that added and set-up in run time, since i activated the grouping functionality in the grid I still get JS error says ';' expected whenever i use (click) on one of grouping/sorting abilities, I activated script Debugging for IE, in the JS code turns out that there is no missing ';' and once i click ignore for the error msg that VS generates every thing works fine, and surly end-user can't see this msg so i figured out if i try/catch the script that may help avoid this error. Thanks in advance

    Read the article

  • PHP and Javascript: Getting file contents with Javascript variable

    - by celliott1997
    Could someone help me to understand why this isn't working? var uname = "<?php echo strtolower($_GET['un']) ?>"; var source = "<?php echo file_get_contents('accounts/"+uname+"') ?>"; console.log(source); I've been trying for a while to get this working and it just doesn't seem to. Before I added in the source variable, it was working fine and displayed the un variable on the page. Thanks.

    Read the article

  • How do I do JavaScript Array Animation

    - by Henry
    I'm making a game but don't know how to do Array Animation with the png Array and game Surface that I made below. I'm trying to make it so that when the Right arrow key is pressed, the character animates as if it is walking to the right and when the Left arrow key is pressed it animates as if it is walking to the left (kind of like Mario). I put everything on a surface instead of the canvas. Everything is explained in the code below. I couldn't find help on this anywhere. I hope what I got below makes sense. I'm basically a beginner with JavaScript. I'll be back if more is needed: <!doctype html5> <html> <head></head> <script src="graphics.js"></script> <script src="object.js"></script> <body onkeydown ="keyDown(event)" onkeyup ="keyUp(event)" ></body> <script> //"Surface" is where I want to display my animation. It's like the HTML // canvas but it's not that. It's just the surface to where everything in the //game and the game itself will be displayed. var Surface = new Graphics(600, 400, "skyblue"); //here's the array that I want to use for animation var player = new Array("StandsRight.png", "WalksRight.png", "StandsLeft.png","WalksLeft.png" ); //Here is the X coordinate, Y coordinate, the beginning png for the animation, //and the object's name "player." I also turned the array into an object (but //I don't know if I was supposed to do that or not). var player = new Object(50, 100, 40, 115, "StandsRight.png","player"); //When doing animation I know that it requires a "loop", but I don't // know how to connect it so that it works with the arrays so that //it could animate. var loop = 0; //this actually puts "player" on screen. It makes player visible and //it is where I would like the animation to occur. Surface.drawObject(player); //this would be the key that makes "player" animation in the righward direction function keyDown(e) { if (e.keyCode == 39); } //this would be the key that makes "player" animation in the leftward direction function keyUp(e){ if (e.keyCode == 39); } //this is the Mainloop where the game will function MainLoop(); //the mainloop functionized function MainLoop(){ //this is how fast or slow I could want the entire game to go setTimeout(MainLoop, 10); } </script> </html> From here, are the "graphic.js" and the "object.js" files below. In this section is the graphics.js file. This graphics.js part below is linked to the: script src="graphics.js" html script section that I wrote above. Basically, below is a seperate file that I used for Graphics, and to run the code above, make this graphics.js code that I post below here, a separate filed called: graphics.js function Graphics(w,h,c) { document.body.innerHTML += "<table style='position:absolute;font- size:0;top:0;left:0;border-spacing:0;border- width:0;width:"+w+";height:"+h+";background-color:"+c+";' border=1><tr><td> </table>\n"; this.drawRectangle = function(x,y,w,h,c,n) { document.body.innerHTML += "<div style='position:absolute;font-size:0;left:" + x + ";top:" + y + ";width:" + w + ";height:" + h + ";background-color:" + c + ";' id='" + n + "'></div>\n"; } this.drawTexture = function(x,y,w,h,t,n) { document.body.innerHTML += "<img style='position:absolute;font-size:0;left:" + x + ";top:" + y + ";width:" + w + ";height:" + h + ";' id='" + n + "' src='" + t + "'> </img>\n"; } this.drawObject = function(o) { document.body.innerHTML += "<img style='position:absolute;font-size:0;left:" + o.X + ";top:" + o.Y + ";width:" + o.Width + ";height:" + o.Height + ";' id='" + o.Name + "' src='" + o.Sprite + "'></img>\n"; } this.moveGraphic = function(x,y,n) { document.getElementById(n).style.left = x; document.getElementById(n).style.top = y; } this.removeGraphic = function(n){ document.getElementById(n).parentNode.removeChild(document.getElementById(n)); } } Finally, is the object.js file linked to the script src="object.js"" in the html game file above the graphics.js part I just wrote. Basically, this is a separate file too, so thus, in order to run or test the html game code in the very first section I wrote, a person has to also make this code below a separate file called: object.js I hope this helps: function Object(x,y,w,h,t,n) { this.X = x; this.Y = y; this.Velocity_X = 0; this.Velocity_Y = 0; this.Previous_X = 0; this.Previous_Y = 0; this.Width = w; this.Height = h; this.Sprite = t; this.Name = n; this.Exists = true; } In all, this game is made based on a tutorial on youtube at: http://www.youtube.com/watch?v=t2kUzgFM4lY&feature=relmfu I'm just trying to learn how to add animations with it now. I hope the above helps. If not, let me know. Thanks

    Read the article

  • Monitoring Html Element CSS Changes in JavaScript

    - by Rick Strahl
    [ updated Feb 15, 2011: Added event unbinding to avoid unintended recursion ] Here's a scenario I've run into on a few occasions: I need to be able to monitor certain CSS properties on an HTML element and know when that CSS element changes. For example, I have a some HTML element behavior plugins like a drop shadow that attaches to any HTML element, but I then need to be able to automatically keep the shadow in sync with the window if the  element dragged around the window or moved via code. Unfortunately there's no move event for HTML elements so you can't tell when it's location changes. So I've been looking around for some way to keep track of the element and a specific CSS property, but no luck. I suspect there's nothing native to do this so the only way I could think of is to use a timer and poll rather frequently for the property. I ended up with a generic jQuery plugin that looks like this: (function($){ $.fn.watch = function (props, func, interval, id) { /// <summary> /// Allows you to monitor changes in a specific /// CSS property of an element by polling the value. /// when the value changes a function is called. /// The function called is called in the context /// of the selected element (ie. this) /// </summary> /// <param name="prop" type="String">CSS Properties to watch sep. by commas</param> /// <param name="func" type="Function"> /// Function called when the value has changed. /// </param> /// <param name="interval" type="Number"> /// Optional interval for browsers that don't support DOMAttrModified or propertychange events. /// Determines the interval used for setInterval calls. /// </param> /// <param name="id" type="String">A unique ID that identifies this watch instance on this element</param> /// <returns type="jQuery" /> if (!interval) interval = 200; if (!id) id = "_watcher"; return this.each(function () { var _t = this; var el$ = $(this); var fnc = function () { __watcher.call(_t, id) }; var itId = null; var data = { id: id, props: props.split(","), func: func, vals: [props.split(",").length], fnc: fnc, origProps: props, interval: interval }; $.each(data.props, function (i) { data.vals[i] = el$.css(data.props[i]); }); el$.data(id, data); hookChange(el$, id, data.fnc); }); function hookChange(el$, id, fnc) { el$.each(function () { var el = $(this); if (typeof (el.get(0).onpropertychange) == "object") el.bind("propertychange." + id, fnc); else if ($.browser.mozilla) el.bind("DOMAttrModified." + id, fnc); else itId = setInterval(fnc, interval); }); } function __watcher(id) { var el$ = $(this); var w = el$.data(id); if (!w) return; var _t = this; if (!w.func) return; // must unbind or else unwanted recursion may occur el$.unwatch(id); var changed = false; var i = 0; for (i; i < w.props.length; i++) { var newVal = el$.css(w.props[i]); if (w.vals[i] != newVal) { w.vals[i] = newVal; changed = true; break; } } if (changed) w.func.call(_t, w, i); // rebind event hookChange(el$, id, w.fnc); } } $.fn.unwatch = function (id) { this.each(function () { var el = $(this); var fnc = el.data(id).fnc; try { if (typeof (this.onpropertychange) == "object") el.unbind("propertychange." + id, fnc); else if ($.browser.mozilla) el.unbind("DOMAttrModified." + id, fnc); else clearInterval(id); } // ignore if element was already unbound catch (e) { } }); return this; } })(jQuery); With this I can now monitor movement by monitoring say the top CSS property of the element. The following code creates a box and uses the draggable (jquery.ui) plugin and a couple of custom plugins that center and create a shadow. Here's how I can set this up with the watcher: $("#box") .draggable() .centerInClient() .shadow() .watch("top", function() { $(this).shadow(); },70,"_shadow"); ... $("#box") .unwatch("_shadow") .shadow("remove"); This code basically sets up the window to be draggable and initially centered and then a shadow is added. The .watch() call then assigns a CSS property to monitor (top in this case) and a function to call in response. The component now sets up a setInterval call and keeps on pinging this property every time. When the top value changes the supplied function is called. While this works and I can now drag my window around with the shadow following suit it's not perfect by a long shot. The shadow move is delayed and so drags behind the window, but using a higher timer value is not appropriate either as the UI starts getting jumpy if the timer's set with too small of an increment. This sort of monitor can be useful for other things as well where operations are maybe not quite as time critical as a UI operation taking place. Can anybody see a better a better way of capturing movement of an element on the page?© Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  JavaScript  jQuery  

    Read the article

  • Getting Started with TypeScript – Classes, Static Types and Interfaces

    - by dwahlin
    I had the opportunity to speak on different JavaScript topics at DevConnections in Las Vegas this fall and heard a lot of interesting comments about JavaScript as I talked with people. The most frequent comment I heard from people was, “I guess it’s time to start learning JavaScript”. Yep – if you don’t already know JavaScript then it’s time to learn it. As HTML5 becomes more and more popular the amount of JavaScript code written will definitely increase. After all, many of the HTML5 features available in browsers have little to do with “tags” and more to do with JavaScript (web workers, web sockets, canvas, local storage, etc.). As the amount of JavaScript code being used in applications increases, it’s more important than ever to structure the code in a way that’s maintainable and easy to debug. While JavaScript patterns can certainly be used (check out my previous posts on the subject or my course on Pluralsight.com), several alternatives have come onto the scene such as CoffeeScript, Dart and TypeScript. In this post I’ll describe some of the features TypeScript offers and the benefits that they can potentially offer enterprise-scale JavaScript applications. It’s important to note that while TypeScript has several great features, it’s definitely not for everyone or every project especially given how new it is. The goal of this post isn’t to convince you to use TypeScript instead of standard JavaScript….I’m a big fan of JavaScript. Instead, I’ll present several TypeScript features and let you make the decision as to whether TypeScript is a good fit for your applications. TypeScript Overview Here’s the official definition of TypeScript from the http://typescriptlang.org site: “TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.” TypeScript was created by Anders Hejlsberg (the creator of the C# language) and his team at Microsoft. To sum it up, TypeScript is a new language that can be compiled to JavaScript much like alternatives such as CoffeeScript or Dart. It isn’t a stand-alone language that’s completely separate from JavaScript’s roots though. It’s a superset of JavaScript which means that standard JavaScript code can be placed in a TypeScript file (a file with a .ts extension) and used directly. That’s a very important point/feature of the language since it means you can use existing code and frameworks with TypeScript without having to do major code conversions to make it all work. Once a TypeScript file is saved it can be compiled to JavaScript using TypeScript’s tsc.exe compiler tool or by using a variety of editors/tools. TypeScript offers several key features. First, it provides built-in type support meaning that you define variables and function parameters as being “string”, “number”, “bool”, and more to avoid incorrect types being assigned to variables or passed to functions. Second, TypeScript provides a way to write modular code by directly supporting class and module definitions and it even provides support for custom interfaces that can be used to drive consistency. Finally, TypeScript integrates with several different tools such as Visual Studio, Sublime Text, Emacs, and Vi to provide syntax highlighting, code help, build support, and more depending on the editor. Find out more about editor support at http://www.typescriptlang.org/#Download. TypeScript can also be used with existing JavaScript frameworks such as Node.js, jQuery, and others and even catch type issues and provide enhanced code help. Special “declaration” files that have a d.ts extension are available for Node.js, jQuery, and other libraries out-of-the-box. Visit http://typescript.codeplex.com/SourceControl/changeset/view/fe3bc0bfce1f#samples%2fjquery%2fjquery.d.ts for an example of a jQuery TypeScript declaration file that can be used with tools such as Visual Studio 2012 to provide additional code help and ensure that a string isn’t passed to a parameter that expects a number. Although declaration files certainly aren’t required, TypeScript’s support for declaration files makes it easier to catch issues upfront while working with existing libraries such as jQuery. In the future I expect TypeScript declaration files will be released for different HTML5 APIs such as canvas, local storage, and others as well as some of the more popular JavaScript libraries and frameworks. Getting Started with TypeScript To get started learning TypeScript visit the TypeScript Playground available at http://www.typescriptlang.org. Using the playground editor you can experiment with TypeScript code, get code help as you type, and see the JavaScript that TypeScript generates once it’s compiled. Here’s an example of the TypeScript playground in action:   One of the first things that may stand out to you about the code shown above is that classes can be defined in TypeScript. This makes it easy to group related variables and functions into a container which helps tremendously with re-use and maintainability especially in enterprise-scale JavaScript applications. While you can certainly simulate classes using JavaScript patterns (note that ECMAScript 6 will support classes directly), TypeScript makes it quite easy especially if you come from an object-oriented programming background. An example of the Greeter class shown in the TypeScript Playground is shown next: class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } Looking through the code you’ll notice that static types can be defined on variables and parameters such as greeting: string, that constructors can be defined, and that functions can be defined such as greet(). The ability to define static types is a key feature of TypeScript (and where its name comes from) that can help identify bugs upfront before even running the code. Many types are supported including primitive types like string, number, bool, undefined, and null as well as object literals and more complex types such as HTMLInputElement (for an <input> tag). Custom types can be defined as well. The JavaScript output by compiling the TypeScript Greeter class (using an editor like Visual Studio, Sublime Text, or the tsc.exe compiler) is shown next: var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })(); Notice that the code is using JavaScript prototyping and closures to simulate a Greeter class in JavaScript. The body of the code is wrapped with a self-invoking function to take the variables and functions out of the global JavaScript scope. This is important feature that helps avoid naming collisions between variables and functions. In cases where you’d like to wrap a class in a naming container (similar to a namespace in C# or a package in Java) you can use TypeScript’s module keyword. The following code shows an example of wrapping an AcmeCorp module around the Greeter class. In order to create a new instance of Greeter the module name must now be used. This can help avoid naming collisions that may occur with the Greeter class.   module AcmeCorp { export class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } } var greeter = new AcmeCorp.Greeter("world"); In addition to being able to define custom classes and modules in TypeScript, you can also take advantage of inheritance by using TypeScript’s extends keyword. The following code shows an example of using inheritance to define two report objects:   class Report { name: string; constructor (name: string) { this.name = name; } print() { alert("Report: " + this.name); } } class FinanceReport extends Report { constructor (name: string) { super(name); } print() { alert("Finance Report: " + this.name); } getLineItems() { alert("5 line items"); } } var report = new FinanceReport("Month's Sales"); report.print(); report.getLineItems();   In this example a base Report class is defined that has a variable (name), a constructor that accepts a name parameter of type string, and a function named print(). The FinanceReport class inherits from Report by using TypeScript’s extends keyword. As a result, it automatically has access to the print() function in the base class. In this example the FinanceReport overrides the base class’s print() method and adds its own. The FinanceReport class also forwards the name value it receives in the constructor to the base class using the super() call. TypeScript also supports the creation of custom interfaces when you need to provide consistency across a set of objects. The following code shows an example of an interface named Thing (from the TypeScript samples) and a class named Plane that implements the interface to drive consistency across the app. Notice that the Plane class includes intersect and normal as a result of implementing the interface.   interface Thing { intersect: (ray: Ray) => Intersection; normal: (pos: Vector) => Vector; surface: Surface; } class Plane implements Thing { normal: (pos: Vector) =>Vector; intersect: (ray: Ray) =>Intersection; constructor (norm: Vector, offset: number, public surface: Surface) { this.normal = function (pos: Vector) { return norm; } this.intersect = function (ray: Ray): Intersection { var denom = Vector.dot(norm, ray.dir); if (denom > 0) { return null; } else { var dist = (Vector.dot(norm, ray.start) + offset) / (-denom); return { thing: this, ray: ray, dist: dist }; } } } }   At first glance it doesn’t appear that the surface member is implemented in Plane but it’s actually included automatically due to the public surface: Surface parameter in the constructor. Adding public varName: Type to a constructor automatically adds a typed variable into the class without having to explicitly write the code as with normal and intersect. TypeScript has additional language features but defining static types and creating classes, modules, and interfaces are some of the key features it offers. So is TypeScript right for you and your applications? That’s a not a question that I or anyone else can answer for you. You’ll need to give it a spin to see what you think. In future posts I’ll discuss additional details about TypeScript and how it can be used with enterprise-scale JavaScript applications. In the meantime, I’m in the process of working with John Papa on a new Typescript course for Pluralsight that we hope to have out in December of 2012.

    Read the article

  • Good resources and tools for modern, heavy JavaScript development?

    - by Matt Greer
    I am interested in doing some projects that involve heavy use of JavaScript. Namely HTML5 based canvas games, potentially using node.js as well. I am interested in learning modern best practices, tools and resources for JavaScript. JavaScript is tough to research because you end up wading through a lot of really outdated material, hailing from the times that "JavaScript" was a four letter word. If you are heavily involved in JavaScript programming... What text editor or IDE do you use? What unit testing framework do you use? Do you use Selenium, or something else? What other tools do you use? What communities exist that discuss recent advents in JavaScript? What books do you read/refer to? What blogs do you read?

    Read the article

  • Preserve onchange for a dropdown list when setting the value with Javascript.

    - by Zac Altman
    I have a dropdown list with a piece of code that is run when the value is changed: <select name="SList" onchange="javascript:setTimeout('__doPostBack(\'SList\',\'\')', 0)" id="SList"> Everything works fine when manually done. As an option is selected, the onchange code is called. The problem begins when I try to change the selected value using a piece of Javscript. I want to be able to automatically change the selected option using JS, whilst still having the onchange code called, exactly as if done manually. I try calling this: form.SList.value = "33"; The right option is selected, but the onchange code does not get called. So then I try doing this: form.SList.value = "33"; javascript:setTimeout('__doPostBack(\'SList\',\'\')', 0); The right value is not selected and nothing happens. FYI, the code is done in ASP.NET and Javascript. What can I run to change the selected option whilst still calling the onchange code?

    Read the article

  • Hijax == sneaky Javascript redirects? Will I get banned from Google?

    - by Chris Jacob
    Question Will I get penalised as "sneaky Javascript redirects" by Google if I have the following Hijax setup (which requires a JavaScript redirect on the page indexed by google). Goal I want to implement Hijax to enable AJAX content to be accessibile to non-JavaScript users and search engine crawlers. Background I'm working on a static file server (GitHub Pages). No server side tricks allowed (so Google's #! "hash bang" solution is not an option). I'm trying to keep my files DRY. I don't want to repeat the common OUTER template in all my files i.e. header, navigation menu, footer, etc They will live in the main index.html Setup the Hijax index.html page contains all OUTER html/css/js... the site's template. index.html has a <div id="content"> which defaults to containing the "homepage" html. index.html has a navigation menu, with a Hijax link to an "about" page. With JavaScript disabled (e.g. crawler) it follows link to /about.html. With JavaScript enabled (e.g. most people) the link updates the url hash fragment to /#about and jQuery replaces the <div id="content"> innerHTML with $("#content").load("about.html #inner-container");. AJAX content about.html does not contain anything extra to try an cloak content for crawlers. about.html file contains enough HTML / CSS / JavaScript to display /about.html as a standalone page with it's own META data... e.g. <html><head><title>About</title>...</head><body></body></html>. about.html has NO OUTER HTML template (i.e. header, navigation menu, footer, etc). about.html <body> contains a <div id="inner-container"> which holds the content that is injected into index.html. about.html has a <noscript> tag as the first child of <body> which explains to non-JavaScript users that they are viewing the about page "inner content" - with a link to navigate to the index.html page to get the full page layout with menu. The (Sneaky?) Redirect Google indexes the /about.html page. However when a person with JavaScript enabled visits that page there is no OUTER html template (e.g. header, navigation menu, footer, etc). So I need to do a JavaScript redirect to get the person over the /#about page (deeplinking to the "about" page "state" in index.html). I'm thinking of doing a "redirect on click or after 10 seconds". The end results is that user ends up on an "enhanced" page back on index.html with all it's OUTER template - but the core "page" content is practically identical. Known issue with inbound links e.g. Share / Bookmarking It seems that if a user shares the URL /#about on their blog, when allocating inbound links to my site Google ignores everything after the # ... it allocates value to the / page - See: http://stackoverflow.com/questions/5028405/hashbang-vs-hijax/5166665#5166665. I can only try an minimise this issue offering "share" buttons on the page with the appropriate urls i.e. /about.html. Duplicate Sorry. I posted this same question over on http://stackoverflow.com/questions/5561686/hijax-sneaky-javascript-redirects-will-i-get-banned-from-google ... then realised it probably belongs more on this Stack Exchange site... Not sure if I should delete the Stack Overflow question? Or just leave it on both sites? Please leave comment.

    Read the article

  • What are the typical reasons Javascript developed on Firefox fails on IE?

    - by karlthorwald
    I developed some javascript enhanced pages that run fine on recent Firefox and Safari. I missed to check in Internet Explorer, and now I find the pages don't work on IE 6 and 7 (so far). The scripts are somehow not executed, the pages show as if javascript wasn't there, although some javascript is executed. I am using own libraries with dom manipulation, from YUI 2 I use YUI-Loader and the XML-Http-Request, and on one page I use "psupload", which depends on JQuery. I am installing Microsoft Script Editor from Office XP and will now debug. I will also write specific tests now. What are the typical failing points of IE? What direction I can keep my eyes open. I found this page, which shows some differences: http://www.quirksmode.org/compatibility.html Can you from your experience name some typical things I should look for first? I will also ask more questions here for specific tasks later, but for now I am interested in your experience why IE usually fails on scripts that run fine in Firefox

    Read the article

  • Function currying in Javascript

    - by kerry
    Do you catch yourself doing something like this often? 1: Ajax.request('/my/url', {'myParam': paramVal}, function() { myCallback(paramVal); }); Creating a function which calls another function asynchronously is a bad idea because the value of paramVal may change before it is called.  Enter the curry function: 1: Function.prototype.curry = function(scope) { 2: var args = []; 3: for (var i=1, len = arguments.length; i < len; ++i) { 4: args.push(arguments[i]); 5: } 6: var m = this; 7: return function() { 8: m.apply(scope, args); 9: }; 10: } This function creates a wrapper around the function and ‘locks in’ the method parameters.  The first parameter is the scope of the function call (usually this or window).  Any remaining parameters will be passed to the method call.  Using the curry method the above call changes to: 1: Ajax.request('/my/url', {'myParam': paramVal}, myCallback.curry(window,paramVal)); Remember when passing objects to the curry method that the objects members may still change.

    Read the article

  • Pass Extra Parameters to JavaScript Callback Function

    - by BRADINO
    Here is a simple example of a function that takes a callback function as a parameter. query.send(handleQueryResponse); function handleQueryResponse(response){      alert('Processing...'); } If you wanted to pass extra variables to the callback function, you can do it like this. var param1 = 'something'; var param2 ='something else'; query.send(function(response) { handleQueryResponse(response, param1, param2) }); function handleQueryResponse(response,param1,param2){      alert('Processing...');      alert(param1);      alert(param2); }

    Read the article

  • javascript game loop and game update design

    - by zuo
    There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like updateEveryNFrames(n, func). I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the counter % n. For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation. Can some give some advice or other solutions?

    Read the article

  • Experience formula with javascript

    - by StealingMana
    I'm having trouble working out a formula using this experience curve to get the total exp after each level. I bet its easy and im just over thinking it. maxlvl = 10; increment = 28; baseexp = 100; function calc(){ for (i = 0;i<(maxlvl*increment);i+=increment){ expperlvl = baseexp + i; document.writeln(expperlvl); } } I figured it out. maxlvl=6; base=200; increment=56; function total(){ totalxp= (base*(maxlvl-1))+(increment*(maxlvl-2)*(maxlvl-1)/2); document.write(totalxp); }

    Read the article

  • JavaScript objects and Crockford's The Good Parts

    - by Jonathan
    I've been thinking quite a bit about how to do OOP in JS, especially when it comes to encapsulation and inheritance, recently. According to Crockford, classical is harmful because of new(), and both prototypal and classical are limited because their use of constructor.prototype means you can't use closures for encapsulation. Recently, I've considered the following couple of points about encapsulation: Encapsulation kills performance. It makes you add functions to EACH member object rather than to the prototype, because each object's methods have different closures (each object has different private members). Encapsulation forces the ugly "var that = this" workaround, to get private helper functions to have access to the instance they're attached to. Either that or make sure you call them with privateFunction.apply(this) everytime. Are there workarounds for either of two issues I mentioned? if not, do you still consider encapsulation to be worth it? Sidenote: The functional pattern Crockford describes doesn't even let you add public methods that only touch public members, since it completely forgoes the use of new() and constructor.prototype. Wouldn't a hybrid approach where you use classical inheritance and new(), but also call Super.apply(this, arguments) to initialize private members and privileged methods, be superior?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >