...

View Full Version : "function not defined" error



Dee99
11-08-2010, 03:06 AM
I always get "function not defined" when buttons are clicked - can anyone tell me what's wrong with this code ?
[CODE]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>Show and Hiding Images</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

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

function showImage(){
$('#imgSwitch').show();
}
function hideImage(){
$('#imgSwitch').hide();
}
});//ready
</script>
</head>
<body>
<h1>Showing and Hiding Images</h1>
<p>This is an example of showing and hiding images.</p>

<IMG id="imgSwitch" SRC="./images/grid/SortASC.gif" WIDTH="50" HEIGHT="40" >

<form>
<input type="button" value="show" onclick="showImage()"></input>
<input type="button" value="hide" onclick="hideImage()"></input>
</form>

</body>
</html>
[Icode]

SB65
11-08-2010, 12:09 PM
Either remove your functions from $(document).ready - you're not actually doing anything when the DOM is ready here, or, better because less obtrusive, get rid of your onclick attributes and add click events within $(document).ready to run your function code.

As it stands at the moment your inline onclick attributes are loading before $(document).ready and hence the functions are not defined. Try this and note the order in which the alerts fire:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>Show and Hiding Images</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

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

alert('setting up functions now');

function showImage(){
$('#imgSwitch').show();
}
function hideImage(){
$('#imgSwitch').hide();
}


});//ready
</script>
</head>
<body>
<h1>Showing and Hiding Images</h1>
<p>This is an example of showing and hiding images.</p>

<IMG id="imgSwitch" SRC="./images/grid/SortASC.gif" WIDTH="50" HEIGHT="40" >

<form>
<input type="button" value="show" onclick="showImage()"></input>
<input type="button" value="hide" onclick="hideImage()"></input>
<script type="text/javascript">alert('onclick events established');</script>
</form>

</body>
</html>

Dee99
11-08-2010, 06:02 PM
that was it

--thanks

A1ien51
11-09-2010, 03:27 AM
Never use onclick="showImage() on the element, that is very bad practice, especially when you are using a library that makes it as easy as pie to add events the correct way.


$("#ElementId").click( function(){ $('#imgSwitch').show(); } );


Eric



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum