Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



I wrote this to make it easier to slap a quick canvas element into jsconsole

code:
(function _loader(window){
	if(!window.document.getElementById('thecanvas')){
		var can = document.createElement('canvas');
		can.setAttribute('height', '200');
		can.setAttribute('width', '200');
		can.setAttribute('id', 'thecanvas');
		can.setAttribute('style', 'border: 1px solid black');
		window.document.getElementById('input').parentNode.appendChild(can);
		window.can = can;
		window.ctx = can.getContext("2d");
	}
})(window);
And it works fine in FF 3.6 when I load it using load('http://localhost/addCanvas.js')*, but not in Opera and I can't figure out why. It doesn't even seem to be running _loader. Does anyone see anything wrong that I'm not?

*I tired using my IP, too in case it was a security thing, but no dice.

Adbot
ADBOT LOVES YOU

Bearnt!
Feb 6, 2004

No onions, no onions
I have this here. You should be able to see all the code from a View>Source. It functions fine, the only problem I'm having is that it shows all three drop down menus when the page is first loaded. When you start clicking the radio button's this changes to show only the corresponding drop down menu which I want. I'm sure it's something easy but I'm pretty new at this stuff so if someone could supply me with the correct code/what I need to edit that would really be fantastic as this is starting to get very frustrating. Thanks!

epswing
Nov 4, 2003

Soiled Meat

Bearnt! posted:


Set display: none; on the two divs you don't want to display right away.

code:
...
<div id="IDX-searchPage-countyField" class="IDX-searchBox" style="display: none;">
...
<div id="IDX-searchPage-zipCodeField" class="IDX-searchBox" style="display: none;">
...

Hughmoris
Apr 21, 2007
Let's go to the abyss!
Can somebody recommend me a book to learn Javascript. I have no programming experience worth mentioning so I need one that starts from scratch, and I am only looking to learn this as a hobby.

epswing
Nov 4, 2003

Soiled Meat

Hughmoris posted:


Someone should really link this in the OP...

The Good Parts

Edit: I'm going to leaf through the beginning of it to make sure it's suitable for beginners. I seem to remember it being ok.

Bearnt!
Feb 6, 2004

No onions, no onions

epswing posted:

Set display: none; on the two divs you don't want to display right away.

code:
...
<div id="IDX-searchPage-countyField" class="IDX-searchBox" style="display: none;">
...
<div id="IDX-searchPage-zipCodeField" class="IDX-searchBox" style="display: none;">
...

I love you. Seriously though thank you so much.

bebaloorpabopalo
Nov 23, 2005

I'm not interested in constructive criticism, believe me.
I'm not very familiar with Javascript and only have a bit of experience with PHP but what I want to do simply isn't possible in PHP.

I need a way to update a link every x seconds where a part of the link is a query in an external search engine stored in a string in PHP. For example:

code:
<?php
echo "<a href='http://www.google.com/#q=".$string."'>blah</a>";
?>
$string is the contents of a text file that is updated every 10 seconds. I'm also assuming this won't work because the string won't update unless the PHP script is re-run which would require a page refresh, which I want to avoid. I figure there's a way to store/update a string in Javascript without a page refresh, but I don't know a lick of Javascript.

Thanks in advance for any help/advice you guys can give.

anotherone
Feb 8, 2001
Username taken, please choose another one
include jquery:

code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
give your link an id:
code:
<?php
    echo "<a href='http://www.google.com/#q=".$string."' id='updateLink'>blah</a>";
?>
and then:

code:
<script type="text/javascript">
$(function () {
    setInterval(function () {
        $.get('/fakeurl.php').success(function (data) {
            $('#updateLink').attr('href', data);
        });
    }, 10000);
});
</script>
Change the fake URL I put in there to be the URL to a php script that just echos the URL you want to set the link's href to. It must be on the same domain.

(EDIT: I left out the # in $('#updateLink') - thanks Lumpy.)

anotherone fucked around with this message at 04:17 on Mar 9, 2011

bebaloorpabopalo
Nov 23, 2005

I'm not interested in constructive criticism, believe me.

anotherone posted:

Change the fake URL I put in there to be the URL to a php script that just echos the URL you want to set the link's href to. It must be on the same domain.

Tried this and it didn't work. Stripped it down to the three main elements (inclusion of jquery, the link with PHP string included, and the javascript pointing to a php file that just echos the new link) to eliminate any other factors. Every 10 seconds the page will sort of jutter/freeze as if it's updating, but the link stays the same. The code for my test page is this:

code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<?php
    $string = file_get_contents('string.txt');
    echo "<a href='http://www.google.com/#q=".$string."' id='updateLink'>blah</a>";
?>

<script type="text/javascript">
$(function () {
    setInterval(function () {
        $.get('/url.php').success(function (data) {
            $('updateLink').attr('href', data);
        });
    }, 10000);
});
</script>
url.php is:

code:
<?php 
$string = file_get_contents('string.txt');
echo "http://www.google.com/#q=".$string; 
?>
Again, thanks for the help.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Doody the Clown posted:

Tried this and it didn't work. Stripped it down to the three main elements (inclusion of jquery, the link with PHP string included, and the javascript pointing to a php file that just echos the new link) to eliminate any other factors. Every 10 seconds the page will sort of jutter/freeze as if it's updating, but the link stays the same. The code for my test page is this:

code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<?php
    $string = file_get_contents('string.txt');
    echo "<a href='http://www.google.com/#q=".$string."' id='updateLink'>blah</a>";
?>

<script type="text/javascript">
$(function () {
    setInterval(function () {
        $.get('/url.php').success(function (data) {
            $('updateLink').attr('href', data);
        });
    }, 10000);
});
</script>
url.php is:

code:
<?php 
$string = file_get_contents('string.txt');
echo "http://www.google.com/#q=".$string; 
?>
Again, thanks for the help.

this: $('updateLink').attr('href', data);

needs to be this: $('#updateLink').attr('href', data);

The jQuery selector was wrong. The original was looking for a TAG 'updateLink', the corrected version looks for a tag with an ID of 'updateLink'.

bebaloorpabopalo
Nov 23, 2005

I'm not interested in constructive criticism, believe me.

Lumpy posted:

this: $('updateLink').attr('href', data);

needs to be this: $('#updateLink').attr('href', data);

The jQuery selector was wrong. The original was looking for a TAG 'updateLink', the corrected version looks for a tag with an ID of 'updateLink'.

This works! Much thanks to both of you.

anotherone
Feb 8, 2001
Username taken, please choose another one
Thanks Lumpy, I updated my code.

Doody the Clown posted:

code:
<?php 
$string = file_get_contents('string.txt');
echo "http://www.google.com/#q=".$string; 
?>
Again, thanks for the help.

This is neither here nor there but if all you're doing is echoing a .txt file you can just point the URL to the txt file and change the $('#updateLink').attr('href', data); to $('#updateLink').attr('href', 'http://google.com/#?q=' + data); and save a few PHP cycles.

Flamadiddle
May 9, 2004

Just a quick question about the string.match(regex) function in javascript. I noticed while fixing a couple of functions today that the array returned has the complete string in array[0] and then the matched elements in higher positions. I'm pretty sure I read about that in "The Good Parts" recently, but I've not got the book to hand. Can someone correct my understanding?

code:
var matches = "14/03/2011".match(/^(\d{2})\/(\d{2})\/\d{4}$/);

//matches[0] = "14/03/2011";
//matches[1] = "14";
//matches[2] = "03";
Is this standard behaviour for all uses of .match? I understand that the whole string matches the expression, but I don't want to capture that match... Should I be using a non-capturing group around the whole expression?

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Flamadiddle posted:

Is this standard behaviour for all uses of .match? I understand that the whole string matches the expression, but I don't want to capture that match... Should I be using a non-capturing group around the whole expression?

If you use the global flag on the expression, the match object will only contain matching subsequences. Using the expression /\d{2}(?=\/)/g on your previous example, you only get "14" and "03" back in the match object. All that said, why is it a problem to have the whole string in the match object?

Flamadiddle
May 9, 2004

Thanks for the response. It's not a problem at all, it was just a little unexpected as I thought the returned array would just contain capturing-groups.

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!
I guess this is the most relevant thread.
I'm making something in <canvas> and I have two images. I want one to rotate and the other to stay still. Trouble is I can either make it where they both rotate or neither do.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

The Merkinman posted:

I guess this is the most relevant thread.
I'm making something in <canvas> and I have two images. I want one to rotate and the other to stay still. Trouble is I can either make it where they both rotate or neither do.

Rotate the "still" image opposite the direction of the canvas context rotation

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!

Lumpy posted:

Rotate the "still" image opposite the direction of the canvas context rotation
That's what I can't figure out how to do. Rotate seems to affect ALL or NONE, I can't rotate on a per object basis.

I found a different tutorial and recoded my wheel, but now that one won't work in IE with excanvas :(

KuruMonkey
Jul 23, 2004

The Merkinman posted:

That's what I can't figure out how to do. Rotate seems to affect ALL or NONE, I can't rotate on a per object basis.

I found a different tutorial and recoded my wheel, but now that one won't work in IE with excanvas :(

jsfiddle

if not for the more accurate help, then we can all learn :)

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

