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
Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL

Snodar posted:

That leads to a second question, is there any god-damned reason to be using offsetLeft/offsetTop/offsetParent when getBoundingClientRect does the same thing without a loop? I only started doing it because I had a page in Gecko flat-out fail when I tried the offset method, and AFAICT it always produces the correct result.

getBoundingClientRect hasn't always been available in Gecko, iirc. But as long as it's there, you should definitely use it.

Adbot
ADBOT LOVES YOU

The Wizard of Oz
Feb 7, 2004

Nigglypuff posted:

getBoundingClientRect hasn't always been available in Gecko, iirc. But as long as it's there, you should definitely use it.

You're right, it's Firefox 3, and a port of one of IE's handful of good ideas. So no WebKit. I did find a page which covers all the edge conditions HERE.

argz
May 20, 2005

The hand says it all.
I'm trying to write a greasemonkey script to replace the tiny rear end thumbnails on gnome-look.org (seriously 80px by 50px? This is 1990, jesus christ). Only problem, is there is no consistency in the thumbnail to fullsize image extensions. A png thumb can be a jpg fullsize, a png fullsize or quite possibly a gif and any other combination like this.

The solution here is to do an image check. Unfortunately, I'm a javascript idiot and I've gotten stuck on this problem while trying to solve it different ways. The one I _thought_ would be successful was most certainly not, that was using a global var to set and test true/false.

Can someone please help me out and liberate me from this ancient website?

code:
// ==UserScript==
// @name           gnome-look.org big pic
// @namespace      buttface
// @version        1.0.0
// @description    Replace large images in posts to thumbnailed version
// @include        [url]http://gnome-look.org*[/url]
// @include        [url]http://*.gnome-look.org*[/url]
// ==/UserScript==

// Well this global didn't work
// var exists=false;

