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
Optimus Prime Ribs
Jul 25, 2007

I'm trying to convert a timestamp (in seconds) to HH:MM:SS.

Everything works fine, except when I try to prefix values that are less than 10 with a zero.
These are the two functions I'm using:
code:
function PrependZero(value)
{
    return (value < 10 ? "0" : "") + value.toString();
}

function ToTimestamp(seconds)
{
    var hour = PrependZero(Math.floor(seconds/3600));
    var min  = PrependZero(Math.floor(seconds/60)%60);
    var sec  = PrependZero(seconds%60);
	
    return hour+":"+min+":"+sec;
}
For some reason the values 8 and 9 aren't being prefixed properly.
So, I did a quick test and got this:
code:
[parseInt("0"+0), parseInt("0"+1),
parseInt("0"+2), parseInt("0"+3),
parseInt("0"+4), parseInt("0"+5),
parseInt("0"+6), parseInt("0"+7),
parseInt("0"+8), parseInt("0"+9)]

OUTPUT posted:

0,1,2,3,4,5,6,7,0,0

I'm pretty :psyduck: right now. What the hell is going on?

edit:

Figured it out.
Had to specify a base10 system: parseInt(foo, 10).

I knew it was going to be something stupid. :downs:

Optimus Prime Ribs fucked around with this message at 04:40 on Mar 29, 2012

Adbot
ADBOT LOVES YOU

smug forum asshole
Jan 15, 2005
Yeah, it's really easy to use parseInt without specifying that radix, but that's something you're technically supposed to do. I try to run my code through JSHint (or better yet, have your editor do it for you) to catch those kinds of small annoying things.

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Yeah a leading zero on an integer is interpreted as octal in javascript (and some other languages).

pork never goes bad
May 16, 2008

Are questions about coding a custom button in Salesforce using javascript ok for this thread? If not, does anyone know where I could ask?

coronalight
Oct 12, 2006

asdfghjkl;
I'm a moron and didn't notice this thread. Posted in Web Dev Small Questions as well. I apologize.

I need a really simple way to replace the last number before a .jpg in one thumbnail image on a site I'm making. For example:

<img id="thumb" src="t1G1.jpg" />

What type of Javascript one liner could I put inside an <a> to make this happen? I've tried messing around with onclick but nothing seems to work. I didn't use any regular expressions, just tried something like:

<a href="#" onclick="document.thumb.src='t1G2.jpg';"></a>

I really never experimented with Javascript, so this garbage code is just from stuff I remember seeing. Am I not calling the action correctly? If anyone could point me in the direction of simply locating the character before .jpg and replacing it with another number, that would be awesome. Maybe I'll toss in a forums upgrade or something.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Using jQuery will probably make your life easier:

code:
<img id="thumb" src="t1G1.jpg" />
<a href="#" id="thumb-switcher"></a>

<script>
$("#thumb-switcher").click(function() {
  $("#thumb").attr("src", "t1G2.jpg");
});
</script>

xtal
Jan 9, 2011

by Fluffdaddy
e misunderstood, see below

xtal fucked around with this message at 07:07 on Mar 30, 2012

coronalight
Oct 12, 2006

asdfghjkl;

Suspicious Dish posted:

Using jQuery will probably make your life easier:

code:
<img id="thumb" src="t1G1.jpg" />
<a href="#" id="thumb-switcher"></a>

<script>
$("#thumb-switcher").click(function() {
  $("#thumb").attr("src", "t1G2.jpg");
});
</script>

Thanks for that, is there any alternative to using regexp to change these .jpg links? I will be using a naming scheme for 600 images and 32 different styles but the number at the end will always be 1-9 and correlate to a thumbnail on the page. They will work something like this: 1G9, 3S5, 7G2. First number is style, second character is G or S, for gold or silver, and the last number is 1-9 corresponding to 9 colors. There will be appropriate style numbers and such in the url, if that would make it easier? gently caress, what did I get myself into, hah.


xtal, that would work great if I was using just arrows to navigate through images, but these will be swatches displayed all at once and when clicked, will change the img src no matter what thumbnail was located there previously. I'm definitely being lazy about this, I really haven't dabbled in regexp or anything programming related in years. This will be the only scripting part of this site I'm working on. Honestly I have too many images to edit and static pages to create, if one of you could make something even remotely usable, I'll throw you :10bux: or :20bux:



Maybe something to change just one character in a string? The string will always be the same amount of characters.

coronalight fucked around with this message at 06:01 on Mar 30, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I don't understand. Do you have one image, and want 600*32*2 links to change that image, and want to generate those links with JavaScript?

coronalight
Oct 12, 2006

asdfghjkl;
I have about 30-38 styles of earrings. They have gold and silver styles. Each gold and silver style has 9 colors. That's 30-38*18. The naming scheme can generally be the same amount of characters for all the images: 01G9.jpg, 30S8.jpg. Now, I will have one .php page that will display all of that crap dynamically. The only thing I need to figure out is how to change the one image on the page according to the 9 swatches I'm displaying. They will always be 1-9 and the image src will always be the same length.

Suspicious Dish
Sep 24, 2011

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

scotty posted:

I have about 30-38 styles of earrings. They have gold and silver styles. Each gold and silver style has 9 colors. That's 30-38*18. The naming scheme can generally be the same amount of characters for all the images: 01G9.jpg, 30S8.jpg. Now, I will have one .php page that will display all of that crap dynamically. The only thing I need to figure out is how to change the one image on the page according to the 9 swatches I'm displaying. They will always be 1-9 and the image src will always be the same length.

So, you have a base, and 9 swatch links that swap out the image? I'd have markup like this:

code:
<img src="01G9.jpg" data-image-base="01G" id="thumb">
<a href="#" class="swatch-link" data-swatch-id="1"></a>
<a href="#" class="swatch-link" data-swatch-id="2"></a>
...
<a href="#" class="swatch-link" data-swatch-id="9"></a>

<script>
$(".swatch-link").click(function() {
  $("#thumb").attr('src', $("#thumb").data("image-base") + $(this).data("swatch-id") + ".jpg");
});
</script>
Of course, you can also generate the swatch links with JS as well.

Heavy_D
Feb 16, 2002

"rararararara" contains the meaning of everything, kept in simple rectangular structures

scotty posted:

Maybe something to change just one character in a string? The string will always be the same amount of characters.

As long as you keep the fixed length then you can use the substr function on the string.
code:
original="t1G1.jpg";
replacement=original.substr(0,3)+"2.jpg";

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Anyone know anything about Mocha async testing in Node? I'm finding that a callback called inside of a jsdom is bizarrely muted.

code:
# in app.coffee
exports.get (params, callback) ->
  request {url, followRedirect: no}, (error, response, body) ->
    jsdom.env body, [jquery_url], (errors, window) ->
      callback null, {}

# in test.coffee
describe 'My cool API', ->
  describe '/resource', ->
    it 'does anything, for fucks sake', (done) ->
      expecter = (err, obj) ->
        console.log "This message is logged"
        3.should.equal 5  # ...but this doesn't raise an error
        throw                   # and neither does this
          name:"thing", 
          message: "error"  
        done()                  # and this doesn't end execution, so the test times out.
      
      api.get ["1496", null], expecter
The callback is getting fired, but for some reason it's just not doing anything.

..btt
Mar 26, 2008
Is it possible your 3.should.equal 5 is throwing an exception which is getting caught in an unexpected place? I was under the impression the node devs strongly recommend against using exceptions because the scoping gets rather complex due to async callbacks.

If that line does throw an exception, this obviously explains why nothing after it in the same block executes.

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


Huh, you're right, nothing after the .should call gets executed.

What I put here is actually over-simplified: in the real code, the callback gets passed around to all sorts of functions, and works fine almost anywhere. But if it's in the jsdom.env call OH JESUS gently caress

Just remembered what jsdom.env actually does. :downs:

e: the solution is to wrap the callback in a process.nextTick call. Thank you so much for putting me on the right path. :worship:

Doc Hawkins fucked around with this message at 18:01 on Apr 2, 2012

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
I'm having to do some really nasty stuff to make Oracle WCP play nicely with our js/jQuery validation framework. Due to WCP's less than fantastic way of submiting forms I'm having to remove an onclick function from the submit button, run the validation, re-apply the onclick then fire a click event on the button. I'm aware this is completely insane.

The code which does the last bit looks like this:

code:
					submitButton.attr('onclick', submitOnclick);
					submitButton.off('click');
					var thisButton = submitButton[0];
					if(thisButton.fireEvent) {
						thisButton.fireEvent("onclick");
					} else {
						submitButton.click();
					}
However the .fireEvent(...) doesn't work in IE7. Any ideas on why? Or a better way of doing it? I'm completely baffled by how this is going to work.


e; oh and the reason for using fireEvent like that is that the onclick function uses colons all over the place where it really shouldn't which causes jQuery to blow up.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





This is a Chrome extension question but related to the DOM so any Chrome-only solution is fine.

I am making an extension that manipulates the DOM by adding a DIV into a page on Wikipedia right underneath the last paragraph of a page header. I need to get the actual width of the DIV to match up to the width of the paragraph. However there is usually an infobox on the pages I'm adding onto which has a css property "clear:right" Because of that, the width of the actual paragraph (from clientWidth/offsetWidth) is that of the entire length of the page and does not take into account that the infobox takes up a portion of that width.

Is there any way to get this "true width?" The method I am using right now is kinda clunky so I'd rather not use if I don't have to.

I've attached a picture of the actual width that I want (the line in red) vs what the DOM returns (the orange border area).

Only registered members can see post attachments!

dizzywhip
Dec 23, 2005

I assume you mean the info box has float: right rather than clear: right. Anyways, I just messed around with it a little bit and it looks like if you give your div an overflow: hidden it'll adjust its width to compensate for the info box. I don't know why it does that, it seems like some quirk with the layout engine, but as long as you keep both your width and your height set to auto it shouldn't affect anything else.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Gordon Cole posted:

I assume you mean the info box has float: right rather than clear: right. Anyways, I just messed around with it a little bit and it looks like if you give your div an overflow: hidden it'll adjust its width to compensate for the info box. I don't know why it does that, it seems like some quirk with the layout engine, but as long as you keep both your width and your height set to auto it shouldn't affect anything else.

Yeah meant a float:right although the div does have a clear:right.

Your solution works, unfortunately Chrome still glitches on what I'm trying to do, although using overflow:hidden makes it work much smoother. Thanks!

dizzywhip
Dec 23, 2005

What exactly are you trying to do?

NovemberMike
Dec 28, 2008

Is there an easy way to check that an object is type safe before using it?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

NovemberMike posted:

Is there an easy way to check that an object is type safe before using it?

Yes and no, and I'm not exactly sure what you mean by "an object is type safe".

If you are doing a comparison, then you can use triple equals to check type:
code:
"1" == 1; // true
"1" === 1; // false, string vs. number
0 == false; // true
0 === false; // false


If you mean checking what the type of a given object is, that's tougher. There are no real "types" in javascript, and typeof can lie.

Here's a bigass post that talks about all the stuff I would talk about but since they already typed it out... :effort:

http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript

NovemberMike
Dec 28, 2008

By objects being type safe, I mean that a bird is of type Duck and not Geese. Is it considered best practice to just not check object types to ensure that the code will run?

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

NovemberMike posted:

By objects being type safe, I mean that a bird is of type Duck and not Geese. Is it considered best practice to just not check object types to ensure that the code will run?

Well, you can type hint objects: function doStuff(Duck $bird, Goose $otherbird) { }

And you can also use the instanceof operator (for example, if ($bird instanceof Duck) { }), or the is_a() function.

Suspicious Dish
Sep 24, 2011

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

Golbez posted:

Well, you can type hint objects: function doStuff(Duck $bird, Goose $otherbird) { }

And you can also use the instanceof operator (for example, if ($bird instanceof Duck) { }), or the is_a() function.

Uh, this is the JavaScript thread, not the PHP thread.

You can check for object types in JavaScript if you really want to, but usually you don't do argument checking and make the assumption that if you pass the wrong type of argument your function will error out or return an unexpected value anyway, so why bother.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Suspicious Dish posted:

Uh, this is the JavaScript thread, not the PHP thread.

Jesus christ, that's what I get for posting on 4 hours of sleep. :psyduck: Sorry about that.

dizzywhip
Dec 23, 2005

NovemberMike posted:

By objects being type safe, I mean that a bird is of type Duck and not Geese. Is it considered best practice to just not check object types to ensure that the code will run?

Right, there's usually not really any point in trying to do strict type checking in JavaScript. As long as your object can fly() why does it matter if it's a Duck or a Goose? In general it's better to check for the existence of properties rather than the type of an object, like this:

code:
if (bird.fly) {
    bird.fly();
}
Although even that is usually not necessary if you expect to only be passed in a Bird object. If someone mistakenly passes in another type of object, just let it error out.

An example of a situation where you might actually want to do type checking is if you want to explicitly support that a parameter of a function could be, say, a string or a function that returns a string. You can use type checking to make sure it's a function before you actually call it.

ufarn
May 30, 2009
My JS fu is dreadful, and I am trying to implement this password validator.

say I have an example folder:
code:
index.html
zxcvbn.js
zxcvbn-async.js
And index.html looks like this:

code:
<!DOCTYPE html>
    <head>
        <script type="text/javascript" src="zxcvbn-async.js"></script>
    </head>
    <body>
        <form method='post' action=''>
            <p><label for="id_username">username:</label><input id="id_username" 
type="text" name="username" /></p>

            <p><label for="id_email">email address:</label><input id="id_email"
type="text" name="email" /></p>

            <p><label for="id_password">password:</label><input id="id_password1"
type="password" name="password1" /></p>
                    
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
I change the relevant part of async.js to this:

code:
b.src="zxcvbn.js"
Nothing still happens, when I enter something into the password field. How exactly is this supposed to work?

ufarn fucked around with this message at 00:33 on Apr 18, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
There's nothing automatically that hooks zxcvbn up to existing password fields. You need to do that yourself. Unfortunately, I don't know of any existing projects that do.

ufarn
May 30, 2009

Suspicious Dish posted:

There's nothing automatically that hooks zxcvbn up to existing password fields. You need to do that yourself. Unfortunately, I don't know of any existing projects that do.
I thought as much. Thanks for clarifying it at least.

dizzywhip
Dec 23, 2005

Assuming you're using jQuery, it looks like you need to do something like this:

code:
$("#id_password").keydown(function() {
    var username     = $("#id_username").val();
    var email        = $("#id_email").val();
    var password     = $(this).val();
    var passwordInfo = zxcvbn(password, [username, email]);
    
    // Update your UI to reflect the data in passwordInfo.
});

smug forum asshole
Jan 15, 2005
I think I get almost everything about JS except closures.

Can someone post the best closure resource they know of -- some post/article that made them say "a-ha"? Or some example for us here on the forums about how they work and where they are useful? Maybe we can make it a conversation or something.

smug forum asshole
Jan 15, 2005

smug forum rear end in a top hat posted:

I think I get almost everything about JS except closures.

Can someone post the best closure resource they know of -- some post/article that made them say "a-ha"? Or some example for us here on the forums about how they work and where they are useful? Maybe we can make it a conversation or something.

From Crockford's Good Parts:

quote:

An inner function also enjoys access to the parameters and variables of the functions it is nested within. The function object created by a function literal contains a link to that outer context. This is called closure. This is the source of enormous expressive power.

I already know this, and it makes good sense to me. However, when I read the article on closures at https://developer.mozilla.org/en/JavaScript/Guide/Closures , I get a bit confused. I wonder what in-between step I'm missing here.

Peanut and the Gang
Aug 24, 2009

by exmarx

smug forum rear end in a top hat posted:


My a-ha moment was when I tried binding event handlers in a loop and it spit out the "wrong" value when I triggered each handler.

Click the numbers in this fiddle and use what you know to figure out why 'a' and 'b' are the values they alert: http://jsfiddle.net/AEJdw/1/

Suspicious Dish
Sep 24, 2011

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

smug forum rear end in a top hat posted:

I think I get almost everything about JS except closures.

Can someone post the best closure resource they know of -- some post/article that made them say "a-ha"? Or some example for us here on the forums about how they work and where they are useful? Maybe we can make it a conversation or something.

What don't you understand about closures? What they do? Why they're useful or powerful? Or implementation details, like scope chains and how that messes with garbage collection?

smug forum asshole
Jan 15, 2005
After a little more reading, the part that I don't understand is the idea that the inner function has to be returned to create a closure.

Where did this idea come from?

Suspicious Dish
Sep 24, 2011

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

smug forum rear end in a top hat posted:

After a little more reading, the part that I don't understand is the idea that the inner function has to be returned to create a closure.

That's not true at all. It doesn't have to be returned. Any function which has access to the outer scope's variables from an inner scope is a closure, whether it's used in a loop, as a callback, passed to an other function, or returned.

Of course, programmers largely argue over uninteresting semantics like this, but if you have the basic idea of saving and accessing outer scope even when the function is no longer "called", then you're good.

smug forum rear end in a top hat posted:

Where did this idea come from?

Closures originally came from Lisp.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
A closure only has to be formed when a function outlives its upvalues' scopes. In the specific case of Javascript, since functions are the only scoping mechanism, conceptually closures only have to be created when returning from functions (and the function is either being returned or has been stored in a variable in a surviving scope). In practice, I'd expect most implementations to create the closure at the same time as the instantiation of the anonymous function.

ufarn
May 30, 2009

Gordon Cole posted:

Assuming you're using jQuery, it looks like you need to do something like this:

code:
$("#id_password").keydown(function() {
    var username     = $("#id_username").val();
    var email        = $("#id_email").val();
    var password     = $(this).val();
    var passwordInfo = zxcvbn(password, [username, email]);
    
    // Update your UI to reflect the data in passwordInfo.
});
Thanks.

In general, don't these graders stand a good chance of exposing the passwords to other people, if you don't do it right? I guess it would be fine if it were plug and play with all the intermediate security measures implemented, but putting it up for everyone to implement themselves seems hazardous.

Adbot
ADBOT LOVES YOU

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde

smug forum rear end in a top hat posted:

After a little more reading, the part that I don't understand is the idea that the inner function has to be returned to create a closure.
A function returned from another function is one of the cases where closures are needed. The other is passing a function as an argument. For example, in this code global_var is set to the anonymous function's closure which includes the variable a.
code:
var global_var;
function store(f) {
  global_var = f;
}

function store_one() {
  var a = 1;
  store(function() {return a;});
}
store_one();
Once you have closures in a language it's convenient to use them also when a local function is called locally, they're just not needed in that case.

The problem with referring you to an article on closures is that they're almost invariably Lisp or ML-based.

Gazpacho fucked around with this message at 19:31 on Apr 18, 2012

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