user5075489
user5075489

Reputation:

Defined function is "Not defined"

The following function is defined in the head tags of my page.

<script type="text/javascript">     
$(document).ready(function(){

function greenTab(input){
    if ($input === 'second') {
        $('#green').css({'display':'none'});
        $('#2ndgreen').css({'display':'initial'});
    } else if ($input === 'first') {
        $('#2ndgreen').css({'display':'none'});
        $('#green').css({'display':'initial'});
    }
}   
});
</script>

And I call it in this fashion:

<div class="container">
    <ul class="nav nav-pills">
        <li class="active" onclick="greenTab('first')"><a>1st Green</a></li>
        <li class="active" onclick="greenTab('second')"><a>2nd Green</a></li>                         
    </ul>
</div>

The issue: Firebug says the function is not defined. Desired outcome: For the function to be defined.

Upvotes: 0

Views: 289

Answers (1)

phenomnomnominal
phenomnomnominal

Reputation: 5515

Why is it broken:

The onclick attribute expects functions to be exposed on global scope.

Because you have defined greenTab within the ready function, it is defined within the scope of that function, not on global scope, so it can't be found on the global scope.

How to fix it:

Either:

  1. Expose it globally. (Don't do this)
  2. Add your event listeners through JS, not HTML (Probably do this)

Since you're using jQuery, you should add your event handlers like this:

$('some selector').click(function () {
    greenTab('first');
});

What some selector should be right now is '.container ul li:nth-of-type(1)', but I would suggest adding something to those elements to select on them better, eg:

<div class="container">
    <ul class="nav nav-pills">
        <li class="active first-green"><a>1st Green</a></li>
        <li class="active second-green"><a>2nd Green</a></li>                         
    </ul>
</div>

And then your first selector should just be:

$('.first-green').click(function () {
    greenTab('first');
});

You will need to do the same for the second click handler as well.

Upvotes: 4

Related Questions