function $xu(p, c) {
	var i, r = [], x = document.evaluate(p, c || document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
	while(i=x.iterateNext()) r.push(i);
	return r;
}
$xu('//IMG[contains(@src, "content-m1")]').forEach(function(img) {

		var src = img.src.replace(/\/content-m1\/m/i, '/content-pre1/');

		//testImage(src);
		//if (exists==false) {
		if (testImage(src)==false) {
			alert(src);
			src = src.replace(/.png/i, '.jpg');
		}
		
		if (testImage(src)==false) {
			alert(src);
			src = src.replace(/.jpg/i, '.gif');
		}
		
		if (testImage(src)==false) {
			alert(src);
			src = src.replace(/.gif/i, '.png');
		}
		
		img.src = src;
		
		img.removeAttribute('width');
		img.removeAttribute('height');

});


function testImage(URL) {
    var tester=new Image();

	tester.onError=isBad;
	tester.onLoad=isGood;
	
	return exists;
    /*if (tester.onError) {
		return false;
	} else {
		return true;
	}*/
}

function isGood() {
	//exists = true;
	return false;
}

function isBad() {
    //alert('That image does no exist!');
	//exists = false;
	return false;
}

sonic bed head
Dec 18, 2003

this is naturual, baby!

argz posted:


The solution here is to do an image check. Unfortunately, I'm a javascript idiot and I've gotten stuck on this problem while trying to solve it different ways. The one I _thought_ would be successful was most certainly not, that was using a global var to set and test true/false.


Sadly I'm pretty sure that javascript in a browser does not give you access to MIME types of the Image() object. Maybe you can make an XHR get the image and check the response headers, but I think that might be a lot of work for this problem.

argz
May 20, 2005

The hand says it all.
Well the actual check whether the image exists or not works, no XHR necessary there. The problem I'm having is looping it.

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
Forgive me argz, I ended up doing a wholesale rewrite of your script. It was fun, but possibly not that helpful to you for figuring out the original issue.

It works though! And it's kind of novel, if a little awkward, to write in continuation-passing style.

code:
// ==UserScript==
// @name           gnome-look.org thumbnail enlarger
// @author         Nigglypuff
// @namespace      meta.ironi.st
// @include        http://gnome-look.org*
// @include        http://*.gnome-look.org*
// ==/UserScript==

var thumbnailPath = '/CONTENT/content-m1/m',
	fullSizePath = '/CONTENT/content-pre1/';

function fixImageExtension(url, callback) {
	// remove extension from original url
	url = url.slice(0, -3);
	
	var extensions = ['jpg', 'gif', 'png'];
	
	function tryNextExtension(){
		var extension = extensions.shift();
		
		if (extension) {
			testImageExists(url + extension, function (exists) {
				if (exists) {
					callback(url + extension);
				} else {
					tryNextExtension();
				}
			});
		} else {
			callback(null);
		}
	};
	
	tryNextExtension();
	
};

function testImageExists(url, callback) {
	var testImg = document.createElement('img');
	
	testImg.addEventListener('load', function () {
		callback(true);
	}, false);
	
	testImg.addEventListener('error', function () {
		callback(false);
	}, false);
	
	testImg.src = url;
};

[].forEach.call(document.images, function(img) {
	var thumbnailName = img.src.split(thumbnailPath)[1];
	
	if (thumbnailName) {
		img.style.maxWidth = '300px';
		fixImageExtension(fullSizePath + thumbnailName, function(fixedUrl) {
			if (fixedUrl) img.src = fixedUrl;
		});
	}
});

Nigglypuff fucked around with this message at 08:24 on Apr 20, 2009

argz
May 20, 2005

The hand says it all.
Well, this looks like the better solution. I appreciate the rewrite and I will learn from it. It works great in Opera, however, my main browser, Firefox doesn't seem to make it to the following function in the second parameter at line 18:

code:
fixImageExtension(fullSizePath + thumbnailName, function(fixedUrl) {
        alert("yo, I'm firefox, a big jerk that doesn't like to visit this place");
	if (fixedUrl) img.src = fixedUrl;
});

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
Oops, good point — like a goofball I only tested it in Chrome. Have updated the code slightly in the previous post, just moving the function definitions up before the code that uses them. It seems to be working for me in Firefox now.

argz
May 20, 2005

The hand says it all.
Still not working for me, receiving the following error in console:

Firefox 3.0.8 on Linux

code:
Error: Component is not available
Source File: file:///home/argz/.mozilla/firefox/wdkx9mw3.default/gm_scripts/gnome-lookorg_thumbnail_/gnome-lookorg_thumbnail_.user.js
Line: 41
:doh:

Nigglypuff
Nov 9, 2006


BUY ME BONESTORM
OR
GO TO HELL
Third time's a charm. Turns out that in firefox, userscripts can't add event handlers by assigning element.onload = handler. Instead, you have to do element.addEventListener('event', handler, false), or else an error is thrown. Curious. Maybe the old-fashioned event handler assignment relies on some kind of XPCOM magic that doesn't exist in the greasemonkey sandbox.

argz
May 20, 2005

The hand says it all.
Thanks NigglyPuff, you're my hero! I'm going to browse me some themes :snoop:


By the way, https://www.kde-look.org runs on the same outdated software if you'd like to get double points on userscripts.org or add them to the top of this one like I did.


Thanks again :D

Blackout
Jun 29, 2005

I am a deathdealer.
Hey guys, quick question. I'm trying to write a very simple piece of javascript that does two things. First, it will either show or hide an HTML div with the first id I specify. Second, it will change the text of the div with the second id specified. It should toggle these things, so if the div is shown, it will be hidden and vice versa. Same thing with the text (switches between 'Show...' and 'Hide').

Thing is, I'm doing this through an xsl stylesheet. I've got a separate javascript file that the stylesheet references. I've used my javascript functions elsewhere in the stylesheet and they work fine, but in this instance, I'm using xml attributes as ids for the divs, and I'm getting weird results. In IE, the text will toggle just fine, but the div won't disappear/reappear. In Firefox, the show/hide works but the text will only toggle once.

Here is the java script:

code:
function togglePage(objID) {
if (!document.getElementById) return;
var ob = document.getElementById(objID).style;
ob.display = (ob.display == 'none')?'block': 'none';
}

function togglePageAndText(objID, objID2) {
togglePage(objID);
document.getElementById(objID2).innerHTML = (document.getElementById(objID2).innerHTML == 'Show...')?'Hide' : 'Show...';
}
And here is the xsl:

code:
<div id="{@FunctionalArea}" onclick="togglePageAndText('{@FunctionalArea}_testCases', '{@FunctionalArea}')">Show...</div>
<div id="{@FunctionalArea}_testCases">
    <xsl:call-template name="DetailTestCases"/>
</div>
Any ideas?

Thanks!

MonkeyMaker
May 22, 2006

What's your poison, sir?
OK, I have a JSON object with two sub-objects. How do I reference a sub-object by name, not index?

Here's the JSON:
code:
{"menus":
	[
		{"buckets":
			[
				{"name":"item name", "price":"9.99", "description":"item description"},
				{"name":"item name", "price":"9.99", "description":"item description", "subs":
					[
						{"name":"item name", "price":"9.99"}
					]
				},
				{"name":"item name", "price":"9.99", "description":"item description"}
			]
		},
		{"baskets":
			[
				{"name":"item name", "price":"9.99", "description":"item description2"},
				{"name":"item name", "price":"9.99", "description":"item description2", "subs":
					[
						{"name":"item name", "price":"9.99"}
					]
				},
				{"name":"item name", "price":"9.99", "description":"item description2"}
			]
		}
	]
}
which validates as...valid...on jsonlint.com. I can access ['menus'] or ['menus'][0], but trying to get ['menus']['buckets'] fails. I have to be able to do this by name since it'll be client-updated as plain text.

No Safe Word
Feb 26, 2005

MonkeyMaker posted:

OK, I have a JSON object with two sub-objects. How do I reference a sub-object by name, not index?

Here's the JSON:
code:
{"menus":
	[
		{"buckets":
			[
				{"name":"item name", "price":"9.99", "description":"item description"},
				{"name":"item name", "price":"9.99", "description":"item description", "subs":
					[
						{"name":"item name", "price":"9.99"}
					]
				},
				{"name":"item name", "price":"9.99", "description":"item description"}
			]
		},
		{"baskets":
			[
				{"name":"item name", "price":"9.99", "description":"item description2"},
				{"name":"item name", "price":"9.99", "description":"item description2", "subs":
					[
						{"name":"item name", "price":"9.99"}
					]
				},
				{"name":"item name", "price":"9.99", "description":"item description2"}
			]
		}
	]
}
which validates as...valid...on jsonlint.com. I can access ['menus'] or ['menus'][0], but trying to get ['menus']['buckets'] fails. I have to be able to do this by name since it'll be client-updated as plain text.
But what you have is a one-item mapping of "menus" to a list of two other one-item mappings with keys of "buckets" and "baskets".

You want something like:
code:
{"menus":
   {"buckets":
      [ ... stuff ... ],
    "baskets":
      [ ... stuff ... ]
    }
}
The first set of brackets means you have a list of things, and you can only access stuff by index in a list.

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

MonkeyMaker posted:

OK, I have a JSON object with two sub-objects. How do I reference a sub-object by name, not index?

Here's the JSON:
...snip...

which validates as...valid...on jsonlint.com. I can access ['menus'] or ['menus'][0], but trying to get ['menus']['buckets'] fails. I have to be able to do this by name since it'll be client-updated as plain text.

Arrays (using the []) notation, and objects (using {}) are different. Objects can be accessed using the dot notation or as an associative array. Arrays can only have numeric indexes, hence why you can't use ['menus']['buckets'].

http://javascript.crockford.com/survey.html has a good explanation.

MonkeyMaker
May 22, 2006

What's your poison, sir?
Thanks to both of you. Removing that level of nesting and the brackets fixed it.

There Will Be Penalty
May 18, 2002

Makes a great pet!

Blackout posted:

Hey guys, quick question. I'm trying to write a very simple piece of javascript that does two things. First, it will either show or hide an HTML div with the first id I specify. Second, it will change the text of the div with the second id specified. It should toggle these things, so if the div is shown, it will be hidden and vice versa. Same thing with the text (switches between 'Show...' and 'Hide').

Your JavaScript appears to be up to snuff. I'd have to see some generated HTML, incase there's any funky stuff going on.

There Will Be Penalty
May 18, 2002

Makes a great pet!

Tivac posted:

Arrays can only have numeric indexes, hence why you can't use ['menus']['buckets'].

http://javascript.crockford.com/survey.html has a good explanation.

That explanation contradicts you. :)

