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
Supervillin
Feb 6, 2005

Pillbug

sonic bed head posted:

Does anyone know why 3rd party JS libraries never throw any errors?

I noticed this too, and some library sites actually advertise that as a feature. I guess it increases market share among people who want just "plug and play (or don't play)" rather than actually writing try catch blocks when appropriate. I wish at least there were an option you could set before loading the library that would turn on/off "throw errors" mode.

Adbot
ADBOT LOVES YOU

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

Supervillin
Feb 6, 2005

Pillbug

Crysinth posted:

See, in this experiment, reaction time is important, but there seems to be a variable amount of lag due to IE (or so he claims) trying to run and do things in the background, and FireFox is worse about it, so it throws off the reaction times recorded from the experiment.

Pretty sure any given browser's implementation of JavaScript is going to be faster than any given human's reaction time, but I could be wrong.

How is he trying to time stuff? Unless he's somehow blocking the browser with while(true) { ... }, time is time and will be pretty accurate. If nothing else the start time and end time would be "off" by approximately the same amount, if it's just due to browser overhead. Reaction time would be the difference between the two, so still accurate.

Can he just ask that they close other browser windows while testing whatrever he's testing? Or what else is running?

Supervillin
Feb 6, 2005

Pillbug

diadem posted:

1 time out of 100, the DOM gets updated and the window doesn't redraw properly

Modifying the DOM again should trigger it, some libraries (I think scriptaculous?) create, append, and remove a text node containing only spaces. I did a little searching and found that adding and removing a class, or even just reassigning a class works.

code:
// this should do it
element.className = element.className;


// if not, this should do it
element.className += "forcedomredraw";
element.className = element.className.replace(/forcedomredraw/, '');


// if not, try this?
var redraw = function(element) {
    var t = document.createTextNode(' ');
    element.appendChild(t);
    setTimeout(function() {
        n.parentNode.removeChild(n);
    }, 0);
};
// changeDomStuff();
redraw(document.getElementById('whatever'));

// if not, kill everyone at Microsoft.

Supervillin
Feb 6, 2005

Pillbug

noapparentfunction posted:

1) How do I create this long horizontal page without adding scrollbars to the frame cell or exploding the page sideways?
overflow: hidden in your CSS "turns off" scrollbars, then you would use JS to scroll the div to particular coordinates.

noapparentfunction posted:

2) How can I make the stationary scroll links target the particular cell of grids?

Can't speak specifically for the demos you linked to, but it seemed they all have fixed-size containers, which means they know "where other content is". For example:

code:
<style type="text/css">
    #container {
        position: relative;
        width: 100px;   /* ridiculously small... */
        height: 100px;  /* ... but easy for math */
        overflow: hidden;
    }
    #contents {
        position: absolute;
        width: 300px;
    }
    #contents p {
        width: 100px;
        height: 100px;
        float: left;
    }
</style>
<div id="container">    <!-- the "window" we're looking through -->
    <div id="contents"> <!-- 3x2 grid -->
        <p>blah blah blah</p>
        <p>blah blah blah</p>
        <p>blah blah blah</p>
        <p>blah blah blah</p>
        <p>blah blah blah</p>
        <p>blah blah blah</p>
    </div>
</div>
<div id="navigation">
    <a href="top-left.html">top left</a>
    ...
    <a href="top-right.html">top right</a>
    ...
</div>
Then your script would attach to the links and move stuff accordingly. If you want to go from "top left" to "top right", scroll 200px to the right. "top right" to "bottom right" scroll 100px down.

Edit: Looking at that Hotel Oxford source code, find <div id="contents_wrapper">, that's the container above. All the divs with class "content" are the fixed-size boxes. Not exactly the same implementation, of course, but same concept.

Supervillin fucked around with this message at 04:32 on May 12, 2009

Supervillin
Feb 6, 2005

Pillbug

FateFree posted:

Eh that didnt work for either, I think because its not a form field, rather just text.

Since it's a DIV, .innerHTML should work everywhere.

Supervillin
Feb 6, 2005

Pillbug

Fruit Smoothies posted:

Hey. I have an XML request which gives me a list of data. An older version of these data already exist on the webpage. Both data are variants on a simple list. What's the best way of syncing these lists? In the HTML list, each item is in its own div, and the XML nodes from the new list are being looped through.
The method I can think of at the moment, is to remove all old (HTML) items from the new (XML) list. If an item isn't found in the XML list, it's removed from the HTML. At the end, all the remaining items in the XML are added to the HTML div list.
This poses data structure problems, and I'm not familiar with how best to handle lists in javascript. Would arrays be the way forward?

