Reputation: 31
When I run this javascript, I get applyBefore is not defined. I simply have 2 buttons with onclick="applyBefore();" in HTML. Here is JS:
(function (){
$("div").css("border", "1px solid black");
$("div").css("margin-top", "100px");
$("div").css("margin-left", "50px");
$("div").css("width", "100px");
var input = $("input[text]").value;
var btnLeft = $("#btnLeft");
function applyBefore() {
console.log("ne staa");
var content = document.createElement("p");
content.appendChild(document.createTextNode(input));
$("div").prepend(content);
content.before$("#mainDiv");
console.log("ne staa");
}
function applyAfter() {
}
}());
Upvotes: 0
Views: 70
Reputation: 149020
The problem is that you've only defined those functions within the scope of the outer function. If you want to use it to bind an event directly in html as in <a onclick="applyBefore();">
, you'll have to declare them outside that function:
function applyBefore() {
var input = $("input[text]").val(); // Note the use of val()
...
}
function applyAfter() {
}
(function (){
$("div").css("border", "1px solid black");
$("div").css("margin-top", "100px");
$("div").css("margin-left", "50px");
$("div").css("width", "100px");
}());
Or better yet, get rid of the html event binding and do it in JavaScript:
(function (){
$("div").css("border", "1px solid black");
$("div").css("margin-top", "100px");
$("div").css("margin-left", "50px");
$("div").css("width", "100px");
input = $("input[text]").val(); // Note the use of val()
var btnLeft = $("#btnLeft");
function applyBefore() {
...
}
function applyAfter() {
...
}
$("#myElement").on('click', applyBefore); // bind event here
}());
Also, if you want to get the value of an input element(s) returned by $("input[text]")
you should use $("input[text]").val()
or possibly $("input[text]")[0].value
instead of just $("input[text]").value
.
Upvotes: 1
Reputation: 943556
You have defined the function inside another function. It therefore exists in the scope of that function and not the global scope.
Don't use onclick
attributes. Bind your event handlers with JavaScript, and do so inside the anonymous function that you are using to limit the scope of your other variables.
Since you are using jQuery:
jQuery('button').on('click', applyBefore);
You probably want to get the value of the input correctly too (the value
property exists on DOM node objects, you have a jQuery object so use the val()
method) and to get that value when the button is clicked instead of storing the value the document has when it is loaded.
Upvotes: 6