Crockford posted:

Arrays in JavaScript are also hashtable objects.

Meaning: because arrays are objects, they can have string-indexed properties. Restating Crockford, the special thing about Array objects is their magical length property. And because of the equivalence of the bracket and dot notations, the length property can be accessed via a["length"], by the way.

It is not common to use other string-indexed properties on an array, but it is common to extend Array.prototype with methods, which are nothing more than string-indexed object (or prototype) properties whose values are functions.

There Will Be Penalty fucked around with this message at 02:31 on Apr 22, 2009

There Will Be Penalty
May 18, 2002

Makes a great pet!
One other thing I noticed about JavaScript.

The equivalence of the dot and bracket notations for accessing object properties extends to method calls. This includes the aspect that the value of this during the method call is set to the referenced object. Meaning: o.method(args) and o["method"](args) are exactly equivalent.

This means you can write code such as the following:

code:
var visible;                    /* a boolean */
/* ... */
$("#div0")[visible ? "show" : "hide"]();
This is equivalent to calling either $("#div0").show() or $("#div0").hide() depending on visible's value.

EDIT: I know that in most instances you can use $("#div0").toggle(). This is an example. But sometimes you may wish to maintain the state separately.

There Will Be Penalty fucked around with this message at 02:44 on Apr 22, 2009