The Merkinman posted:

That's what I can't figure out how to do. Rotate seems to affect ALL or NONE, I can't rotate on a per object basis.

I found a different tutorial and recoded my wheel, but now that one won't work in IE with excanvas :(

I'm on my phone all week, so no code, but what you do in essence:

Save context
Rotate and draw "rotated" image
Restore context
Draw "static" image
Refresh context

Here is an article that has some code and I found helpful http://visitmix.com/Articles/Translating-CANVAS-with-HTML5

Randomosity
Sep 21, 2003
My stalker WAS watching me...
Is there a way to set a script to execute after another, or otherwise control the order of execution? I'm trying to integrate a 3rd party widget onto a site. They give us a script tag that inserts its own content into the page when it runs. I want to write my own script to modify some of the elements their script created, but I'm not sure how to create it so it always runs when those elements exist.

I know I could do something like setting a timeout of X seconds, when I assume it will have finished running, but that seems hacky and figure there must be a better way.

VVV No callbacks or other hooks, unfortunately. Kludge time!

Randomosity fucked around with this message at 17:33 on Mar 17, 2011

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Randomosity posted:

Is there a way to set a script to execute after another, or otherwise control the order of execution? I'm trying to integrate a 3rd party widget onto a site. They give us a script tag that inserts its own content into the page when it runs. I want to write my own script to modify some of the elements their script created, but I'm not sure how to create it so it always runs when those elements exist.

I know I could do something like setting a timeout of X seconds, when I assume it will have finished running, but that seems hacky and figure there must be a better way.

If you have access to their source, have their widget or whatever fire a custom event when it's done initializing. Have your code listen for said event.

If not, it's kludge time!

code:
function lol() {
  if (document.getElementById('theirElement')) {
    // do poo poo
  } else {
    setTimeout(lol, 100);
  }
};
setTimeout(lol, 100);

NotShadowStar
Sep 20, 2000

Lumpy posted:

If you have access to their source, have their widget or whatever fire a custom event when it's done initializing. Have your code listen for said event.

If not, it's kludge time!

code:
function lol() {
  if (document.getElementById('theirElement')) {
    // do poo poo
  } else {
    setTimeout(lol, 100);
  }
};
setTimeout(lol, 100);

Kludge or no, I'm having to do that exact pattern a lot in my Flash interaction project. :suicide:

The Merkinman
Apr 22, 2007

I sell only quality merkins. What is a merkin you ask? Why, it's a wig for your genitals!

Lumpy posted:

I'm on my phone all week, so no code, but what you do in essence:

Save context
Rotate and draw "rotated" image
Restore context
Draw "static" image
Refresh context

Here is an article that has some code and I found helpful http://visitmix.com/Articles/Translating-CANVAS-with-HTML5
Yeah I did that and it wouldn't work for some reason.
Coworker found a different demo using it and it works now. Maybe that article you posted will shed some light onto why what I did earlier didn't work.

passionate dongs
May 23, 2001

Snitchin' is Bitchin'
Does anyone have any suggestions as to how approach the smooth animated rescaling of a (large) image?

I've tried jquery with a css3 transforms plugin and the result is slow and jittery. I've tried the same with dividing the image up into a grid of smaller images. I've tried just using css3 transforms without jquery, and while extremely fast in Safari, it's still slow in Chrome and FF. I've also tried doing all the resizing in canvas, but that is slow as well. The size of the image is about 1000x600, so it's really not terribly large.

I know it can be done, as Google Maps rescales map tiles extremely smoothly and quickly before it loads the next set of tiles.


edit: nm

passionate dongs fucked around with this message at 19:58 on Mar 20, 2011

Knackered
Jul 29, 2006

Munkeymon posted:

I wrote this to make it easier to slap a quick canvas element into jsconsole

