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
Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.
:doh: I'm going to be banned one day for not using code tags...sorry

Adbot
ADBOT LOVES YOU

Stoph
Mar 19, 2006

Give a hug - save a life.

Lumpy posted:

I could be missing the semantics of your use of "declared" and "defined"... I consider them "defined" but pointing the value undefined which, now that I think of it, is really splitting hairs, but regardless, it's still good to show folks what happens under the hood.

I agree. I didn't mean to confuse anyone and your example is much clearer. I didn't realize that putting functions in horrible, random places was invalid according to the ECMA standard (works fine in Chrome) - I just thought it was a retarded thing to do. Thanks OddObserver.

BizarroAzrael
Apr 6, 2006

"That must weigh heavily on your soul. Let me purge it for you."
Hey JS thread, I've just spent the last few hours trying to pick up game programming in HTML5 and Javascript, making a quick clone of Asteroids. Right now I have the JS spawning and drawing the player ship and some of the larger asteroids, and the asteroids are floating around on their randomly-determined momentum, but I've not been able to get an event listener working to read keyboard input.

Earlier I was calling the JS from the HTML like this:

code:
<body>  
        <canvas id='c' onclick="gameStart();"></canvas>  
        <script src="asteroids.js"></script>  
      </body>  
Turned out things didn't work like I was expecting so this wasn't nessecary, it just meant I would cause a bunch of extra asteroids to spawn if I clicked the canvas more than once. But it made me think that the way to go was:

code:
<body>  
        <canvas id='c' onkeydown="controls();"></canvas>  
        <script src="asteroids.js"></script>  
      </body>  
I thought that the controls function would be called when I pressed a button, but not the case. However, if I switch it to onclick it works. Is there something else I need to do to make this trigger right?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

BizarroAzrael posted:

code:
<body>  
        <canvas id='c' onkeydown="controls();"></canvas>  
        <script src="asteroids.js"></script>  
      </body>  

From a quick googling, it looks like that canvas does not support onkeydown events. Try putting it on <body>.

Peanut and the Gang
Aug 24, 2009

by exmarx
Is there a way in nodejs to get JSON.stringify() to not throw an error when it finds a circular reference? I'm using expressjs, and want to do things like res.write(JSON.stringify(req)), because its infinitely easier to read it in my browser's View Source window than to console.log() it and scroll up and down.

Mindisgone
May 18, 2011

Yeah, well you know...
That's just like, your opinion man.

Mindisgone posted:

code:
<script type="text/javascript">
function setStyle(x, y, z){
if (document.getElementById(x).selectedIndex != 0){
document.getElementById(y).style.visibility="visible";
} else
{ document.getElementById(y).style.visibility="hidden";
	document.getElementById(z).style.visibility="hidden"; }
}
</script>
Whenever a form calls it it's like this:

code:
onChange="setStyle(country.id,states.id,towns.id)"

and I have this in each option so the dropdown always reflects your choice after submitting

code:
<?php if(isset($_POST['country']) && $_POST['country'] == "(value of option)") { echo "selected=\"selected\" ";} ?>
If I submit the form and the page refreshes I lose my visibilty of the next dropdown. Does anyone know how to combat this?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Mindisgone posted:

and I have this in each option so the dropdown always reflects your choice after submitting

code:
<?php if(isset($_POST['country']) && $_POST['country'] == "(value of option)") { echo "selected=\"selected\" ";} ?>
If I submit the form and the page refreshes I lose my visibilty of the next dropdown. Does anyone know how to combat this?

Two options come to mind off the top of my head:
1. Use AJAX to submit so you don't have to refresh.
2. Set a cookie w/ javascrpit on select, re-set selected index on page load

Bonus suggestion:
3. Return the selected indexes you submitted with as part of the refresh

_areaman
Oct 28, 2009

BizarroAzrael posted:

Hey JS thread, I've just spent the last few hours trying to pick up game programming in HTML5 and Javascript, making a quick clone of Asteroids. Right now I have the JS spawning and drawing the player ship and some of the larger asteroids, and the asteroids are floating around on their randomly-determined momentum, but I've not been able to get an event listener working to read keyboard input.