Tivac
Feb 18, 2003

No matter how things may seem to change, never forget who you are

There Will Be Penalty posted:

That explanation contradicts you. :)

Meaning: because arrays are objects, they can have string-indexed properties. Restating Crockford, the special thing about Array objects is their magical length property. And because of the equivalence of the bracket and dot notations, the length property can be accessed via a["length"], by the way.

It is not common to use other string-indexed properties on an array, but it is common to extend Array.prototype with methods, which are nothing more than string-indexed object (or prototype) properties whose values are functions.

Technically they're a hashtable, yes. I over-generalized a bit to help with the distinction between when you'd want to use arrays vs objects. Never mind that in JS an array is technically just a specialization of an object...

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome
just gonna drop in and mention that no one should ever modify Object.prototype because it means that not only will you have to stop using Objects as hashtables, but anyone who uses your code will have their Object-based hashtables break.

Not that anyone was saying you should, but just thought I'd mention it.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.

There Will Be Penalty posted:

This means you can write code such as the following:

code:
var visible;                    /* a boolean */
/* ... */
$("#div0")[visible ? "show" : "hide"]();

I personally can't stand this type of thing. Just because it's clever doesn't mean you should do it. When someone comes back 6 months later to read thousands of lines of code like this it's just a nightmare when it's not at all obvious what's happening without having to mentally pause for every bit of cleverness to figure it out. Use an if statement and write explicit and readable code where what's happening is instantly recognizable without even having to think.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
What that statement is doing should be instantly obvious if you have any understanding of how javascript objects work. It's stupid to do things in a way other than the absolutely most basic when the "benefit" is that you save typing 15 characters, but it really shouldn't cause confusion.

Divinorum
Nov 18, 2002
I am trying to create a pick-4 lotto which uses loops. You are supposed to enter 4 numbers 0-9 and create how many times it takes for that series to come up. I am not very good at javascript and have been having a lot of trouble on just a couple things. Any help would be greatly appreciated.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<! Programmer: >
<! Class: CIS 1207 Programmin Logic & Design >
<! Assignment: Homework Program #7>

<head>
<title>Assignment#7 Loops</title>
<script type="text/javascript" src="http://prenhall.com/reed/random.js">
</script>

<script type="text/javascript">