Performance-wise it seems like it would be much faster to just replace the whole list than to sync using two or possibly three loops through each set. Maybe I'm too tired or something, but wouldn't you get the same data if you destroy the HTML list and add all the XML items?

Edit: If I DID misunderstand, either Arrays or object literals should work fine. Those are pretty much the only list paradigms built into JavaScript. I know ExtJS and probably some other libraries have ways of binding data sets together, might be what you need.

Editx2: vvv Just need more semantic markup and you should be all set. Make your list a real list (ul/dl), or if that's not feasible at least surround the list with a container div that can be reset without affecting the forms and images after the list.

Supervillin fucked around with this message at 01:38 on Jun 14, 2009

Supervillin
Feb 6, 2005

Pillbug

Jreedy88 posted:

Yay! Worked like a charm. Thanks.

FYI, when you set it to "" you're telling it to set display to whatever its default is, which according to your CSS is "none"; that's why it seemed like it didn't do anything.

Often when you come across snippets that hide/show stuff they'll use display="none" to hide it and display="" to show it, because the default could be "inline", "block", etc. depending on the element.

Supervillin
Feb 6, 2005

Pillbug

FedEx posted:

wait, for real?

I was going to do that originally but its like 1600 lines >_> I already wrote an alternative PEACE OUT

If your JS menu was 1600 lines then it's drat good you wrote an alternative :)

Supervillin
Feb 6, 2005

Pillbug

Carthag posted:

code:
map.addOverlay(GGeoXml("http://domain/path/to/file.kml"));
should be
code:
map.addOverlay(new GGeoXml("http://domain/path/to/file.kml"));
GGeoXml is a constructor, you have to use new.

Supervillin
Feb 6, 2005

Pillbug

Slasher posted:

Is this hack for IE bad practice for any reason (assume necessary variables exist)?

try{
var form = document.createElement("<form action='upload.php' method='POST' name='fileUpload"+fileCount+"' id='fileUpload"+fileCount+"' enctype='multipart/form-data' target = 'frmUpload"+fileCount+"' >");
} catch (err) {
var form = document.createElement("form");
form.setAttribute("action", "upload.php");
form.setAttribute("method", "POST");
form.setAttribute("name", "fileUpload"+fileCount);
form.setAttribute("id", "fileUpload"+fileCount);
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("target", "frmUpload"+fileCount);
}

Just readability and maintenance, I would think. If you need to change anything about the form, you would have to do it twice.

form.action = 'upload.php'; // should work in both IE and Regular Browsers

Supervillin
Feb 6, 2005

Pillbug

awdio posted:

It does not work. I think it's because an options value, not a selected index value, needs to be passed somehow. Without it being so dynamic, this is what originally worked: onChange="Show_Stuff(display4)"

code:
ShowStuff(this.selectedIndex.value); // selectedIndex is a number, .value doesn't exist
ShowStuff(this[this.childNodes[this.selectedIndex].value); // this[index] is an option, .value exists

Supervillin fucked around with this message at 02:00 on Dec 2, 2009

Supervillin
Feb 6, 2005

Pillbug

Elected by Dogs posted:

Would it be easier to just make a function asking to click ok/cancel when a link is onclick=""'d?

That's what peepsalot just showed you, actually. :)

More specifically, (new RegExp(document.domain, 'i')).test(this.href) will tell you if the domain matches, and confirm(...) pops up the OK/Cancel dialog. I use that for an analytics script and it works goodish.

For performance's sake you might want to do something like:
code:
var r = new RegExp(document.domain, 'i');
$("a").click(function() { if (!r.test(this.href)) { return confirm("You sure about that?")} });
That way it can reuse one regex instead of creating a new identical regex for every link.

Edit: Whoops, misread the first question, the above will tell you if the link goes to somewhere other than the current page's domain. To whitelist you could use something like:
code:
var r = /whatever\.com|goodsite\.net|othersite\.com/i;
$("a").click(...);
Depending on how long your whitelist is and how often that list changes, you (or we) could whip up a function that joins an array of whitelisted domains and uses that in the regex.

Supervillin fucked around with this message at 07:15 on Dec 3, 2009

Supervillin
Feb 6, 2005

Pillbug

awdio posted:

I'm excited to get closer to a solution, but in your example ShowStuff(this[this.childNodes[this.selectedIndex].value); where does the missing bracket go? I tried all different sorts of combinations.

Whoops! So this is why they always said "show your work" in math class. Didn't need the initial "this".
code:
// more verbose
var index = this.selectedIndex; // chosen option's index
var option = this.childNodes[index]; // actual <option> element
var value = option.value; // chosen option's value attribute

ShowStuff(this.childNodes[this.selectedIndex].value); // try this!

Supervillin
Feb 6, 2005

Pillbug

RussianManiac posted:

Ok, so I ended up solving my problem using Canvas. What is an equivalent feature in IE i could use?

If the canvas code's already done, adding excanvas to the page would probably be easiest.

If it's exactly 90, 180, or 270 degrees you can actually use CSS (or set CSS with JavaScript):
code:
var element = document.getElementById('thingToRotate');

// no rotation
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';

// 90 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';

// 180 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';

// 270 degrees
element.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
Won't work for arbitrary angles, so excanvas may be your best bet.

Supervillin
Feb 6, 2005

Pillbug

MononcQc posted:

Is there any difference between the regular expression engines of different js browser implementations?

Not likely. Can you post an example of something that one browser gets but the others don't?

Supervillin
Feb 6, 2005

Pillbug

JSLint reports some unescaped characters in those regexes, that ambiguity could lead to the browser differences you're seeing.

The lines it mentions were for not for the shell output regex, but it might make a difference depending on how each browser attempts to correct them. I copied just your shell_output regex and it returns true in Chrome and Firefox:

http://arguments.callee.info/sandbox/regex/ test page, view source.

So if Chrome sees that shell output as a string, it might be testing the regexes in the wrong order. Any way to debug and verify each regex as it's being applied?

Edit: vvv Default settings, I just loaded jslint and pasted the whole script. Stuff like \s came up, which is whitespace in an actual regex but ambiguous in new RegExp(str). Since the argument is a string, \s may be interpreted as whitespace (which is obviously what is intended) or it may be interpreted as an attempt at escaping an s. Inside a string, backslashes need to be escaped, like '\\s'.

Supervillin fucked around with this message at 05:35 on Jan 16, 2010

Supervillin
Feb 6, 2005

Pillbug

epswing posted:

Say I have
code:
var map = {};
map['key'] = 'value';
Is there a difference between delete map['key']; and map['key'] = undefined; ?

Edit: I guess there IS a difference:

code:
map = { foo: 0, bar: 0 };
delete map.foo;
map.bar = undefined;

[map.hasOwnProperty('foo'), map.hasOwnProperty('bar')] // [false, true]

Yeah, more specifically delete unsets the actual property, but assigning undefined leaves the property and unsets its value. Both map.foo === undefined and map.bar === undefined are true after your example, so in most cases there's a literal difference but not a functional difference.

Supervillin
Feb 6, 2005

Pillbug

mit_senf posted:

Is there a way to have an event fire when the browser's vertical scrollbar appears?

Not technically, but there are ways to manually check.

code:
// returns the complete document height, including scrolled content
function getDocumentHeight() {
    return (document.compatMode == "CSS1Compat"
        ? document.documentElement.scrollHeight
        : document.body.scrollHeight);
}

// returns the available vertical browser space
function getViewportHeight() {
    return ('ActiveXObject' in window && !('opera' in window)
        ? (this.isStrict
            ? document.documentElement.clientHeight
            : document.body.clientHeight)
        : window.innerHeight);
}

// if content > space, there is probably a scrollbar
function hasVerticalScroll() {
    return getDocumentHeight() > getViewportHeight();
}
When do you want to catch that event? If it's when you're adding stuff to the page, just call hasVerticalScroll afterward and act on that. If it's when the person resizes the browser, add an event listener to window's resize event and check in there.

Note hasVerticalScroll() will return true if there SHOULD BE a scrollbar, but depending on your CSS one may never actually show up. I'm assuming that won't be an issue in your case but prolly something to keep in mind.

Supervillin
Feb 6, 2005

Pillbug

mit_senf posted:

The first case is when the page is short enough before images are placed on the page so that there's no scrollbar, but afterwards the images make it long enough for a scrollbar to appear.

...

The second case isn't as bad, but still annoying. If the user resizes the window to be small enough to make the scrollbar appear, the same thing will happen, but only the first instant that the scrollbar appears. That is, if you very slowly resize the window smaller and stop the instant that the scrollbar pops up, the tabs will be stuck in the messed up state until you resize it again. It causes an annoying "flicker" between the two states when you resize back and forth. It seems that the resize event is firing before the scrollbar actually appears.

Do you have control over the content that gets loaded? If you can assign width and height styles to each image, they'll be properly sized on append, rather than waiting until they load.

Slightly messier, once the tab contents are replaced you could add an onload to each image that will check the tab size / scrollbar issue again. But I'd only do this if I don't have control over what images are loaded, meaning I wouldn't necessarily know what size they are during coding.

No idea about the second thing, sorry.

Supervillin
Feb 6, 2005

Pillbug
Also, that div doesn't need an ID at all, duplicated or unique or anything. DIV is a tag name.

code:
var div = myForm.getElementsByTagName('div')[0]; // first div inside the form
Also, jQuery is a great idea if you're working on something that actually needs to get done, but feel free to learn pure JavaScript if you're just doing it for yourself. But please don't learn it from anywhere or anyone that tells you language="javascript" is good practice, as that attribute was deprecated about 10-12 years ago.

Try the definitive guide, there's a ton of good info in there, even though it's from 2006. And Head First is a good one for starting out with HTML/CSS, along with why you may or may not want to use XHTML (your code currently uses both, which means it's incorrect either way).

Supervillin fucked around with this message at 01:18 on Feb 14, 2010

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

Supervillin
Feb 6, 2005

Pillbug

Rainbow Pony Deluxe posted:

I'm new to javascript and apparently I must have missed something somewhere, but is there a way to read from a file on YOUR domain and parse the contents, etc., using javascript. So far, all of my searching has led me to use XMLhttpRequest or ActiveXObject depending on the browser, but how do I get the contents of the file that's stored in the XMLhttpRequest Object? Whenever I use XMLhttpRequest.requestText/XML, the result is blank. I'm checking for the ready state being 4 and 200 before I proceed but everytime, XMLhttpRequest.requestText/XML has nothing stored in it. I'm starting to think I'm using the wrong tool to open a file in javascript. What am I doing wrong?

EDIT: Actually, now I'm getting an error saying that says "not well-formed". I don't understand how it isn't well-formed, though, it is just a text file called test.txt and it contains: "6/21 Meeting" and nothing else.

First, make sure you're checking responseText/XML and not requestText/XML, as that second pair doesn't exist. Since you're getting errors, I figure this was just a typo here, but better safe than sorry since you did it twice.

Second, "6/21 Meeting" is not valid XML, so you definitely need to check only responseText. As Haystack said, if the XHR is expecting XML or the server is serving that as XML, that's where the error's coming from.

I doubt any server serves .txt files as XML by default though. Can you post the URL to your text file here? We can check the headers and see if your server is at fault, either setting the MIME type incorrectly or possibly another header.

Otherwise, the XHR object may be built incorrectly. Post your code?

Supervillin
Feb 6, 2005

Pillbug
file:/// requests have status 0, not 200. HTTP status codes are written by the HTTP server, so if there is no server, there's no code.

If you decide to go the jQuery route, cool, otherwise modify your status check:
code:
if (request.readyState == 4 && (request.status == 200 || request.status === 0)) ...

Adbot
ADBOT LOVES YOU

Supervillin
Feb 6, 2005

Pillbug

Chinaski posted:

The first dropdown works fine but if a choice is made on the second dropdown, it clears everything out and leaves only the first dropdown on screen.

You're setting an element (id "os1" or "os2") to be visible, but at the same time you're setting its parent element (id "no") to be hidden. That means os1 or os2 will still not be visible.

As you said, there are cleaner ways to go about this, and it will probably be easier to use a library so you can grab everything with a particular class name easily. But if not, at least make sure all of the stuff that needs to be visible is at the same level in the document and your current code should work fine.

Also you don't need <!-- and --> inside a script tag anymore, that was literally for Netscape Navigator 1, Internet Explorer 2, and Mosaic. That in itself may tell you that scripts you find on the net may be too old to really be helpful.

Edit: Also also, you don't need a hidden class AND a visible class. Stuff's visible by default, just use class="hidden" or class="".

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