Do you know a js library that implements a generic Iterator class for collections (be it Arrays or some abstract Enumerable) with a full set of features, like the Google Common or the Apache Commons?
I've done a lot of research on this but have come up empty handed. What I would like to do is invoke or create an event for the right arrow key (Key Code 39). I was planning on using an onclick event inside an tag to go to a function where this event could be 'fired'. Any help would be appreciated.
If anyone needs context, I have a jQuery content slider that's functionality is very hard to alter and currently the functionality I need to emulate only occurs when a user hits the right arrow on their keyboard. What I would like to do is tie an onclick() event to a image that when clicked on fires the right keyboard event and the content will slide. Please let me know if I can provide further details or explanation.
My working demo for this is: http://greenplanet3d.com
I need to replace a substring from some string. I've already created corrected code for doing it. But I amn't sure is it best way. Please, see code below:
var str = 'test ruby,ruby on rails,ruby,'
var substr = 'ruby';
var reg = new RegExp(',' + substr + ',|^' + substr + ',', 'gi');
str.replace(reg, ','); //returns "test ruby,ruby on rails,"
I've got a list of links that point to images, and a js function that takes a URL (of an image) and puts that image on the page when the function is called.
I was originally adding an inline onlick="showPic(this.getAttribute('href'))" to each a, but I want to separate out the inline js. Here's my func for adding an onclick to each a tag when the page loads:
function prepareLinks(){
var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++){
var thisLink = links[i];
var source = thisLink.getAttribute('href');
if(thisLink.getAttribute('class') == 'imgLink'){
thisLink.onclick = function(){
showPic(source);
return false;
}
}
}
}
function showPic(source){
var placeholder = document.getElementById('placeholder');
placeholder.setAttribute('src',source);
}
window.onload = prepareLinks();
...but every time showPic is called, the source var is the href of the last image. How can I make each link have the correct onclick?
I have tried rectifying the code below. But I am not able to find a solution. After executing the code, firebug says "document.getElementById(haystack.value) is null". I tried if(document.getElementById(haystack).value ==null) but it was of no use. Please help me out.
var haystack=document.getElementById('city1').value;
if(!document.getElementById(haystack).value)
{
alert("null");
}
else
{
alert("not null");
}
I'm developing a website using the Seam framework and the RichFaces AJAX library (these isn't really all that important to the problem at hand - just some background).
I seem to have uncovered a bug, however, in RichFaces which, in certain instances, will cause AJAX-based updating to fail in IE8 (see here for more info: http://community.jboss.org/message/585737).
The following is the code where the exception is occurring:
var anchor = oldnode.parentNode;
if(!window.opera && !A4J.AJAX.isWebkitBreakingAmps() && oldnode.outerHTML && !oldnode.tagName.match( /(tbody|thead|tfoot|tr|th|td)/i ) ){
LOG.debug("Replace content of node by outerHTML()");
if (!Sarissa._SARISSA_IS_IE || oldnode.tagName.toLowerCase()!="table") {
try {
oldnode.innerHTML = "";
} catch(e){
LOG.error("Error to clear node content by innerHTML "+e.message);
Sarissa.clearChildNodes(oldnode);
}
}
oldnode.outerHTML = new XMLSerializer().serializeToString(newnode);
}
The last line (the one with XMLSerializer) is where the exception is occurring in IE. I was wondering if anyone knows of any replacement method / library / etc I could use there (only on IE is fine). Thanks.
I have a javasrcript variable
var hash = {
'.bmp' : 1,
'.gif' : 1,
'.jpeg' : 1,
'.jpg' : 1,
'.png' : 1,
'.tif' : 1,
'.tiff' : 1,
};
I want to display the values (.bmp, .gif, .jpeg, .jpg, .png, .tif, .tiff) of this "hash" object in my alert message. How can I do this? Please help.
I am trying to recreate this, and I have been fairly successful. I am having issues with the collision handling though. Although the collision handling seems to work, it has very strange behavior. Here is what I have so far. This is the code that handles collisions:
var dx = particle2.getX() - particle1.getX();
var dy = particle2.getY() - particle1.getY();
var angle = Math.atan2(dy, dx);
var newP2X = particle1.getX() + (particle1.getRadius() + particle2.getRadius()) * Math.cos(angle);
var newP2Y = particle1.getY() + (particle1.getRadius() + particle2.getRadius()) * Math.sin(angle);
particle2.setX(newP2X);
particle2.setY(newP2Y);
var p1Vxi = particle1.getVx();
var p1Vyi = particle1.getVy();
var p1Mass = particle1.getMass();
var p2Vxi = particle2.getVx();
var p2Vyi = particle2.getVy();
var p2Mass = particle2.getMass();
var vxf = (p1Mass * p1Vxi + p2Mass * p2Vxi) / (p1Mass + p2Mass);
var vyf = (p1Mass * p1Vyi + p2Mass * p2Vyi) / (p1Mass + p2Mass);
particle1.setVx(vxf);
particle1.setVy(vyf);
particle2.setVx(vxf);
particle2.setVy(vyf);
EDIT: I have tried to change it to inelastic collisions like suggested, but for some reason the balls collide erratically. Check it out here.
Any help is much appreciated!
I have an iframe which content is a php-file, and that php-file displays some mysql records.
The more records, the larger the iframe height should get, otherwise it wont show all of the information in the iframe.
Here is a code I have for dynamically setting the iframe height, from the iframes content (the php file):
var x = document.body.scrollHeight;
x = x + 20 + 'px';
window.parent.document.getElementById("iframe001").style.height=x;
iframe001 is the iframe I am referring to above.
I am adding 20px of height extra because of borders etc...
Now, sometimes this resizing works, sometimes it doesn't.
Does anybody know why it works sometimes. If I alert the 'x' variable, it shows different values sometimes, but most times it works.
Any other ways you know of setting the iframes height from the content of the iframe?
Thanks
I am working on a project similar to a table where the user will be able to add rows. Right now there is just one row type available but I would like to give the user the ability to select from a list without changing the layout of the page. So, I put together a menu that appears on mouseover of the 'add row' link and disappears on mouseout (with a slight delay and fade in/out) using mootools event listeners. It looks like:
I am now trying to figure out an easy way to make it so that the list stays available when the user's mouse leaves the 'add a row' link to go to select an item from the list. I looked through various mootools add-ons and tutorial but didn't find anything all that helpful. Does anyone know of a good tutorial guide me through this or can otherwise point me in the right direction here?
I have problem with validation such code
function show_help_tip(event, element) {
var $e = $(element);
var pos = $e.offset();
$('.body-balloon',$help_tip_div).html($(' <p> </p> ').html(element.getAttribute('title')));
$help_tip_div.css({position:'absolute',top:530,left:pos.left+$e.width()-20}).show();
}
end tag for element "P" which is not open
What's wrong?
See following class:
function availItem(xs, s, m, l, xl) {
this.xs = xs;
this.s = s;
this.m = m;
this.l = l;
this.xl = xl;
}
How can I declare the above class using JSON? I think It should be in following manner but problem is to pass argument.
var availItem = {
xs : xs,
s : s,
m : m,
l : l,
xl : xl
}
Still trying to answer this question, and I think I finally found a solution, but it runs too slow.
var $div = $('<div>')
.css({ 'border': '1px solid red', 'position': 'absolute', 'z-index': '65535' })
.appendTo('body');
$('body *').live('mousemove', function(e) {
var topElement = null;
$('body *').each(function() {
if(this == $div[0]) return true;
var $elem = $(this);
var pos = $elem.offset();
var width = $elem.width();
var height = $elem.height();
if(e.pageX > pos.left && e.pageY > pos.top
&& e.pageX < (pos.left + width) && e.pageY < (pos.top + height)) {
var zIndex = document.defaultView.getComputedStyle(this, null).getPropertyValue('z-index');
if(zIndex == 'auto') zIndex = $elem.parents().length;
if(topElement == null || zIndex > topElement.zIndex) {
topElement = {
'node': $elem,
'zIndex': zIndex
};
}
}
});
if(topElement != null ) {
var $elem = topElement.node;
$div.offset($elem.offset()).width($elem.width()).height($elem.height());
}
});
It basically loops through all the elements on the page and finds the top-most element beneath the cursor.
Is there maybe some way I could use a quad-tree or something and segment the page so the loop runs faster?
I want to call function with arguement periodically.
I tried setTimeout("fnName()",timeinseconds); and it is working.
But when I add an arguement it won't work. eg: setTimeout("fnName('arg')",timeinseconds);
I'm wondering about the .childNodes property, I have the code below, and for some reason I get 18 children, while 6 are HTMLInputElements as expected, and the rest are undefined. What is this about? Is there an efficient way to iterate over the input elements?
<html>
<head>
<script>
window.onload = function(e){
form = document.getElementById('myForm');
alert(form.childNodes.length);
for(i=0; i<form.childNodes.length; i++){
alert(form[i]);
}
}
</script>
</head>
<body>
<form id='myForm' action="haha" method="post">
Name: <input type="text" id="fnameAdd" name="name" /><br />
Phone1: <input type="text" id="phone1Add" name="phone1" /><br />
Phone2: <input type="text" id="phone2Add" name="phone2" /><br />
E-Mail: <input type="text" id="emailAdd" name="email" /><br />
Address: <input type="text" id="addressAdd" name="address" /><br />
<input type="submit" value="Save" />
</body>
</html>
I was so sure that this question has been answered a thousand times before, but I've been unable to find an answer in StackOverflow. If there is already an answer and I was unable to find it then I apologize.
I create hidden form elements dynamically like this:
submitForm=document.getElementById('my-form');
var element=document.createElement('input');
element.id='hidden-form-data'; // or setAttribute('id','hidden-form-data');
element.name='my-hidden-form-data';
element.type='hidden';
element.value='my-data';
submitForm.appendChild(element);
This works and the input field is created and it is taken into account when submitting the form.
But I want to remove it after I have dynamically created it. I was sure that creating a new node this way would be 'correct' for browser and DOM, but apparently it is not.
This returns null:
element=document.getElementById('hidden-form-data');
if(element!=null){
element.parentNode.removeChild(element);
}
But it never gets removed and is always null.
Is there any way I can remove a dynamically created node with an ID?
Thank you!
Please do not suggest jQuery, it's not possible to use jQuery for this, footprint is too heavy for such a small task
I could not get a working answer from here, which was the closest thread I could find.
Based on a click event on the page, via ajax I fetch a block of html and script, I am able to take the script element and append it to the head element, however WebKit based browsers are not treating it as script (ie. I cannot invoke a function declared in the appended script).
Using the Chrome Developer Tools I can see that my script node is indeed there, but it shows up differently then a script block that is not added dynamically, a non-dynamic script has a text child element and I cannot figure out a way to duplicate this for the dynamic script.
Any ideas or better ways to be doing this? The driving force is there is potentially a lot of html and script that would never be needed unless a user clicks on a particular tab, in which case the relevant content (and script) would be loaded. Thanks!
Hi all.
I've some data that i'd like to publish just on one website, ie. it should not be reused on other websites. The data is a set of numbers that change every day, our journalists work to get hard gather it.
Is there any way to hide, crypt, etc. the data in a way that it cannot be reused by others? But to show it in a graph in the same time?
I found the ASCII to HEX tool that could be used for (http://utenti.multimania.it/ascii2hex/). I wonder if you can suggest other ways. (Even if I have to completely change the strategy.)
Many thanks!
I 'm writing a code with JS and I don't know how to populate array when clicking on button. We have this code, which uses a list (ul), where the items (li) can be moved with mouse. How can do onclick to populate an array with 2 data, its first position and the last position?
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="https://raw.github.com/furf/jquery-ui-touch-punch/master/jquery.ui.touch-punch.min.js"></script>
<script>
$(function() {
$( ".documents" ).sortable();
$( ".documents" ).disableSelection();
});
</script>
<meta charset="utf-8">
<title>toArray demo</title>
<style>
span {
color: red;
}
</style>
</head>
<body>
Reversed - <span></span>
<ul id="opciones" class="documents">
<li>uno</li>
<li>dos</li>
<li>tres</li>
</ul>
<script>
function disp( li ) {
var a = [];
for ( var i = 0; i < li.length; i++ ) {
a.push( li[ i ].innerHTML );
}
$( "span" ).text( a.join( " " ) );
}
disp( $( "li" ).toArray() );
</script>
<input type="button" value="actualizar_array" onclick="disp('#opciones')" />
</body>
</html>
I'm writing a Rails app and I've partially integrated in this nice little patch to the in line ajax editor: http://inplacericheditor.box.re/
The problem is, on that page I have tinymce, prototype and scriptaculous included. In Firefox at least there's a big lag when all this stuff is loading. I was hoping to fix it by compressing the files so I checked out a plugin for rails called Smurf. It seemed to do what it was supposed to do nicely, but it choked on the little patch files that are included with the Ajax editor thing. THe patch files look like this:
Object.extend(Ajax.InPlaceEditor.prototype, {
handleAJAXFailure: function(transport)
Alternatively, should I just be catching them instead of worrying about minfying them? I know I'm running on development and that Apache would maybe be handling serving the js files differently..It just seems like a lot of things to serve on one page.
Is
for (var i=0, cols=columns.length; i<cols; i++) { ... }
more efficient than
for (var i=0; i<columns.length; i++) { ... }
?
In the second variant, is columns.length calculated each time the condition i<columns.length is checked ?
I want to implement zooming on the mouse pointer with the mouse wheel. That is scaling the image while the point under the mouse pointer stays fixed.
Here is my code, which doesn't work very well
var scala = 1 + event.wheelDelta / 1000;
canvas.context.translate(-canvas.mouse.x * ( scala - 1 ) / canvas.scale,-canvas.mouse.y * ( scala - 1 ) / canvas.scale);
canvas.context.scale(scala,scala);
canvas.scale *= scala;
//canvas.scale is my variable that is initially set to 1.
//canvas.mouse is my variable that represents the mouse position relative to the canvas
Is it possible to create an object container where changes can be tracked
Said object is a complex nested object of data. (compliant with JSON).
The wrapper allows you to get the object, and save changes, without specifically stating what the changes are
Does there exist a design pattern for this kind of encapsulation
Deep cloning is not an option since I'm trying to write a wrapper like this to avoid doing just that.
The solution of serialization should only be considered if there are no other solutions.
An example of use would be
var foo = state.get();
// change state
state.update(); // or state.save();
client.tell(state.recentChange());
A jsfiddle snippet might help : http://jsfiddle.net/Raynos/kzKEp/
It seems like implementing an internal hash to keep track of changes is the best option.
[Edit]
To clarify this is actaully done on node.js on the server. The only thing that changes is that the solution can be specific to the V8 implementation.