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 have this code in a frame (the kind with a frameset and everything):

code:
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript">
pageTracker = false;
this.document.onload = function(){
pageTracker = _gat._getTracker("blah");
pageTracker.track = pageTracker._trackPageview;
trackURL("http://"+this.top.location.hostname+this.top.location.pathname);
alert('wtf');
};
</script>
The alert never goes off. I also tried document.onload and $(document).ready and $(document).load. .ready goes off before urchin.js has been parsed and .load also never happens. Can anyone see what I'm doing wrong here? I mean aside from working on a site with frames because that I can't do anything about unless I quit my job.

edit: unfucking mixed newlines

Munkeymon fucked around with this message at 21:41 on Mar 30, 2010

Adbot
ADBOT LOVES YOU

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
Try $(window).load(...) instead.

Munkeymon
Aug 14, 2003

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



Nigglypuff posted:

Try $(window).load(...) instead.

That does work and .ready() probably does as well.

I'm just an idiot for copying and pasting an old version of Google's URL. _gat didn't exist when I was calling it because urchin.js doesn't define a _gat object - ga.js defines a _gat object.

Munkeymon fucked around with this message at 18:06 on Mar 31, 2010

noz
May 21, 2003

Has anyone else had problems getting a (document).click event to work with Chrome? This works perfectly in FF but it doesn't seem to fire the event at all in Chrome... Google isn't too helpful.

edit: I should add that this is using jQuery.

Let's assume I'm just doing this.

code:
$(document).click( 
function () {
 
 alert("ciao");
  }
 );
further edit: This seems to work sometimes and not others... Really odd.

noz fucked around with this message at 11:10 on Apr 1, 2010

HFX
Nov 29, 2004

noz posted:

Has anyone else had problems getting a (document).click event to work with Chrome? This works perfectly in FF but it doesn't seem to fire the event at all in Chrome... Google isn't too helpful.

edit: I should add that this is using jQuery.

Let's assume I'm just doing this.

code:
$(document).click( 
function () {
 
 alert("ciao");
  }
 );
further edit: This seems to work sometimes and not others... Really odd.

Sounds like a focus issue or something else is capturing the event and not letting it bubble.

noz
May 21, 2003

Chrome's excellent dev tools (seriously, I'm not being sarcastic here) let me find the problem pretty fast.

Some judicious use of jQuery.noConflict() resolved it.

Thanks for the reply!

HFX
Nov 29, 2004

noz posted:

Chrome's excellent dev tools (seriously, I'm not being sarcastic here) let me find the problem pretty fast.

Some judicious use of jQuery.noConflict() resolved it.

Thanks for the reply!

I agree. I wish I had them on the platform I'm working on right now. Even Mozilla's would be nice. Doing everything with debug statements to a log file is a pain.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I have a long string that is a mixture of digits and the uppercase letters A through J. I want to replace every occurence of 'A' with '0|', every occurence of 'B' with '1|', ..., and every occurence of 'J' with '9|'. I looked for how to do this on the internet, but the answers I found all said that the only way to replace every occurence of a substring was to use regular expressions and supply the 'g' modifier. Is that really correct? Do I really have to do
code:
mystring = mystring.replace(/A/g,'0|');
mystring = mystring.replace(/B/g,'1|');
...
mystring = mystring.replace(/J/g,'9|');
or is there a smarter way?

epswing
Nov 4, 2003

Soiled Meat

Hammerite posted:

Do I really have to do
code:
mystring = mystring.replace(/A/g,'0|');
mystring = mystring.replace(/B/g,'1|');
...
mystring = mystring.replace(/J/g,'9|');
or is there a smarter way?

If the order of replaces doesn't matter, you could put the mappings into an object and iterate over the properties of the object.

code:
var mystring = "blahblahblah";

var map = {
  'A': '0|',
  'B': '1|',
  ...
  'J': '9|'
}

for (var i in map) {
  if (map.hasOwnProperty(i)) { // do this whenever you use "for X in Y"
    mystring = mystring.replace(i, map[i], 'g');
  }
}
The final param ('g') of the replace method might not be cross-browser, test it with the browsers you want to support.

Also, looks like you can use another loop to generate the map.

Peanut and the Gang
Aug 24, 2009

