I've wrote this code seems correct but appear this error :
Uncaught ReferenceError: show is not defined
This is my simple code:
(function ($) {
$(document).ready
(
function () {
$('.mapban').parent().jclip(0, 0, 1060, 750);
$('#mapplane').draggable();
$('#mapplane > div ').css( 'display', 'none' );
$('.button').attr('onclick','show(this)');
function show(button){
alert(button);
}
}
)
})(jQuery)
3 Answers 3
It's not working because the show() function is not in the window scope, it's inside the scope of the document.ready function and the uneccessary IIFE, while the element's onclick handler is trying to call it from the window(global) scope.
Better just use jQuery
jQuery(function($) {
$('.mapban').parent().jclip(0, 0, 1060, 750);
$('#mapplane').draggable();
$('#mapplane > div ').hide();
$('.button').on('click', show);
function show(){
var button = this;
alert(button);
}
});
7 Comments
$('.button').on('click', show()); and not $('.button').on('click', show); ?Element attributes like onclick are executed in the global scope. The show function does not exist in the global scope. You need to attach a reference to the function's onclick property, not not a string to its attribute. In jQuery you can do this with the on method (among others):
$('.button').on('click', show);
function show(){
alert(this);
}
Comments
You must declare declare the function show outside of the call to $(document).ready(...);
The way you have it declared now, the scope of the function is limited the execution time of that function and cannot be seen by the page.
onclickattribute with jQuery?! You have easy access to the right way to do this (attaching non-exclusive event handlers).