function PickNum()
{
var Pick1, Pick2, Pick3, Pick4;
var Roll1, Roll2, Roll3, Roll4;
var Count;

Pick1=parseFloat (document.LottoFrm.txtPick1.value);
Pick2=parseFloat (document.LottoFrm.txtPick2.value);
Pick3=parseFloat (document.LottoFrm.txtPick3.value);
Pick4=parseFloat (document.LottoFrm.txtPick4.value);
Count=document.LottoFrm.txtcount.value;

do
{
Roll1=RandomInt(0,9);
Roll2=RandomInt(0,9);
Roll3=RandomInt(0,9);
Roll4=RandomInt(0,9);

}
while
(Roll1!=Pick1 || Roll2!=Pick2 || Roll3!=Pick3 || Roll4!=Pick4);
count++;
}
</script>
</head>

<body bgcolor="blue" style="color:white">
<h3 style="text-align:center">CNM Lotto</h3>

<form name="LottoFrm" style="text-align:center">

<br/>
Pick-4 Lottery Numbers: <input text="text" name="txtPick1" size=5 value=""
;"/>
<input text="text" name="txtPick2" size=5 value=""
"/>
<input text="text" name="txtPick3" size=5 value=""
"/>
<input text="text" name="txtPick4" size=5 value=""
"/>

<br/><br/>

<input type="button" value="Click Here to Begin Drawing"
onClick ="PickNum();"/>
<input type="text" name="txtCount" size=5 value=""/>


</form>
</body>
</html>

Kekekela
Oct 28, 2004

Divinorum posted:

do my homework for me

Start by resolving your javascript errors. For one, I don't think document.LottoFrm.txtcount will work, you can give the text box an id and call document.getElementById('txtcount') instead. (The latest version of firefox requires you to go to Tools>ErrorConsole to see the errors, not sure about IE et al)

Then once the syntax is correct start looking at your logic. It may be doing what you want already, I just glanced pretty quickly, but from what you're describing you want to be reading the count value and displaying it in the txtcount field after you've processed the main loop, instead of reading it in from the txtcount field before the loop (should there even be anything in that field at this point? seems like this is where your answer goes, not where you get user input)

Kekekela fucked around with this message at 18:10 on Apr 22, 2009

ohgodwhat
Aug 6, 2005

Divinorum, did you complete assignment #6 successfully with that AAA website's javascript?

SuckerPunched
Dec 20, 2006

Kekekela posted:

Start by resolving your javascript errors. For one, I don't think document.LottoFrm.txtcount will work, you can give the text box an id and call document.getElementById('txtcount') instead. (The latest version of firefox requires you to go to Tools>ErrorConsole to see the errors, not sure about IE et al)

To add to this, you could also install the Firebug extension to get even better Javascript debugging if you're using Firefox. If you're not using FF, I suggest you start because debugging Javascript in IE (and, in my opinion, even in Safari, Opera, or Chrome) is a pain when compared to the power you get from Firebug.

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome

SuckerPunched posted:

To add to this, you could also install the Firebug extension to get even better Javascript debugging if you're using Firefox. If you're not using FF, I suggest you start because debugging Javascript in IE (and, in my opinion, even in Safari, Opera, or Chrome) is a pain when compared to the power you get from Firebug.

Microsoft script editor is imho just as good as firebug

SuckerPunched
Dec 20, 2006

rotor posted:

Microsoft script editor is imho just as good as firebug

It's ok, but I'd argue that it's quite a bit less convenient to use than Firebug, generally speaking. The MSE tends to hang a lot, as well as (unless I've missed out on a better way) having to be re-opened every time there's another error. I admit I don't use it often but I've always had very mixed / slightly negative feelings about debugging with it.

With Firebug, it's all right there in the same window (or popped out, whatever), with the errors cleanly displayed. I dunno, it's just a better overall experience in general, if you ask me.

Kekekela
Oct 28, 2004
I haven't used any of the IE tools since IE Dev Toolbar or whatever for IE7, which I thought was really buggy compared to Firebug. Is there something better out there for IE now?

rotor
Jun 11, 2001

classic case of pineapple derangement syndrome