Earlier I was calling the JS from the HTML like this:

code:
<body>  
        <canvas id='c' onclick="gameStart();"></canvas>  
        <script src="asteroids.js"></script>  
      </body>  
Turned out things didn't work like I was expecting so this wasn't nessecary, it just meant I would cause a bunch of extra asteroids to spawn if I clicked the canvas more than once. But it made me think that the way to go was:

code:
<body>  
        <canvas id='c' onkeydown="controls();"></canvas>  
        <script src="asteroids.js"></script>  
      </body>  
I thought that the controls function would be called when I pressed a button, but not the case. However, if I switch it to onclick it works. Is there something else I need to do to make this trigger right?

You should use jQuery to handle key/mouse events, just bind a function to the event.

dizzywhip
Dec 23, 2005

BizarroAzrael posted:

I thought that the controls function would be called when I pressed a button, but not the case. However, if I switch it to onclick it works. Is there something else I need to do to make this trigger right?

There's generally no reason to bind events directly in the HTML like that, but as was mentioned, the problem is that you're binding the event to the canvas. I believe the canvas never actually receives focus, so you can't bind key events to it like that.

Just set up the events in your JavaScript instead. Here's how you do it with jQuery:

code:
$(document).keyDown(function(event) {
  // Do key down stuff here.
});
If you're not using jQuery you can do it like this (there's probably going to be some cross-browser compatibility issues if you do it this way, although maybe not amongst browsers that support canvas):

code:
document.addEventListener("keydown", function(event) {
  // Do key down stuff here.
}, false);
edit: Fixed second example

dizzywhip fucked around with this message at 00:18 on Dec 2, 2011

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Gordon Cole posted:

If you're not using jQuery you can do it like this (there's probably going to be some cross-browser compatibility issues if you do it this way, although maybe not amongst browsers that support canvas):

code:
document.addEventListener("keydown", function(event) {
  // Do key down stuff here.
});

The third argument to addEventListener is required. Pass "false".

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How do I call a userscript function in the Firebug console?

stoops
Jun 11, 2001
i've been tasked to get rid of some javascript popup windows, and make the popup content appear on the main page itself.

the way it works is, there is a form on a main page. when submitted, javascript passes some variables to a cgi page. the cgi page spits
out the data, which in turn, the javascript shows that data on a pop up window.

i'm not familiar with cgi, but looking at the cgi script, it's just alot of print statements spitting out the data. would i need to know cgi to handle this?

i would like the data to appear below the main page, but i'm not sure how to write the javascript so it won't be a pop up.

i hope this makes sense. any help is appreciated. the javascript popup example code is shown below:

code:
   
if (stuff == true) {
        var stuff = URL
        + 'stuff.cgi';
	var win = new Window({className: "spread", title: "TITLE Sections of ", 
                width:700, height:500, parent: document.getElementById('window_area'),
                url: stuff})
	win.show();

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

fletcher posted:

How do I call a userscript function in the Firebug console?

If the function is declared in the global scope, probably just by typing some_function(your, arguments). I'm pretty sure userscripts work basically the same way as any other javascript.

If the userscript has done what many of them do, namely wrap its namespace inside an anonymous function, you're hosed.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
CGI is just a gateway between the web server and the language. Commonly, CGI is used with languages like Perl, so I'm guessing this is a Perl script. But no, you don't have to know or care, as long as the script emits a HTML fragment.

Let's pretend that when you browse to stuff.cgi, you get back:

code:
<div class="container">
  <p>This is some content</p>
  <img style="float: right;" src="this-sure-is-some-content.png">
</div>
So now what you need to do is use AJAX to make an HTTP request, and stuff that somewhere in your document. If you're using a framework like jQuery, it could be done like this:

code:
$.ajax({
  url: 'stuff.cgi',
  type: 'GET'
}).done(function(data) {
  // 'popup' is a CSS class that contains 'position: absolute; width: 700px; height: 500px;'
  var $popup = $('<div>', {'class': 'popup'}).html(data);
  $popup.css({'top': 50, 'left': 50});
});

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Wheany posted:

If the function is declared in the global scope, probably just by typing some_function(your, arguments). I'm pretty sure userscripts work basically the same way as any other javascript.

If the userscript has done what many of them do, namely wrap its namespace inside an anonymous function, you're hosed.

code:
// ==UserScript==
// @name           test
// @namespace      test
// @description    test
// @include        [url]http://forums.somethingawful.com/showthread.php?noseen=0&threadid=3070034&pagenumber=31#pti12[/url]
// ==/UserScript==

alert('hello');

function sayHi() {
	alert('say hi');
}
Reload this thread, I get the hello alert. Then in the Firebug console:

code:
>>> sayHi();
ReferenceError: sayHi is not defined
[Break On This Error] sayHi(); 
edit: this worked
code:
unsafeWindow.sayHi = function() {
    alert('hi');
}

fletcher fucked around with this message at 00:13 on Dec 2, 2011

stoops
Jun 11, 2001

quote:

So now what you need to do is use AJAX to make an HTTP request, and stuff that somewhere in your document. If you're using a framework like jQuery, it could be done like this:

code:
$.ajax({
  url: 'stuff.cgi',
  type: 'GET'
}).done(function(data) {
  // 'popup' is a CSS class that contains 'position: absolute; width: 700px; height: 500px;'
  var $popup = $('<div>', {'class': 'popup'}).html(data);
  $popup.css({'top': 50, 'left': 50});
});

thank you for this. yeah, i think initially they want to do away with this old code and they want me to update it with the latest stuff. i've modified jquery scripts before, but i've never done something from scratch.

thanks again, i'll probably be posting more on the jquery thread, as i'll most likely have lots of questions.

dizzywhip
Dec 23, 2005

Suspicious Dish posted:

The third argument to addEventListener is required. Pass "false".

:downs: Shows how often I use plain JavaScript!

stoops
Jun 11, 2001
i have this javascript that opens and collapses 2 menu buttons

code:

function MenuSelected(divName, listName, anchorName)
{	
	if(document.getElementById(listName).style.display == 'none')
	{
		document.getElementById(divName).className='home_side_menu_button_sel';
		document.getElementById(anchorName).title='Click to collapse.';
		try
		{
			new Effect.SlideDown(listName,{ duration:0.7});
			
		}

		catch(err)
		{
			document.getElementById(listName).style.display = 'block';
			
		}
	}
	else
	{
		document.getElementById(divName).className='home_side_menu_button';
		document.getElementById(anchorName).title='Click to expand.';
		try
		{
			new Effect.SlideUp(listName,{ duration:0.7});
		}
		catch(err)
		{
			document.getElementById(listName).style.display = 'none';
			
			
		}


my problem is that menu1 stays open even when menu2 is open. menu1 only closes when menu1 is clicked again.

what do i have to do, or look for, so i can make menu1 collapse when menu 2 is open, and vice versa.

here is my html code


code:
<div class="home_side_menu_button" id="menu1">
	<a href="javascript:;" id="menu1_a" title="Click to expand."
		onClick="MenuSelected('menu1', 'menu1_table', 'menu1_a');">
		<h4>Menu1</h4>
	</a>
</div>

<div class="menu_list" id="menu1_table" style="display:none;">
	LINK 1
	LINK 2
	LINK 3
</div>



<div class="home_side_menu_button" id="menu2">
	<a href="javascript:;" id="menu2_a" title="Click to expand."
		onClick="MenuSelected('menu2', 'menu2_table', 'menu2_a');">
		<h4>Menu2</h4>
	</a>
</div>

<div class="menu_list" id="menu2_table" style="display:none;">
	LINK 1
	LINK 2
	LINK 3
</div>
any help or a point to the right direction is appreciated. thanks.

stoops fucked around with this message at 21:08 on Dec 2, 2011

Stoph
Mar 19, 2006

Give a hug - save a life.
Well, you did not mention that you are using Prototype with Scriptaculous. That might have made it easier to help you. The thing is, when I use a library like jQuery or Prototype, I try to use it for all my DOM queries, because the syntax is just so much nicer/more maintainable.

In jQuery I would do something like this (I don't know the Prototype syntax):

code:
	var $menuItems = $('#nav li');

	$menuItems.click(function (e) {
		e.preventDefault();

		$menuItems.not(this).slideUp('fast');

		$(this).find('> ul').slideDown('fast');
	});

stoops
Jun 11, 2001

Stoph posted:

Well, you did not mention that you are using Prototype with Scriptaculous. That might have made it easier to help you. The thing is, when I use a library like jQuery or Prototype, I try to use it for all my DOM queries, because the syntax is just so much nicer/more maintainable.

In jQuery I would do something like this (I don't know the Prototype syntax):

code:
	var $menuItems = $('#nav li');

	$menuItems.click(function (e) {
		e.preventDefault();

		$menuItems.not(this).slideUp('fast');

		$(this).find('> ul').slideDown('fast');
	});

sorry about that. i'm still green on prototype, but this helps, thanks.

biochemist
Jun 2, 2005

Who says we don't have backbone?
Hey all, I've been trying to learn my way around javascript, and here's a function I borrowed from a tutorial, then hacked up to make clickable tabs that display different divs appear. It's all working fine, but I'm sure it could be optimized. I swear I'm not in school for this or anything, but could someone grade my work and point out things that I need to work on?

I'm using jQuery and the backgroundColor animation plugin.

code:
$(function() {
	var tabContainers = $('#contentContainer > div');
	tabContainers.hide().filter('#aboutContent').show();
	
	$('#linkColumn ul.navBar div').click(function(){
		tabContainers.hide()
		tabContainers.filter('#'+$(this).attr('id')+'Content').show();
		$('#linkColumn ul.navBar div').removeClass(' selected');
		$('#linkColumn ul.navBar div').not($(this)).animate({
			backgroundColor: '#333',
			width:'300px'
		},100,function(){})
		$(this).animate({
			backgroundColor: '#8bc84a'
		},1,function(){})
		$(this).addClass(' selected');		
		return false;
	});
});
and here's a goofier part, each tab div has it's own class and a mouseover event to trigger them sliding out. Then, it starts looking for a mouseout to move it back to the regular size unless it got clicked. There are five of these, one for each tab div.

code:
function mouseOverAbout()
{
	if ($('#about').hasClass('selected')){
		return false;}
	else{
	$('#about').animate({
	width: '350px',
	backgroundColor: '#888'
	}, 100, function() {
	})};

$('#about').mouseout(function() {
	if ($('#about').hasClass('selected')){
		return false;}
	else{
	$('#about').animate({
	width: '300px',
	backgroundColor: '#333'
	}, 100, function() {
	})};
})}
Like I said, it works fine and looks pretty good on the page (as far as I'm concerned) but seeing how I have almost no JS experience I'm sure there's a cleaner way to code this. Pointers?

Edit: Stoop, looks like we're trying to do something similar. If you switch to jQuery, maybe you can borrow something from me?

biochemist fucked around with this message at 06:03 on Dec 12, 2011

stoops
Jun 11, 2001

biochemist posted:

Edit: Stoop, looks like we're trying to do something similar. If you switch to jQuery, maybe you can borrow something from me?

I appreciate, but I ended up finding another prototype accordion.

I do tend to be in the same boat as you. I always find tutorials, hack them to death, get what I want to work, but then wonder if I could have optimize it better.

I may switch to using Jquery later on as i find way more plugins,etc than prototype, but maybe I'm not looking right?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

biochemist posted:

Hey all, I've been trying to learn my way around javascript, and here's a function I borrowed from a tutorial, then hacked up to make clickable tabs that display different divs appear. It's all working fine, but I'm sure it could be optimized. I swear I'm not in school for this or anything, but could someone grade my work and point out things that I need to work on?

I'm using jQuery and the backgroundColor animation plugin.

If I were you, I would use CSS3 transitions to make the clickable tab effect, and structure your HTML like this:

code:
<span>Tab 1</span>
<div>
Tab 1 content, foo bar
</div>

<span>Tab 2</span>
<div>
Tab 1 content, foo bar baz
</div>
Using code like this should work:

code:
$("span").click(function() {
    $("span").removeClass("selected");
    $("span + div").slideUp();
    $(this).addClass("selected");
    $(this).next().slideDown();
});

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

biochemist posted:

Hey all, I've been trying to learn my way around javascript, and here's a function I borrowed from a tutorial, then hacked up to make clickable tabs that display different divs appear. It's all working fine, but I'm sure it could be optimized. I swear I'm not in school for this or anything, but could someone grade my work and point out things that I need to work on?


A few things:

1. Cache your selectors. I say it 99% of the time anyone posts jQuery. If you are every going to use a selector more than once, store it. For example in this block in your code:

code:
$('#linkColumn ul.navBar div').click(function(){
  tabContainers.hide()
  tabContainers.filter('#'+$(this).attr('id')+'Content').show();
  $('#linkColumn ul.navBar div').removeClass(' selected');
  $('#linkColumn ul.navBar div').not($(this)).animate({
  ...
You are performing a look-up three times. You can get rid of one w/ chaining, but still, store that, especially since you re-look it up every click.

2. I can't tell since you didn't post it, but based on your selectors, your HTML is probably not very semantic / efficient. You are probably writing a lot more code than you need to due to your markup.

3. You are making empty callback functions. Don't do that.

4. Do you have a function for each tab that's like the 'About' one? If so, refactor.

5. You are missing semi-colons at the end of some lines. (this is me channeling jslint and being anal)

6. You are calling animate() on lots of elements when it seems like only the one that would previously be "selected" needs it. This is inefficient.

EDIT:

7. CSS animations are a nifty way of doing this without code, as mentioned, but you lose IE support.

8. Remember that web page animations on UI elements steal time away from people's lives that they will never get back. Ask yourself: are your color / size animations worth taking chunks away from peoples time on earth 300ms at a time?

Lumpy fucked around with this message at 03:25 on Dec 13, 2011

CapnBry
Jul 15, 2002

I got this goin'
Grimey Drawer
Is there a shortcut way to use the value of a variable as an object property name in a JSON expression? The resulting object I want is:
code:
{mykey: "myvalue"}
But the string "mykey" is stored in a variable
code:
var key = "mykey";
var value = "myvalue";

var o = {key: value}; // creates {key: "myvalue"}
var o = {}; o[key] = value; // works
I'd like to use a syntax like the former just for consistency sake. The JSON spec says that a pair is defined as a string(colon)value. A string being defined as (quote)characters(quote) so key is supposed to be "key" if you really want the literal "key" in there! I require pedantic implementations :colbert:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

CapnBry posted:

Is there a shortcut way to use the value of a variable as an object property name in a JSON expression? The resulting object I want is:
code:
{mykey: "myvalue"}
But the string "mykey" is stored in a variable
code:
var key = "mykey";
var value = "myvalue";

var o = {key: value}; // creates {key: "myvalue"}
var o = {}; o[key] = value; // works
I'd like to use a syntax like the former just for consistency sake. The JSON spec says that a pair is defined as a string(colon)value. A string being defined as (quote)characters(quote) so key is supposed to be "key" if you really want the literal "key" in there! I require pedantic implementations :colbert:

No (Python lets you do this, but not JavaScript). The reason that the JSON spec requires quotes around keys is so that they don't clash with JavaScript keywords like "do" and "for" and such. They are optional in JavaScript, and {foo: "bar"} means the same thing as {"foo": "bar"}.

jivemuffin
Jun 23, 2002

Historically significant
I think this might be the place for this...using Google's custom search API, I'm trying to write a script that censors random results. I have absolutely zero clue how to go about doing this. :( Can anyone point me in the right direction?

Google's docs show how to restrict certain sites, which is all well and good, but I want those results to still show up, and have a note about why they are filtered.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

CapnBry posted:

Is there a shortcut way to use the value of a variable as an object property name in a JSON expression? The resulting object I want is:
code:
{mykey: "myvalue"}
But the string "mykey" is stored in a variable
code:
var key = "mykey";
var value = "myvalue";

var o = {key: value}; // creates {key: "myvalue"}
var o = {}; o[key] = value; // works
I'd like to use a syntax like the former just for consistency sake. The JSON spec says that a pair is defined as a string(colon)value. A string being defined as (quote)characters(quote) so key is supposed to be "key" if you really want the literal "key" in there! I require pedantic implementations :colbert:

Make Doug Crockford cry and open a world of awful!!!
code:
var o = eval('{"' + key + '": "' + val + '"}');
: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!
How do I get a textarea to have a limit of 500 words? Anything I've found in my searching either counts characters, not words; or doesn't actually work when I copy/paste the code.

EDIT: Got IT

Found a code that counted 500 words (well spaces really, I don't care about a double space bug). But it then erased to 500 characters for some reason. So I took that code and fixed it.

The Merkinman fucked around with this message at 16:43 on Dec 15, 2011

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Lumpy posted:

Make Doug Crockford cry and open a world of awful!!!
code:
var o = eval('{"' + key + '": "' + val + '"}');
:suicide:

code:
function obj(k, v) {
    var o = {}; o[k] = v; return o;
}

var key = "three";
var o = obj(key, "foo bar baz");

CapnBry
Jul 15, 2002

I got this goin'
Grimey Drawer

Lumpy posted:

Make Doug Crockford cry and open a world of awful!!!
Haha especially because value is a user-supplied value. JavaScript injection ahoy! I don't know why I spent so much time trying to force it to accept my syntax. Thanks guys.

PS I love server-sent events. Go go real time BBQ updates in my browser!

opie
Nov 28, 2000
Check out my TFLC Excuse Log!
How do I get around this error:
Variable 'XMLHttpRequest' has not been declared

This is happening in IE 8 and .NET framework 2.0. All the stuff I've been reading seems to imply that it should just work.

This might be a stupid question but I don't really know anything about javascript or ajax and both our web guys are out this week. The only thing I've gotten to work is ActiveXObject("MSXML2.ServerXMLHTTP"); and they said they don't want to use ActiveX.

ElCondemn
Aug 7, 2005


opie posted:

How do I get around this error:
Variable 'XMLHttpRequest' has not been declared

This is happening in IE 8 and .NET framework 2.0. All the stuff I've been reading seems to imply that it should just work.

This might be a stupid question but I don't really know anything about javascript or ajax and both our web guys are out this week. The only thing I've gotten to work is ActiveXObject("MSXML2.ServerXMLHTTP"); and they said they don't want to use ActiveX.

Check out http://msdn.microsoft.com/en-us/library/ms535874 to understand how this works under IE. I would however suggest using a library like jQuery to do this kind of thing, they do a good job of abstracting out all of the browser specific code.

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with

Grimey Drawer
I'm pretty bad with the Javascripts. I want to a different image to load depending on the URL of the site. I've attempted this:

code:
<html>
<head>
<script type="text/javascript">

if(location.href=="www.mysite.com/index.html")
{
document.getElementById('image').src = "someimage1.jpg";
}
else if (location.href="www.mysite.com")
{
document.getElementById('image').src = "tsomeimage2.jpg";

</script>
</head>
<body>
<img src="blank.jpg" id="image">
</body>
</html>

And it doesn't load anything. I write Javascript pretty much never, so I'm sure it's some simply syntax error, but I've been crawling the Internet for an example of something similiar for the last 20 mintues with nothing to show for it.

Kekekela
Oct 28, 2004

Canine Blues Arooo posted:

I'm pretty bad with the Javascripts. I want to a different image to load depending on the URL of the site. I've attempted this:

code:
<html>
<head>
<script type="text/javascript">

if(location.href=="www.mysite.com/index.html")
{
document.getElementById('image').src = "someimage1.jpg";
}
else if (location.href="www.mysite.com")
{
document.getElementById('image').src = "tsomeimage2.jpg";

</script>
</head>
<body>
<img src="blank.jpg" id="image">
</body>
</html>

And it doesn't load anything. I write Javascript pretty much never, so I'm sure it's some simply syntax error, but I've been crawling the Internet for an example of something similiar for the last 20 mintues with nothing to show for it.
Just off the top of my head you're missing a closing bracket from the else if, and also doing an assignment instead of a comparison there (single = sign instead of double or triple)...this is also something that probably needs to be occurring after the page loads which I'd typically put in a jQuery ready handler, I guess the non-jQuery way is doing page onLoad or something but I don't know if that works in every browser.

I think location.href also returns the http:// prefix which could be causing your comparison to fail.

Ned
May 23, 2002

by Hand Knit
code:
<html>
</head>
<body>
<img src="blank.jpg" id="image">

<head>
<script type="text/javascript">

if(location.href == "www.mysite.com/index.html")
{
document.getElementById('image').src = "someimage1.jpg";
}
else if (location.href == "www.mysite.com")
{
document.getElementById('image').src = "tsomeimage2.jpg";
}
</script>
</body>
</html>

You need to run it after the image id actually exists in the page.

But you shouldn't be doing this with JS

opie
Nov 28, 2000
Check out my TFLC Excuse Log!

ElCondemn posted:

Check out http://msdn.microsoft.com/en-us/library/ms535874 to understand how this works under IE. I would however suggest using a library like jQuery to do this kind of thing, they do a good job of abstracting out all of the browser specific code.
The problem is that all the stuff we use for this crap is server side, and apparently this is a client side function. Trying to inject this one little loving thing in this infrastructure is proving to be a huge pain in the rear end for me.

opie fucked around with this message at 07:35 on Dec 21, 2011

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
What are you trying to do that needs XMLHttpRequest on the server?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Canine Blues Arooo posted:

I'm pretty bad with the Javascripts. I want to a different image to load depending on the URL of the site. I've attempted this:
[snip]
And it doesn't load anything. I write Javascript pretty much never, so I'm sure it's some simply syntax error, but I've been crawling the Internet for an example of something similiar for the last 20 mintues with nothing to show for it.

What are you allowed to do on your server?

If you can add libraries, add one (like jQuery), because that will allow you to do it "the right way" the easiest.

What goes wrong (aside from syntax errors): Well, one thing is that Javascript is executed immediately, so in a structure like this:
code:
<html>
	<head>
		<script></script>
	</head>
	<body>
		<img src="whatever">
	</body>
</html>
When the script inside the head tag is executed, the document body and image do not exist yet.

What you need to do is:
1) Put your image swap code in a function, then
2a)(better) run your function when the DOM has been loaded (event: document.DOMContentLoaded), or
2b)(worse) run your function when the whole document has loaded (event: window.load).

Adbot
ADBOT LOVES YOU

opie
Nov 28, 2000
Check out my TFLC Excuse Log!

Suspicious Dish posted:

What are you trying to do that needs XMLHttpRequest on the server?
Basically all the code I'm allowed to touch, like all the display code, is server side. What I need to do is open a third-party URL (which is on the same server as our web stuff), parse the xml to get a count of certain nodes, and display the sum. For some reason displaying that number is the tricky part, because none of the client stuff I've tried adding will work. There's a lot of infrastructure involved. I was able to ask the guy who originally wrote it about it, but he seemed to hint that it would be really easy to inject client code in. Either he doesn't understand what I'm trying to do, or I'm just retarded.

The latter is certainly possible. I have done almost zero web programming in my life, especially in the last 5 years. I just happened to get this task because it was part of another thing in the product I generally work on.

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