by exmarx
You can also pass a function as the second argument:
code:
alert('blAhBlahblah'.replace(/[A-J]/g,function(a){return ""+(a.charCodeAt(0)-65)+"|"}));

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Thanks both of you. I've used barbarianbob's solution, since the cross-browser usability is an advantage. I'm glad there's a one-line solution, it's nice to be able to just "drop it in".

Grumpicat
May 27, 2005
Mood: Angsty
Hi I'm trying to add a .current class to the div#sidebar li that has text inside that matches some text that identifies each page (uniqueid).

The actual site is on wordpress which generates the <li>'s and changes the page identifying text for me.
Also I've never written a javascript thing like this and don't really know what I'm doing.

Here's what I have on my test page:
code:
<html>
<head>
<style type="text/css">
.current {color: red;}
</style>
</head>
<body>
<span class="current">2010 should look like this</span><br />
Unique ID: <span id="uniqueid">2010</span>

<div id="sidebar">
<li>2008</li>
<li>2009</li>
<li>2010</li>
</div>

<script type="text/javascript">
var uniqueId = document.getElementById('uniqueid').innerHTML;
alert('UniqueID is ' + uniqueId); //alerts 2010
var spanArray = document.getElementById('sidebar').getElementsByTagName('li');
alert('spanArray[2] is ' + spanArray[2].innerHTML); //alerts 2010
alert('spanArray.length is ' + spanArray.length); //alerts 3
var i = 0;
for (i = 0 ; i < spanArray.length ; i++);
{
alert('for loop started..'); //alerts for start
	if (uniqueId == spanArray[i].innerHTML)
	{
	alert('it worked!');  //all alerts work except this one
	spanArray[i].setAttribute("class", "current"); //duno if this works
	}
}
</script>
</body>
</html>
everything seems to go along fine until I try to satisfy the if statement. Then nothing works!!

Where did I go wrong?

edit: ok someone I know wrote this which works:
code:
var uniqueId = document.getElementById('uniqueid').innerHTML;
var spanArray = document.getElementById("sidebar").getElementsByTagName("li"); 
for ( var i=0, len=spanArray.length; i<len; ++i ){
 if (spanArray[i].innerHTML==uniqueId){
document.getElementById("sidebar").getElementsByTagName("li")[i].setAttribute("class", "current");
}
}
He said it could be cleaner or something but I'm so glad that it works!

last edit: The problem appears to have been the semicolon at the end of the 'for' line. This is going to be so awesome on the wordpress site!

Grumpicat fucked around with this message at 22:08 on Apr 3, 2010

Haystack
Jan 23, 2005





Grumpicat posted:

Hi I'm trying to add a .current class to the div#sidebar li that has text inside that matches some text that identifies each page (uniqueid).

....

Where did I go wrong?


After taking a quick look, two things popped out at me.

First, get rid of the semicolon from after:
code:
for (i = 0 ; i < spanArray.length ; i++);
Second, your spanArray[i].innerHTML code is returning strings like:
code:
"\n         2010        \n"
Which is probably causing your problems.

Third, as a fellow Javascript newbie, I really, really recommend using the jQuery framework and a good debugger like Firebug.

Grumpicat
May 27, 2005
Mood: Angsty

Haystack posted:

things

The problem was indeed the semicolon at the end of the 'for' line. So you were right!

I did try to use jquery but my image slideshow totally broke when I linked to the jquery.js. Kinda weird.

Also thanks for the tip about firebug.

edit: wow im editing like crazy here. The setAttribute I made works I think so maybe the semicolon was the only problem.

Grumpicat fucked around with this message at 22:08 on Apr 3, 2010

Ned
May 23, 2002

by Hand Knit
How did you link to jQuery?

use wp_enqueue_script('jquery'); and you should be good. It might even be included if you use a bunch of plugins. Just remember that it gets loaded with the no conflict stuff there.

Grumpicat
May 27, 2005
Mood: Angsty

Ned posted:

How did you link to jQuery?

use wp_enqueue_script('jquery'); and you should be good. It might even be included if you use a bunch of plugins. Just remember that it gets loaded with the no conflict stuff there.

I put
code:
<?php wp_enqueue_script('jquery'); ?>
into the header but I don't think it's doing anything..

code:
<script type="text/javascript">
$(document).ready(function() {
   alert('hi');
});
</script>
doesn't do anything but
code:
<script type="text/javascript">
   alert('hi');
</script>
works fine

I'm not too worried about jQuery tho I'm almost done with this site now.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I have some variables that are being treated as undefined, but I don't understand why.
I have a JS file included that looks like this
code:
$(document).ready(function() {
	$("#tabs").tabs();

	var image = 1;
});
and then come html with events

code:
<a href="#" onclick="
	image = image + 1;
	$('#demos').attr('src', 'image-' + image + '.png');
">next slide</a>
but when I use it, it says that 'image' is undefined. Am I missing some scoping issue? Should I just bind all those buttons in my document.ready? The tabs from the first code sample get initialized just fine.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

rt4 posted:

I have some variables that are being treated as undefined, but I don't understand why.
I have a JS file included that looks like this
code:
$(document).ready(function() {
	$("#tabs").tabs();

	var image = 1;
});
and then come html with events

code:
<a href="#" onclick="
	image = image + 1;
	$('#demos').attr('src', 'image-' + image + '.png');
">next slide</a>
but when I use it, it says that 'image' is undefined. Am I missing some scoping issue? Should I just bind all those buttons in my document.ready? The tabs from the first code sample get initialized just fine.

Your image var is scoped to the anonymous function. You probably want to do something like this:

