Skip to content
Advertisement

JavasScript function undefined

i’ve got an html element declared as so:

<div id="taskImage" runat="server">
   <a href="javascript:void(0);" onclick="switchViews('div<%# Eval("proId") %>', 'one');">
      <img id='imgdiv<%# Eval("proId") %>' alt="Click to show/hide tasks" border="0" src="..."/>
   </a>
</div>

and the javascript function switchViews is declared post-html as such:

function switchViews(obj, row) {

      var div = document.getElementById(obj);
    var img = document.getElementById('img' + obj);

    if (div.style.display == "none") {
        div.style.display = "inline";

        img.src = "../../images/icons/delete.png";

    }
    else {
        div.style.display = "none";

        img.src = "../../images/icons/add.png";

    }

}

when I click on the html element, i get thrown a JS error saying “Object Exepcted”, and in the google chrome script debugger it says that switchViews is undefined. Why would it think that switchViews is undefined and how would I go about fixing it? For the record I have tried it with the javascript declared before the html and with the switchViews call in the href attribute but it all ends the same.

EDIT : to clear something up, by post-html and pre-html i mean before and after i write out the html elements. so post would be like

<div>
   <!-- All my html stuff -->
<div>
<script type="text/javascript">
   <!-- All my Javascript -->
</script>

and pre would be the reverse of that

Advertisement

Answer

Question

At the point where <a href="javascript:void(0);" onclick="switchViews(... etc is encountered by the browser, does the function switchViews exist or is it undefined?

Answer

The code defining switchViews appears after, so at that time switchViews is undefined.

Solution

Place your <script> before the rest of the HTML or attach the event listener in your JavaScript instead of inline. This can be done via addEventListener or using jQuery and may require you to loop over your HTMLElements of interest.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement