I was trying to make a function in JavaScript that could set the onClick property of an HTML button.
So, say I have this as my function:
function myFunc(action){
document.getElementById('mybtn').setAttribute("onClick", action);
}
That would set mybtn's attribute onClick to the contents of the variable action (which should be a function).
So, if I ran the function like this:
myFunc(function(){
alert("Hello, World!");
});
Then the variable action would be set to
function (){
alert("Hello, World!");
}
If I ran myFunc as shown, it would successfully add the contents of action to the button's onClick attribute. The only problem is, if I click the button after myFunc has been run, I just get an error. It says:
Uncaught SyntaxError: Unexpected token (
I think that's because in the onClick attribute, you can't have a new function defined.
How can I get only what's inside the function in the variable action?
You can add an event listener instead of altering the attribute for onclick like this:
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
myFunc(function() {
alert('foo');
});
<button id="mybtn">Foo</button>
Attribute values can only be strings. Your function is stringified to something like
'function(){ alert("Hello, World!"); }'
And then the event handler parses it as a function body. That means it will be treated as a function declaration, but function declarations require a name. Therefore, yes, there is an unexpected (: there should be a name before it. Firefox provides a more meaningful error
SyntaxError: function statement requires a name
function() {
alert("Hello, World!");
}
If you really want to use event handler content attributes, you should pass a string containing only the body of the function:
myFunc('alert("Hello, World!")');
function myFunc(action){
document.getElementById('mybtn').setAttribute("onclick", action);
}
myFunc('alert("Hello, World!")');
<button id="mybtn">Click me</button>
But I strongly discourage event handler content attributes. Instead, use event handler IDL attributes:
function myFunc(action) {
document.getElementById('mybtn').onclick = action;
}
function myFunc(action) {
document.getElementById('mybtn').onclick = action;
}
myFunc(function (){
alert("Hello, World!");
});
<button id="mybtn">Click me</button>
Or even better, event listeners
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
function myFunc(action) {
document.getElementById('mybtn').addEventListener('click', action);
}
myFunc(function (){
alert("Hello, World!");
});
<button id="mybtn">Click me</button>
html onclick event attribute expects a string, not a function. You can defined function to be called then pass string referencing function to myFunc
<div id="mybtn">click</div>
<script>
function myFunc(action) {
document.getElementById("mybtn").setAttribute("onclick", action);
}
function clickHandler() {
alert("Hello, World!");
}
myFunc("clickHandler()");
</script>
Related
I am trying to execute code when the onmuseout/onload events occur, but for some reason my code is not running??
function outFunction() {
document.getElementById("mouseout").alert("Don't Leave!")
}
function myFunction() {
document.getElementById("hi").innerHTML = "This DIV is loaded."
}
<div onmouseout="outFunction()" , id="mouseout">DIV</div>
<div id="hi" onload="myFunction()"></div>
outFunction:
The alert function is on window (or the implicit global object). It is not on the returned div element (which is an instance of HTMLDivElement).
Change your function to this:
function outFunction() {
window.alert("Don't Leave!")
}
Note that this also works (the same alert function is being used, because window is the global object):
function outFunction() {
alert("Don't Leave!")
}
myFunction:
onload is not defined on HTMLDivElement. You should use document.addEventListener( 'DOMContentLoaded', handler ) instead.
Change your HTML and JavaScript function to this:
<div id="hi"></div>
function myFunction() {
document.getElementById("hi").innerHTML = "This DIV is loaded."
}
document.addEventListener( 'DOMContentLoaded', myFunction ); // Do NOT put parentheses! i.e. don't put `myFunction()`, just put `myFunction` - because you're passing a function-reference, not a function-call.
<div id='example' data-fn='functiona'>OK</div>
$('#button').click function(){
$('#example').attr('data-fn', functionb');
});
function functiona(){
console.log('functiona');
}
function functionb(){
console.log('functionb');
}
$('#example').click(function(){
// execute function currently stored inside data-fn attribute
});
Probably everything is clear.
I need dinamically change the function which will be executed by clicking on example.
The current function should be stored inside data-fn.
Any help?
What you want to do is described in Can you set a javascript function name as an html attribute?
But I suggest that you solve it that way:
$('#button').click(function() {
$('#example').off('click.myNamespace') // remove the previously assigned callback
.on('click.myNamespace', creatClickCallback(functionb)); // register the new callback
});
function functiona() {
console.log('functiona');
}
function functionb() {
console.log('functionb');
}
function creatClickCallback(functionToCall) {
return function(evt) {
functionToCall()
}
}
$('#example').on('click.myNamespace', creatClickCallback(functiona));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example'>OK</div>
<div id='button'>button</div>
This way you ensure that you do not accitantily name a function the wrong way, because you pass it as an actual reference to that function instead of a string.
Couldn't you just store the function name, then when you click you check which function is then call it and update the function to which one you want?
Something like this:
function functiona(){
console.log('called functiona');
document.body.style.background = '#aaa';
}
function functionb(){
console.log('called functionb');
document.body.style.background = '#fff';
}
$('#example').on("click", function(ev){
var func = $(ev.target).attr('data-fn');
console.log(func);
window[func]();
});
$('#changer').on("click", function(ev){
//HERE you can change the function will be called based on what you want
//Here I just changed it with a simple if...
var fn = $("#example").attr("data-fn");
if (fn == 'functiona'){
$("#example").attr("data-fn", "functionb");
}else {
$("#example").attr("data-fn", "functiona");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='example' data-fn='functiona'>Click Me to call function</div>
<button id='changer'>Change Function</button>
Here, the global variable window have your functions stored, so going through it by it's name and calling it, should work, if this name exist as a function window[stringOfFuncionName]();
This is not the best way of doing what you need (actually you didn't let completely clear your final objective), but this maybe can help.
In Console I got following error using e.preventDefault() method
I used e as a function parameter
function function1(e){
e.preventDefault();
}
1533 Uncaught TypeError: Cannot read property 'preventDefault' of undefined.
Called function1 like
Click Me
You have to pass event in the used function:
function1(event); // where you called it
For example:
Click Me
Make sure you call this function within an event handler. Such as :
$(document).click(function(event){
function1(event);
});
I remove event from function and invoke function in this way:
<button class="btn btn-primary" runat="server" id="btnSave" type="submit"
onserverclick="btnSave_OnServerClick" onclick="return
jsFunction();">Save</button>
In JavaScript:
function jsFunction() {
alert('call');
if ($('#form1').bootstrapValidator('validate').has('.has-error').length) {
alert('SOMETHING WRONG');
} else {
alert('EVERYTHING IS GOOD');
__doPostBack('<%=btnSave.UniqueID%>', '');
}
return false;
}
You are writing the function wrong. Suppose you are using function on a particular button click having id as 'clickBtn' then you need to write function like this.
$("#clickBtn").on("click", function(e){
e.preventDefault();
});
You failed to pass the event as a parameter in your in luck event in the html.
So it should be written as the sample below:
Click Me
function function1(event){
e.preventDefault();
}
i try to pass paramater to function. When i click the div it will alert the paramater that i pass
i have 2 file
index.html
script.js
here's what i try
Example 1
index.html
<div id="thediv" >
script.js
window.onload = initialize;
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = myFunction(" something ");
}
//end of bind
//function
function myFunction(parameter) { alert( parameter ) };
//end of all function
the trouble is the function its executed without click
Example 2
index.html
<div id="thediv" onclick="myfunction('something')" >
script.js
function myFunction(parameter) { alert( parameter ) };
yap its done with this but the trouble if i have many element in index.html it will painful to read which element have which listener
i want to separate my code into 3 section (similiar with example1)
the view(html element)
the element have which listener
the function
what should i do? or can i do this?
(i don't want to use another library)
Placing () (with any number of arguments in it) will call a function. The return value (undefined in this case) will then be assigned as the event handler.
If you want to assign a function, then you need to pass the function itself.
...onclick = myFunction;
If you want to give it arguments when it is called, then the easiest way is to create a new function and assign that.
...onclick = function () {
myFunction("arguments");
};
Your first solution logic is absolutely ok .. just need to assign a delegate ... what you are doing is calling the function .. So do something like this ...
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function () { myFunction(" something "); };
}
//end of bind
Instead of assign you invoke a function with myFunction();
Use it like this
//bind event listener
function initialize(){
document.getElementById("thediv").onclick = function(){
myFunction(" something ");
}
}
I have a function in html:
<script>
function update_x(obj) {
...
}
</script>
and I call it on click in html with onclick="update_x(this)" (inside of <div class="aaa">).
How can be the same achieved in jquery? I've tried some stuff, like:
$('.aaa').click(update_x);
});
and
$('.aaa').click(function () {
$(this).update_x(1, false);
});
neither won't work...
This would be equivalent:
$('.aaa').click(function () {
update_x(this);
});
But you don't need to use that. Just change your function to
function update_x(event_obj) {
// 'this' will be the clicked object automatically
// plus, you have further info in the event object
}
$('.aaa').click(update_x);
Make sure $('.aaa').click(update_x) is called after the element with class "aaa" exists in the DOM. You can wrap that code in a document.ready handler, or use event delegation.