code:
jQuery(document).ready( function()
{
  var image = 1;
  jQuery('a.someNewClass').click( function()
  {
     image++;
     jQuery('#demos').attr('src', 'image-' + image + '.png' );
    // test with
    // alert( image );
  }
}

// then your HTML looks like:
<a href="#" class="someNewClass">baldfa</a>
the anon. click hander function will have access to image because it's in it's context ( because it's inside it. )

Lumpy fucked around with this message at 15:16 on Apr 4, 2010

spiritual bypass
Feb 19, 2008

Grimey Drawer
Thanks, Lumpy. That's the explanation I was looking for.

I hadn't done any (serious) JS in a couple months and somehow had the idea that everything was a global.

Ned
May 23, 2002

by Hand Knit

Grumpicat posted:

I put
code:
<?php wp_enqueue_script('jquery'); ?>
into the header but I don't think it's doing anything..

Write your code like this when you include it that way.

code:
<script type="text/javascript">
jQuery(function($) {
   alert('hi');
});
</script>

Grumpicat
May 27, 2005
Mood: Angsty

Ned posted:

Write your code like this when you include it that way.

code:
<script type="text/javascript">
jQuery(function($) {
   alert('hi');
});
</script>

Still not getting anything :/ Does it make a difference that the site isn't hosted on wordpress?

Munkeymon
Aug 14, 2003

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



I'd like to replace this junk:
code:
function getFlexApp(appName){
	if(navigator.appName.indexOf ("Microsoft") !=-1){
		return window[appName];
	}else{
		return document[appName];
	}
}
with $(appName) using Prototype, but the element returned by prototype doesn't seem to expose the JavaScript functions we use to communicate with the Flash object (at least in Firefox). I'm just messing with prototype for the first time today, but I was under the impression Prototype just added helpers to objects without wrapping them like jQuery does. Could Prototype's interference cause the element to drop function definitions?

Supervillin
Feb 6, 2005

Pillbug

Munkeymon posted:

I'd like to replace this junk:
code:
function getFlexApp(appName){
	if(navigator.appName.indexOf ("Microsoft") !=-1){
		return window[appName];
	}else{
		return document[appName];
	}
}
with $(appName) using Prototype, but the element returned by prototype doesn't seem to expose the JavaScript functions we use to communicate with the Flash object (at least in Firefox). I'm just messing with prototype for the first time today, but I was under the impression Prototype just added helpers to objects without wrapping them like jQuery does. Could Prototype's interference cause the element to drop function definitions?

Pretty sure Prototype will treat that argument as an ID, so if you try $('whatever') it returns document.getElementById('whatever'), not window.whatever or document.whatever. So it's probably returning null.

I don't use Prototype so could be wrong, but that's what their docs say.

Edit: vvv Are you sure they're actually returning some element? Their docs explicitly state "nonexistent IDs will yield null". Remember that typeof null == 'object', so you'll have to examine it to see if it's really returning something. If it does return null you could take advantage of JavaScript's short circuiting operators:
code:
var myElement = $(x) || window[x] || document[x];

Supervillin fucked around with this message at 16:20 on Apr 6, 2010

Munkeymon
Aug 14, 2003

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



Supervillin posted:

Pretty sure Prototype will treat that argument as an ID, so if you try $('whatever') it returns document.getElementById('whatever'), not window.whatever or document.whatever. So it's probably returning null.

I don't use Prototype so could be wrong, but that's what their docs say.

That's the impression I got, too, but getElementById does return null while the dollar function actually returns an element.

Edit: maybe the Prototype $() has to return something other than null since null wouldn't chain. Anyway, it's not a huge deal - just one of many ugly things.

Munkeymon fucked around with this message at 15:03 on Apr 6, 2010

Munkeymon
Aug 14, 2003

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



Is there a more reliable way of finding the viewable pixel real estate than Prototype's viewport methods? I'm trying to make images shrink to fit the viewport but after a resize, the methods report the document dimensions instead of the dimensions of the window. Since HTML flows down like it's going out of style, I end up with wacky numbers for viewport height (ie bigger than my monitor) and pictures that flow off the screen given otherwise working resize code. This behavior doesn't seem to be entirely consistent since it was working fine at the end of last week in my tests and this morning the same tests are failing.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Munkeymon posted:

Is there a more reliable way of finding the viewable pixel real estate than Prototype's viewport methods? I'm trying to make images shrink to fit the viewport but after a resize, the methods report the document dimensions instead of the dimensions of the window. Since HTML flows down like it's going out of style, I end up with wacky numbers for viewport height (ie bigger than my monitor) and pictures that flow off the screen given otherwise working resize code. This behavior doesn't seem to be entirely consistent since it was working fine at the end of last week in my tests and this morning the same tests are failing.

jQuery(window).height();
jQuery(window).wdth();
:v:

Munkeymon
Aug 14, 2003

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



Lumpy posted:

jQuery(window).height();
jQuery(window).wdth();
:v:

I suppose reverse engineering that would be easier than trying to get jQuery to play nice with Prototype :\

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Munkeymon posted:

I suppose reverse engineering that would be easier than trying to get jQuery to play nice with Prototype :\

Probably not!

http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Munkeymon
Aug 14, 2003

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




Oh nice - of course the test server just took a poo poo so I can't do anything with it but, hey, at least now I know.

smug forum asshole
Jan 15, 2005
I posted this in the jQuery thread, but it hasn't seen any action in the last few days. Since it's related, I thought I might be able to post it here and get some useful feedback :hehe:

Using jQuery, I produced a long block of animations nested inside of each other with callbacks. It looks kind of ridiculous and it's already pretty terrible to make changes to it. Is there a more elegant way to write this?
code:
$(document).ready(function () {

	$('.bar').css({ width: '0%' }).delay(600);

	$('.bar h1').css({ opacity: 0 });
	
	$('#bar-1').animate({ width: '90%' }, 1200, 'easeOutBack', function (){
		$('#bar-1 h1').animate({ opacity: 1 }, 200, function () {
			$('#bar-2').animate({ width: '80%' }, 800, 'easeOutBack', function () {
				$('#bar-2 h1').animate({ opacity: 1 }, 200, function() {
					$('#bar-3').animate({ width: '70%' }, 500, 'easeOutBack', function () {
						$('#bar-3 h1').animate({ opacity: 1 }, 200, function() {
							$('#bar-4').animate({ width: '60%' }, 1200, 'easeOutBack', function () {
								$('#bar-4 h1').animate({ opacity: 1}, 200);
							});
						});
					});
				});
			});
		});
	});
	
});

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

smug forum rear end in a top hat posted:

jQuery

If you just want to get rid of ugly nesting, I would stick each callback in a local variable like so:
code:
$(document).ready(function () {
    $('.bar').css({ width: '0%' }).delay(600);
    $('.bar h1').css({ opacity: 0 });
    var step7 = function() { $('#bar-4 h1').animate({ opacity: 1}, 200); }
    var step6 = function() { $('#bar-4').animate({ width: '60%' }, 1200, 'easeOutBack', step7); }
    var step5 = function() { $('#bar-3 h1').animate({ opacity: 1 }, 200, step6); }
    var step4 = function() { $('#bar-3').animate({ width: '70%' }, 500, 'easeOutBack', step5); }
    var step3 = function() { $('#bar-2 h1').animate({ opacity: 1 }, 200, step4); }
    var step2 = function() { $('#bar-2').animate({ width: '80%' }, 800, 'easeOutBack', step3); }
    var step1 = function (){ $('#bar-1 h1').animate({ opacity: 1 }, 200, step2); }
    $('#bar-1').animate({ width: '90%' }, 1200, 'easeOutBack', step1);
});

Sergeant Rock
Apr 28, 2002

"... call the expert at kissing and stuff..."
Couldn't you do something there with recursion, sending in different params each time?

smug forum asshole
Jan 15, 2005
someone actually posted a stellar reply to the post in the jquery thread. i almost wish i hadn't cross posted, but both threads seemed pretty dead at the time

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Yeah that solution is a lot better than mine. :saddowns:

thepedestrian
Dec 13, 2004
hey lady, you call him dr. jones!
I'm trying to write a function that when a user selects some text on a web page and then clicks a button, that text will be replaced with different text that is the result of another function.

I've gotten to the point where I can grab the text that is selected when the button is clicked and perform the transformation on it, but I'm stuck on how I can then replace the selected text with the new text. Most of the examples I've found are done on text inside a <textarea>, but I want to do it on regular text on the page. Any thoughts?

Sergeant Rock
Apr 28, 2002

"... call the expert at kissing and stuff..."
You can change the innerHTML of the parent object, or do complex stuff with document.createTextNode...

smug forum asshole
Jan 15, 2005
edit: i obviously didn't read the question correctly

smug forum asshole fucked around with this message at 18:27 on Apr 25, 2010

thepedestrian
Dec 13, 2004
hey lady, you call him dr. jones!

Sergeant Rock posted:

You can change the innerHTML of the parent object, or do complex stuff with document.createTextNode...

I guess more specifically the problem I'm having is how to reference the position of the selected text in order to replace it. The parent object could conceivably contain a whole lot of text and I want to replace single words or phrases, and doing a string replace on the word or phrase won't work since there could be multiple occurrences within the parent object and I only want to modify the selected one.

spiritual bypass
Feb 19, 2008

Grimey Drawer
I think NYT's website does something like that for word definitions when you highlight text. Maybe you could take a peek over there and see what's going on.

Adbot
ADBOT LOVES YOU

hasegawa
Dec 30, 2008

Wedge Regret
Alright, I'm trying to do a simple form validation for a drop box. I want it to give a "Hey choose something stupid" if the value is still "Select One" when the user clicks submit. With the current code, it allows the user to go to the next page regardless of what they choose in the dropdown box. I've tried several different javascript validators, but none of them seem to work with this.

code:
<SCRIPT LANGUAGE="JavaScript">

function validateForm(){
if(document.term.selectedIndex=='0')
{
alert("Please select an Item.");
document.term.focus();
return false;
}
return true;
}

</SCRIPT>
and then further down...
code:
 <form id="termForm" method="get" action="QueryOptions.php" onSubmit="return validateForm()">
					
						
<?php

		
	global $one;

	$one = mysql_connect ("localhost","name","password");
	if(!$one){die("Could not connect to MySQL");}
	mysql_select_db("database", $one);
	
	$TermQuery = mysql_query("SELECT sourcedid,title FROM class_terms ORDER BY sourcedid DESC");
	
	echo "<select name=\"term\"><option value=''>Select one</option>";
	
	//while loop
	//declares a temp variable that then pulls up the SQL statement in the termquery variable
	while($Temp=mysql_fetch_array($TermQuery, MYSQL_ASSOC)){//Array or records stored in $Temp
		echo "<option value=$Temp[sourced_id]>$Temp[title]</option>";
	/* Option values are added by looping through the array */
	}
	
	

?>

<input type="Submit" value="Submit">

</form>
I'm not sure why it isn't working, is it something related to using php ECHO statements instead of regular html <select><option> to create the dropdown list?

hasegawa fucked around with this message at 22:22 on Apr 25, 2010

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