Kekekela posted:

I haven't used any of the IE tools since IE Dev Toolbar or whatever for IE7, which I thought was really buggy compared to Firebug. Is there something better out there for IE now?

yes the microsoft script editor, although "now" isn't really appropriate since it's been around since like 2004 or something

http://www.jonathanboutelle.com/mt/archives/2006/01/howto_debug_jav.html

biznatchio
Mar 31, 2001


Buglord

rotor posted:

yes the microsoft script editor, although "now" isn't really appropriate since it's been around since like 2004 or something

http://www.jonathanboutelle.com/mt/archives/2006/01/howto_debug_jav.html

The IE8 Developer Tools comes with a new debugger.

Divinorum
Nov 18, 2002

Kekekela posted:

Start by resolving your javascript errors. For one, I don't think document.LottoFrm.txtcount will work, you can give the text box an id and call document.getElementById('txtcount') instead. (The latest version of firefox requires you to go to Tools>ErrorConsole to see the errors, not sure about IE et al)

Then once the syntax is correct start looking at your logic. It may be doing what you want already, I just glanced pretty quickly, but from what you're describing you want to be reading the count value and displaying it in the txtcount field after you've processed the main loop, instead of reading it in from the txtcount field before the loop (should there even be anything in that field at this point? seems like this is where your answer goes, not where you get user input)


I wasn't trying to get my homework done for me. Just needed a suggestions and the ones provided did very well. Here is my corrected code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<! Programmer: >
<! Class: CIS 1207 Programmin Logic & Design >
<! Assignment: Homework Program #7>

<head>
<title>Assignment#7 Loops</title>
<script type="text/javascript" src="http://prenhall.com/reed/random.js">
</script>

<script type="text/javascript">

function PickNumber()
{
var Pick1, Pick2, Pick3, Pick4;
var Roll1, Roll2, Roll3, Roll4;
var Count;

Pick1=parseFloat (document.LottoFrm.txtPick1.value);
Pick2=parseFloat (document.LottoFrm.txtPick2.value);
Pick3=parseFloat (document.LottoFrm.txtPick3.value);
Pick4=parseFloat (document.LottoFrm.txtPick4.value);

Count=0;

do

{

Roll1=RandomInt(0,9);
Roll2=RandomInt(0,9);
Roll3=RandomInt(0,9);
Roll4=RandomInt(0,9);
Count++;
}



while

(Roll1!=Pick1 || Roll2!=Pick2 || Roll3!=Pick3 || Roll4!=Pick4);

document.LottoFrm.txtCount.value=Count;


}
</script>
</head>

<body bgcolor="blue" style="color:green">
<h3 style="text-align:center">CNM Lotto</h3>

<form name="LottoFrm" style="text-align:center">



<br/>
Pick-4 Lottery Numbers: <input text="text" name="txtPick1" size=5 value=""
/>
<input text="text" name="txtPick2" size=5 value=""
/>
<input text="text" name="txtPick3" size=5 value=""
/>
<input text="text" name="txtPick4" size=5 value=""
/>

<br/><br/>

Click on the button to perform Pick-4 drawings until sequence appears
<br/><br/>

<input type="button" onClick="PickNumber();" value="Click Here to Begin Drawing"/>
<br/><br/>
Number of Picks: <input type="text" name="txtCount" size=5 value="" />

</form>
</body>
</html>

Thanks for the help friends.

TagUrIt
Jan 24, 2007
Freaking Awesome
I'm trying to write a greasemonkey script that adds, among other things, a button to the page. I'm fairly certain the rest of my code works, but I simply cannot figure out how to add the onclick event for the new button. I'm writing this solely for FF3, so I'm not too concerned about stuff not working in IE or whatever.

code:
var button = document.createElement("button");
button.type  = "button";
button.value = "Submit data!";
button.name  = "submitButton";

//what googling suggests is right...but doesn't work
//button.onclick = new Function("alert('lol')");
//button.onclick = new Function (evt) {alert('hi');};

//ditto
//button.onclick = new Function("doStuff()");
//button.onclick = new Function (event) {doStuff();};


