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
Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
This isn't strictly a Javascript question, but is there a way to find the margin of an element if it has not been assigned from javascript?

Example document and java script:
code:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Table</title>
    <style>
div
{
	margin:2px;
	background:pink;
}
    </style>
  </head>
  <body>
	<div id="fff">a</div>
  </body>
</html>
code:
document.getElementById("fff").style.margin

That Javascript snippet is an empty string.

You can find the height and border widths by using offsetHeight and clientHeight, but is there any such trick for margin? This is something that would need to work (only) in FF 3.6, if at all. (:ssh:maintaining poo poo code)

Adbot
ADBOT LOVES YOU

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

The Merkinman posted:

You should be able to do that in jQuery with.css()

Yeah, there is no jQuery. We have MooTools, I could look into that.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

OddObserver posted:

getComputedStyle.

Yes, thank you.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Leshy posted:

code:
contactToggle[0].onmousedown = function(){toggleContactLayer(contactID);};

All of the contactId's refer to the same variable. At the end of the loop it's "company4", so every toggleContactLayer call gets the same value.

You could do this:
code:
      contactToggle[0].onmousedown = (function(){
	var myId = contactID;
	return function(){toggleContactLayer(myId)};
	})();
Variables in Javascript have function scope, so we create a new function, assign contactID to a variable inside it, then return an inner function which has access to the outer function's variables.

That last line with the parentheses just calls the outer function immediately so that "myId" gets assigned and the inner function created.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Leshy posted:

I figured something like this must be happening, I'm just not sure why.

Inner functions have access to outer function's scope.

Your code has 2+n scopes:
Global scope variables:
var contact, contactID, i, contactCompany, contactHeader, contactToggle, contactContent;

Other scopes:
function toggleContactLayer,
contact.length * anonymous function (the ones you assign to contactToggle[0].onmousedown)

Every one of those anonymous functions has their own scope, but can also access outer (global) variables. So each anonymous function refers to the exact same (global) contactID.

When you assign the onmousedown, the Javascript engine just thinks "that sure is a function". Only when the event fires does the engine care about what happens inside the function. In your case it is simply
toggleContactLayer( (global) contactID). There are several anonymous functions, but only one contactId (the global one).

My example:
code:
contactToggle[0].onmousedown = (function(){
	var myId = contactID;
	return function(){toggleContactLayer(myId)};
})();
On the surface it looks like this: ()();, that is "something inside parentheses (the first set of parentheses), that is to be invoked like a function (the second set of parentheses)".
Well, the first set of parentheses actually contains a function definition, so you're defining an anonymous function and then immediately invoking it.

When you invoke the function, you create a new scope, with the variable "myId". Each myId sits inside its own anonymous scope and gets assigned the current value of the global contactID.
Then, from inside this anonymous scope, you return a new anonymous inner function :eek:. This anonymous inner function gets assigned to onmousedown, and once again the Javascript engine just thinks "that sure is a function".

Finally, when the event fires, the anonymous inner function gets run. Again, it's simply
toggleContactLayer( (the outer function's) myId). There are several outer functions, so there are several myId's :lsd:

quote:

On each iteration of the loop, the variable has a different value, so I expected that much like in setting the id of an element, setting the onmousedown event would assign the then current value of the variable.

No, the code inside function(){} is, well, code. It is evaluated when the function is called. You could have assigned contactToggle[0].onmousedown = function(){toggleContactLayer(thisvariableDoesNotEvenExist)}, and you would only get an error on the mousedown event.

quote:

Your solution works perfectly, however, so thanks a lot! I'm still learning this whole javascript thing as I go along, and I couldn't really find a solution for this. Another thing learned!

Well, I only started to appreciate Javascript's (good) weirdness in the last 6 months or so.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Bob Morales posted:

from A to Z do letter
write <a href='#' id='letter_link'>letter</a>
end

Should I add another property like letter='%letter&' to the <a> tag? Could I think grab it via DOM? Should I put the letter in the 'letter_link' id (letter_link_a, letter_link_b) and parse it out?

I'm just lost and need to buy a JQuery book this week.

Are you literally using id="letter_link" for every letter? Because id's are supposed to be unique. I'd use class="letter_link", and then something like id = "letter_a", "letter_b" and so on.

In the onclick handler, your letter would be this.id.charAt(7).

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Keevon posted:

I'm curious, is there something wrong with just grabbing the value inside the <a> tag and using that? Why add the extra properties?

That would work at least now and in this case. But the first thing that I could think of was if you later change the structure of the page like so: <a href="#"><img src="a.gif"></a>, you'd have to change your javascript as well.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Boz0r posted:

code:

    element.attr("onClick","updateBorder(this)");
    element.onclick = "updateBorder(this)";
    alert("onClick " + element.attr("onClick"));


You're also using both onclick and onClick. Is "onClick" a thing that exists?

Edit: Use your browser's developer tools to inspect your elements. And use a function as your onclick handlers, not a string :(

Wheany fucked around with this message at 12:29 on Oct 20, 2011

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Does the first function (updateBorder0?) work in all browsers?

Try
code:
var test = $(cb).parents("tr").first();

 if (cb.checked){
        test.style.border='1px solid red';
    } else {
        test.style.border='';
 }
e: Or even test.addClass("highlighted")/test.removeClass("highlighted")

and then add some css:
code:
.highlighted{
border:1px solid red;
}

Wheany fucked around with this message at 11:17 on Oct 24, 2011

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Mindisgone posted:

ok, so after some critical thinking (:colbert:) I came up with this:

<script type="text/javascript">
function setStyle(x){
if (document.getElementById("country").selectedIndex != 0){
document.getElementById(x).style.visibility="visible";
} else
{ document.getElementById(x).style.visibility="hidden"; }
}
</script>

now this works except if you reselect "country" (essentially my placeholder option) it doesn't re-hide the second menu...any suggestions :confused:

Because you have a <div id="country">. The div's selectedIndex is undefined, and undefined is always != 0 (which is why the second <select> appears when you select a value).

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Mindisgone posted:

THANK YOU VERY MUCH! I never would've guessed the div tag was messing me up like that, I just canned it altogether so now I'm a happy camper. :worship:

Well, I didn't even notice you had a div tag with the same id, I just ran you code and used a breakpoint inside the setStyle function and a watch to see that document.getElementById("country") was returning a HTMLDivElement.

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>.

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.

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).

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Every browser has dev tools for them these days.

Firefox has Firebug (extension), which you've heard of.
IE has F12 developer tools (or whatever the gently caress they're called) built-in
Chrome (and Safari) have Developer Tools (Chrome's can be activated by right-clicking on any element on a page and selecting "inspect element")
Opera has Dragonfly (also activated by right-cliking and selecting "inspect element")

Golbez posted:

Javascript goes from horrible to kind of fun once you get a debugger like Firebug.

Agreed.

The best part, I think, is using the console and just trying all kinds of poo poo. Like if you're using jQuery, just doing something like jQuery(".fancy").css('background', 'pink').

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Octopus Magic posted:

I remember back in the day before dev tools and it was very dark and scary.

alert('result was:' + result);

e: Actually, the three things that have made javascript development better are: developer tools, frameworks and more meaningful error messages. The errors used to be "poo poo broke somewhere, gently caress you", now they might actually tell you which part of foo.bar.quux.message is null.

Wheany fucked around with this message at 09:16 on Dec 30, 2011

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

subx posted:

I think things just not being typed is where I get confused. Just being able to tack random poo poo onto a variable feels weird.

If it quacks like a duck, it is a duck.

var a_thing = {};

a_thing.quack=function(){alert("hello, I'm totally a duck")};

a_thing.quack();

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
1. Probably
2. var someElement = document.getElementById('someId');

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Even if you already decided to do this with transparent pictures...

From Javascript perspective, svg is pretty close to html.

Just add a stylesheet to the the svg-file:
code:
<?xml-stylesheet type="text/css" href="my_style.css" ?>
Then add some styles to the css file:
code:
.selected
{
	stroke:rgb(255,255,0);
	stroke-width:1px;
	opacity:1;
}
Then add the above style to your selected regions:
code:
region.setAttributeNS(null, "class", "selected");

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Does opening a new window fire an event?
Alternatively: do plugins open new windows through the browser's javascript interface?

What I want to do: I want to write an Opera user javascript that fires before any new window (or tab) is opened, examine the to-be-opened window's address and possibly modify it before the window is actually opened.

If it fires an event, I could probably use Opera's BeforeEvent listener. If plugins use window.open, I could probably use defineMagicFunction.

If neither of those happen, I guess I'm SOL.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Suspicious Dish posted:

What do you mean by "plugin"? Flash? Flash doesn't have the native capability to open a new window. Most Flash sites implement pop-ups by going to a link with the "_blank" target (how this works inside Flash internally, I don't know), or by calling out to JavaScript using an FSCommand, ExternalInterface, or going to a java script: url.

That's exactly what I meant. I figured that plugins (including flash) can't actually just open new windows, they have to request the browser to open a new window somehow. I'm trying to intercept that "somehow".

java script: urls should not be a problem, since user javascript has BeforeJavascriptURL handlers.

I'll check out if the google knows anything about FSCommand or ExternalInterface.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Seedy Wizard posted:

Okay so I've showed this to a few people and mostly got really confused looks. This is for a uni assessment and I still get pretty :confused: with a lot of basic stuff so I hope I'm not just missing something obvious.

We're to make a website that sells mobile phones. And that's a part of the order form page. It's supposed to calculate and give me a total. But all it seems to do is reset the page or something when you click calculate and I'm trying to get the prices to pop up in the text boxes depending on what you select.

(code removed)

Sorry for posting the whole thing but I have no idea where it is that I'm mucking up. Thanks in advance.

Using a development tool* to debug, it was pretty trivial to find two errors that happen in calculate();

purchase_form has no member called deliver

this line: result=result.toFixed(2); result is undefined, so you cannot call result.toFixed()

To stop the page from refreshing, return false at the end of calculate();

You probably also want to check that the your conversions form fields are valid numbers before doing calculations (function isNaN()).

* Opera, Chrome, IE and Safari have built-in development tools, Firefox has Firebug extension.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I you use jslint (you probably should) and Notepad++ (also pretty good), download the gently caress out of this plugin:
http://sourceforge.net/projects/jslintnpp/

Ctrl+Shift+F5 lints your current file and moves the cursor to the first error. Makes linting soooo much quicker, holy poo poo.

Polishing old and busted javascript became so much less of a chore.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

tinaun posted:

I would do that but I have no access to the source itself. :sigh:

JavaScript code:
var cssText = "#someElement { background-color: white; } #someElement:hover { background-color: red; }";
var style = document.createElement('style');
style.appendChild(document.createTextNode(cssText));
document.head.appendChild(style);

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

darthbob88 posted:

Wait. You mean you can dynamically create CSS style elements? :aaa: I'm going to abuse that so hard.

Dude, you can dynamically create image files that you then base64-encode and set as a data url to an img-tag. I've done it and it is horribawesome. All the images on that page are created on-the-fly with javascript.

(I've done the same with pngs but don't have access to them right now)

e: here it is

Wheany fucked around with this message at 21:38 on May 30, 2012

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
The crawler probably ignores any css.

In case it doesn't, you could try
CSS code:
.hidden {
    position:absolute;
    top:-10000px;
    left:-10000px;
}
or
CSS code:
.hidden {
    width:0px;
    height:0px;
    overflow:hidden;
}
and then adding the hidden class to the hidden divs.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

burnt_offerings posted:

code:
                //alert(browser + "\n\n" + navindex);

                                        //alert('SAFARI BROWSER');

People please, use a debugger, it's not 2002 anymore.

Seriously, just put a breakpoint in your code and either add browser and navindex in your watches, or use the console to evaluate your values in real time.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Is there some library for doing browser detection? I promise to use it only for good (if at all)

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well for what I would use it, it wouldn't need to be 100% accurate. The accuracy I need would be fulfilled with searching for chrome, safari, opera, firefox (maybe gecko) and IE in the user agent. I just thought that I might get to be lazy.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Naah, it's just "It seems you're using <some browser>, here are instructions specific to your browser". If I don't recognize the browser, or if javascript is disabled, I just show everything.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well, this is what I was going for and it is pretty much as accurate as it needs to be:

http://wheany.com/browserdetect/

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Different browsers have different uis, so howtos, for example, need to be different across browsers.

Also, shock that Opera spoofing as Firefox fools a script that does indexOf on the user agent.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Is there any particular reason you're using XML?

I'd probably use JSON.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well good news, it sounds like JSON (JavaScript Object Notation) is exactly what you want!

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Claeaus posted:

code:
	    a = eval ("(" + jsonTexto + ")");
:ughh::tizzy:

Please use
code:
a = JSON.parse(jsonTexto);

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Kallikrates posted:

Where is a good source for picking up best practices etc for writing javascript for websites?

Its not my first langauge, and so far I have solid grasp of the basics (async, callbacks etc).

Watch this video (java script: The Good Parts). It's a pesentation by Douglas Crockford at Google Tech Talks.

It's not about best practises for websites, but personally, it kinda blew my mind when I watched it:

https://www.youtube.com/watch?v=hQVTIJBZook

Also use JSlint/JShint with as few exceptions as possible. It will force you to write better Javascript.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Well, I don't actually know anything about Zepto and it is not strictly just .ajax(), but it is a "minimalist JavaScript library for modern browsers with a largely jQuery-compatible API."

http://zeptojs.com/

Like I said, I don't know anything about it, just stumbled on it when reading backbone.js documentation.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
I think localStorage is probably the most widely-supported option.

JavaScript code:
// Store value on the browser beyond the duration of the session
localStorage.setItem('key', 'value');
 
// Retrieve value (works even after closing and re-opening the browser)
alert(localStorage.getItem('key'));

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
From the error message it sounds like ValidationCheckbox is undefined.

If you put a breakpoint on that line, what does it say is the value of Spry.Widget.ValidationCheckbox?

Adbot
ADBOT LOVES YOU

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Mindisgone posted:

That's quite a mouthful but I will definitely try this out. I guess without telling it the encoding it doesn't send the variable just a string literal?

What you're doing is the php equivalent of:

PHP code:
$latlong = results[0]['geometry']['location'];
$params = 'latlng=$latlong'; // note the single quotes
What you could do in php (still using single quotes):
PHP code:
$latlong = results[0]['geometry']['location'];
$params = 'latlng=' . $latlong;
Which would be the same as

JavaScript code:
var latlong = results[0].geometry.location;
params = "latlng=" + latlong;

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