code:
(function _loader(window){
	if(!window.document.getElementById('thecanvas')){
		var can = document.createElement('canvas');
		can.setAttribute('height', '200');
		can.setAttribute('width', '200');
		can.setAttribute('id', 'thecanvas');
		can.setAttribute('style', 'border: 1px solid black');
		window.document.getElementById('input').parentNode.appendChild(can);
		window.can = can;
		window.ctx = can.getContext("2d");
	}
})(window);
And it works fine in FF 3.6 when I load it using load('http://localhost/addCanvas.js')*, but not in Opera and I can't figure out why. It doesn't even seem to be running _loader. Does anyone see anything wrong that I'm not?

*I tired using my IP, too in case it was a security thing, but no dice.

It's an anonymous function that's executed straight away, so you don't need to give the function a name. Remove the name and it works just fine in Opera.

Hope this isn't too late.

code:
(function (window){
	if(!window.document.getElementById('thecanvas')){
		var can = document.createElement('canvas');
		can.setAttribute('height', '200');
		can.setAttribute('width', '200');
		can.setAttribute('id', 'thecanvas');
		can.setAttribute('style', 'border: 1px solid black');
		window.document.getElementById('input').parentNode.appendChild(can);
		window.can = can;
		window.ctx = can.getContext("2d");
	}
})(window);

Knackered
Jul 29, 2006

Randomosity posted:

Is there a way to set a script to execute after another, or otherwise control the order of execution? I'm trying to integrate a 3rd party widget onto a site. They give us a script tag that inserts its own content into the page when it runs. I want to write my own script to modify some of the elements their script created, but I'm not sure how to create it so it always runs when those elements exist.

I know I could do something like setting a timeout of X seconds, when I assume it will have finished running, but that seems hacky and figure there must be a better way.

VVV No callbacks or other hooks, unfortunately. Kludge time!

You could use Jquery to load and execute the script. When that's done perform your modifications to their HTML.

Replace

code:
<script type="text/javascript" src="path/to/file"></script>
with

code:
<script type="text/javascript">
$(function(){
	$.getScript("path/to/file", function(){
		//put your code here
	});
});
</script>

All Hat
Jul 11, 2008

He that is without int among you, let him first cast a long

I have a function that updates a list of links. Each of the links have a handler bound to them with jQuerys bind. The handler calls a function which I have declared just before, which in turn updates said links:

code:
function changeCurrent(el) {
	if (currentStep.imgURL !== undefined) {
		previousStep = currentStep;
		currentStep = el;
		updateLinks();
		return false;
	} else {
		alert("Choose an image");
	}
}

function updateLinks() {
	divWhereLinksAppear.append($('<a>'+ previousStep.placeName +
		'</a><br />').bind('click', function() {changeCurrent(previousStep);}));
}

//somewhere below these two updateLinks() gets called for the first time, when the document is ready
JSLint complains about updateLinks() being called before it's declared. poo poo works, but I wonder if this is a sign of bad coding practices.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Knackered posted:

It's an anonymous function that's executed straight away, so you don't need to give the function a name. Remove the name and it works just fine in Opera.

Hope this isn't too late.

code:
(function (window){
	if(!window.document.getElementById('thecanvas')){
		var can = document.createElement('canvas');
		can.setAttribute('height', '200');
		can.setAttribute('width', '200');
		can.setAttribute('id', 'thecanvas');
		can.setAttribute('style', 'border: 1px solid black');
		window.document.getElementById('input').parentNode.appendChild(can);
		window.can = can;
		window.ctx = can.getContext("2d");
	}
})(window);

I was going to extend it to delete the old canvas and load a new one, so I wanted the creator to have a name. Then I started messing with it to get it to work and ended up leaving the name on.

Anyway, I forgot to post a follow-up, but it turns out the Opera just won't load it from the local machine over HTTP. Sticking it on my cheapo web host fixed the problem.

Munkeymon fucked around with this message at 17:29 on Mar 22, 2011

geeves
Sep 16, 2004

All Hat posted:

JSLint complains about updateLinks() being called before it's declared. poo poo works, but I wonder if this is a sign of bad coding practices.

I've never gotten this one, but if it's there this is one of those nit-picky things with which I don't agree in JSLint. Functions and declared variables are always hoisted to the top of their scope by the interpreter so they're ready to be used by everything in its scope.

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

I was going to extend it to delete the old canvas and load a new one, so I wanted the creator to have a name. Then I started messing with it to get it to work and ended up leaving the name on.

Anyway, I forgot to post a follow-up, but it turns out the Opera just won't load it from the local machine over HTTP. Sticking it on my cheapo web host fixed the problem.

As an FYI, Chrome will do the same thing.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

geeves posted:

I've never gotten this one, but if it's there this is one of those nit-picky things with which I don't agree in JSLint. Functions and declared variables are always hoisted to the top of their scope by the interpreter so they're ready to be used by everything in its scope.

http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

Except Hoisting does not include the definition of the function (or assignment if it's an expression) if it's declared as a variable:

code:
function poop() {
  alert(f()); // error
  var f = function(){
    return true;
  }
  alert(f()); // would alert true if it got here.
}
If you are engaging in the bad practice of declaring global functions, then yes, the name and declaration will be hoisted, but since you shouldn't be doing that, JSLint is actually providing a helpful warning.

All Hat
Jul 11, 2008

He that is without int among you, let him first cast a long

thank you, geeves. I've read that article before, but this time I understood it.

and thanks to Lumpy, I'll be reading a bit more about globals, then.

geeves
Sep 16, 2004

Lumpy posted:

Except Hoisting does not include the definition of the function (or assignment if it's an expression) if it's declared as a variable:

code:
function poop() {
  alert(f()); // error
  var f = function(){
    return true;
  }
  alert(f()); // would alert true if it got here.
}
If you are engaging in the bad practice of declaring global functions, then yes, the name and declaration will be hoisted, but since you shouldn't be doing that, JSLint is actually providing a helpful warning.

Good catch - I thought that article covered it, it must have been another one or maybe in The Good Parts?.

All Hat
Jul 11, 2008

He that is without int among you, let him first cast a long

no, it's in the article. declarations goes up, assignments do not.

hayden.
Sep 11, 2007

here's a goat on a pig or something
For the love of God someone save me from my insanity. Why is it in my code below that zipNum isn't being treated as a number? It's evaluating a value from an input field, and as I understand it to convert a string to a number you need only multiply times 1 or something similar.

The empty if condition works fine and the else at the end is fine. I just can't do any numerical valuation on zipNum that comes out true.

code:

html:
Zip Code <input type="text" name="zipcode"style="width:85px" /><br />

javascript:
function validateZip(zipcode)
{
	var error = "";
	var zipNum = zipcode * 1;
	
	if (zipcode.value == "")
	{
        zipcode.style.background = 'red';
        error = "No zip entered.<br />";
	} else if (zipNum > 10)
	{
		zipcode.style.background = 'red';
		error ="Invalid zip format<br />";
	}
	else
	{
		zipcode.style.background = 'white';
	}
	
	return error;
}

I'm pretty new to JS so excuse any terrible conventions used

epswing
Nov 4, 2003

Soiled Meat
Use parseInt!

code:
var zipNum = parseInt(zipcode);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

hayden.
Sep 11, 2007

here's a goat on a pig or something
That's also not working out for me. I guess that suggests there's something else wrong with my code?

hayden. fucked around with this message at 03:00 on Mar 23, 2011

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Is validationErrors is defined somewhere?

You know you can use try/catch blocks, right? Wrap that whole thing in a try block and alert the exception's message property:
code:
function validateForm(myForm)
{
  try{
	var reason = "";
	reason += validateEmail(myForm.email);
	reason += validatePhone(myForm.phone);
	reason += valdiateTextOnly(myForm.address, "physical address"); 
	reason += valdiateTextOnly(myForm.state, "state"); 
	reason += valdiateTextOnly(myForm.city, "city"); 
	reason += validateZip(myForm.zipcode);
	reason += valdiateTextOnly(myForm.name, "name"); 
	
	 
    if (reason != "") {
	validationErrors.innerHTML = "Error: <br>" + reason;
      return false;
    }

    return true;
  }catch(ex){
    alert(ex.message)
    return false;//so you don't have to refresh the stupid page
  }
}

Adbot
ADBOT LOVES YOU

hayden.
Sep 11, 2007

here's a goat on a pig or something

Munkeymon posted:

Is validationErrors is defined somewhere?

I figured this out using Firebug about 5 minutes before you posted :) Thanks a ton though! I was a little confused and didn't think I had to use the document.getElementById thing.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply