Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is javascript namespace polluted?

I do not have a good grasp of the js namespace and am WAGing* re the title, but that's one of my guesses about what's happening.

  • WAG = Wild Guess

My app is crashing (dramatically); trying to figure out why. In fact, after 3 Q/A pairs, it blows up the entire Chrome tab..! I'm beginning to suspect I've done something wrong in my code...

Warning: Save your browsing session before running these jsFiddles. (In Chrome, the jsFiddle only blows up its own tab but I can't comment on other browsers)

jsFiddle One
jsFiddle Two - dupe in case jsFiddle One blown away

Please help me to understand exactly which spectacular moronism I've committed today.

HTML:

<div id="result">
    <div class="truth tr0"><h2>---</h2></div>
    <div class="truth tr1"><h2>answer to one</h2></div>
    <div class="truth tr2"><h2>answer to two</h2></div>
    <div class="truth tr3"><h2>answer to three</h2></div>
    <div class="truth tr4"><h2>answer to four</h2></div>
 </div>   
<div id="replaceLink">
    <div class="youcould yc1">
        <a href="#2"><h2>QUESTION ONE</h2></a>
    </div>
    <div class="youcould yc2">
        <a href="#3"><h2>QUESTION TWO</h2></a>
    </div>
    <div class="youcould yc3">
        <a href="#4"><h2>QUESTION THREE</h2></a>
    </div>
    <div class="youcould yc4">
        <a href="#5"><h2>QUESTION FOUR</h2></a>
    </div>
    <div class="youcould yc5">
        <a href="#6"><h2>THANK YOU</h2></a>
    </div>
</div>

<div id="response"></div>
<input type="button" id="mybutt" value="Start Test" />

Javascript/jQuery:

var cnt = 0;
var window = {};
window.arrDone = [];

function nextQues() {
    if (window.arrDone.length == 4) return 5;

    success = 0;
    while (success == 0) {
        nn = Math.floor(Math.random() * 3) + 1;
        if (window.arrDone.indexOf(nn) == -1 && nn != 5) {
            success++;
            window.arrDone.push(nn);
        }
    }
    return nn;
}

$('.youcould, .truth').hide();
$('.tr0').show();

$('.youcould').click(function() {
    $(this).hide();
    thisA = window.arrDone[window.arrDone.length -1];
    $('.tr'+thisA).show();
});

$('.truth').click(function() {
    $(this).hide();
    nextQ = nextQues();
    $('.yc'+nextQ).show();
});

$('#mybutt').click(function () {
    $(this).hide();
    $('.tr0').hide();
    nextQ = nextQues();
    $('.yc'+nextQ).show();
});
like image 547
cssyphus Avatar asked Jul 10 '26 02:07

cssyphus


1 Answers

My guess would be

var window = {};

window is special, so creating a global variable named window is begging for trouble.

like image 188
Joe Enos Avatar answered Jul 14 '26 11:07

Joe Enos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!