// This works! (I think)
//button.setAttribute("onclick", "alert('hi')");

// but this doesn't :(
//button.setAttribute("onclick", "doStuff()");

// And some other possibilities via google
//button.setAttribute("onclick", "doStuff()");
//button.addEventListener('onClick', 'doStuff()', false);
Appending the button to the page either before or after adding the handler doesn't seem to make any difference.

So, in general, if I'm dynamically creating a button and adding it to the page, how do I actually set the onclick event for it?

edit: I figured it out thanks to stuff on the previous page. I had the wrong type of event named (onclick or onClick instead of click).
code:
button.addEventListener('click', function (){doStuff();}, false);

TagUrIt fucked around with this message at 17:33 on Apr 25, 2009

Kekekela
Oct 28, 2004
Just curious:

Will it work if you change this:
code:
button.addEventListener('click', function (){doStuff();}, false);
To this:
code:
button.addEventListener('click', doStuff, false);

TagUrIt
Jan 24, 2007
Freaking Awesome
Indeed it does. :)

nooge
May 1, 2009

Hmmm I guess I'll try this here because it's more centered around JS.
So I have a single PHP document that consolidates my head, my tool menubar, page content and a footer. My overall goal is to be able to have the active page on the menubar to be highlighted and the link disabled without having to stray from my original idea of organizing the pages. I figure declaring a variable somewhere in the clusterfuck to identify what page I am on then have Javascript tell the header.php (where the menubar is) to do the dirty work.

The issue I have to finding a place to declare the variable. Here is a general idea of what's going on in the main page of index.php:
code:
<?php include "head.php"; ?> 
<?php include "header.php"; ?> 
<?php include "index_content.php"; ?> 
<?php include "footer.php"; ?>
After that, it loads those pages and voila.

All the Javascript action is going to be contained in header.php, so I need a good place to declare a single varaible:
code:
var site_id = "index";
My first thought would be to create another page solely for the use of declaring it, but that seems retarded and I know there must be a better way - such as doing it in my index.php. Any quick way or doing it or a resource to guide me?

tl;dr edit:
I guess I really just would like to know an easy way to declare a variable in my index.php without breaking everything and have it read into the header.php.

nooge fucked around with this message at 15:31 on May 4, 2009

Supervillin
Feb 6, 2005

Pillbug

nooge posted:

I guess I really just would like to know an easy way to declare a variable in my index.php without breaking everything and have it read into the header.php.

Definitely a PHP question, not JS, but here you go:

php:
<?
    // in index.php
    $page = 'index';
    include('header.php';
?>
Voila, $page is available inside header.php.

Personally I'd rather have it automated so I wouldn't have to worry about remembering to add the variable every time I make a new page. Something like:

php:
<?
    function getNavLink($page, $text) {
        if (!strcmp($page, _SERVER["PHP_SELF"]) {
            return '<span>' . $text . '</span>';
        } else {
            return '<a href="' . $page . '">' . $text . '</a>';
        }
    }
?>
Then let CSS handle the styling accordingly. Not that this is THE best way to do it, so if you prefer to declare a variable before including, that works too.

Edit: vvv Welcome. PHP_SELF is usually the current page, though you can check to be sure using phpinfo(). Sometimes you'll need to use a different $_SERVER variable depending on how your host is set up.

Supervillin fucked around with this message at 16:45 on May 4, 2009

nooge
May 1, 2009

Supervillin posted:

Definitely a PHP question, not JS, but here you go:

php:
<?
    // in index.php
    $page = 'index';
    include('header.php';
?>
Voila, $page is available inside header.php.

Awesome that worked perfectly. I'm sure the 2nd method works great too but I'm not entirely fluent in PHP and don't like copy and pasting without fully understanding. I'll sit down tonight and decipher what you did. Thanks a lot!

Adbot
ADBOT LOVES YOU

nooge
May 1, 2009

Another small question... after I used that code it looks and works great - except it lags a bit when loading the picture compared to those around it even though it it is the same size. Any way to speed up the process or am I stuck with that small (.25 second) lag?

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