Add Javascript function with javascript - javascript

I want to add an event trigger (onClick) with javascript dynamically.-at runtime.
I have a dynamic count of buttons, and on each button click, I need a specific javascript function.
I have the idea to add the javascript functions with javascript.
I tried that with some example:
document.getElementById("trigger").innerHTML = "<script type=\"text/javascript\">function testal() { alert(\"trigger\"); }<\/script>";
if i press on the button with the onClick="testal()":
Error Message: "is undefined"

innerHTML is Not JavaScript.
Indeed that causes a scription injection.

document.getElementById("trigger").onclick = testal;
function testal() { alert('trigger'); }
In case you do not know beforehand what event you'd like to register the handler for (onclick, onkeydown, onkeypress etc) you can do:
var event_type = 'onclick';
document.getElementById('trigger')[event_type] = testal;
See also http://www.quirksmode.org/js/events_tradmod.html

I think you want to use jquery .on method. Try this
$(document).off('click', 'button');
$(document).on('click', 'button', function() {
alert('Executed');
});
If you do not know which event handler to be registered with button click, you can write your logic inside the anonymous handler.

I solved it with
$("#trigger").html("<script type=\"text/javascript\">function testal() { alert(\"trigger\"); }<\/script>");

Related

onclick needs to be double clicked

When using onclick in JavaScript to call the function nowClicked(), I need to click the object twice in order for the alert to show. Below is the code for my function.
function nowClicked() {
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});
};
What is the problem?
Here's what happens the first time you click your button:
nowClicked is called because you've set it up on the button's onclick
nowClicked sets up a jQuery click handler for .object
The code inside the jQuery click handler only runs the next time you click on the button.
It looks like you are mixing up two ways of handling clicks -- one is using the onclick event, and the second is using jQuery. You need to pick one and stick to it instead of using both.
There is no need to put it inside another function,because click is itself handling a callback function.Remove the outer function nowClicked else remove the $('.object').click(function() {.In the second case you may to pass the context as a function argument.
$('.object').click(function() {
$('.object').removeClass("clicked");
var myClass = $(this).attr("id");
alert(myClass);
$(this).addClass("clicked");
e.stopImmediatePropagation();
});

Issue regarding javascript onclick

I am creating a link tag (anchor tag) dynamically using javascript.
There is a javascript function which will be fired by an event and it will create a javascript link.
I have already mentioned the required attributes for the newly created anchor tag using javascript. Now I have also mentioned an onclick event on that anchor tag.
The problem is
that the onclick event is fired during the anchor tag creation. And it is firing for that one time. Next time when I am clicking on the link, I am unable to get my desired result.
javascript code:
function waybill()
{
var mail_link = document.createElement("a");
mail_link.href = "javascript:void(0)";
mail_link.className = 'animated bounceInDown';
mail_link.innerHTML = "Mail Waybill";
mail_link.onclick = abc_test();
var holder_div = document.getElementById("holder");
holder_div.appendChild(mail_link);
}
function abc_test()
{
alert("mail link clicked");
}
I am getting the alert only once and without even clicking.
Please help me.
mail_link.onclick = abc_test() will invoke abc_test and assign its return value to mail_link.onclick.
If you just want to reference the function, and not call it, leave out the ():
mail_link.onclick = abc_test;
Adding event listeners is one of those things that a lot of old browsers are doing in their own way, and it's a bit messy to add support for all of them. Sicnce the question is tagged jQuery, you could do all of this in jQuery and have browser support handled for you:
$('<a/>', {
href: 'javascript:void(0);',
'class': 'animated bounceInDown',
text: 'Mail Waybill',
}).appendTo('#holder').click(abc_test);
The problem is that calling abc_test() will execute the function while using only abc_test will pass a reference to the function. in this case you need to change the line:
mail_link.onclick = abc_test();
with the line:
mail_link.onclick = abc_test;
It's because that you've invoked the function instead of referencing it.
mail_link.onclick=abc_test(); - This will invoke the function while initializing
mail_link.onclick=abc_test; - This will add a reference of the function to onClick, so that it will invoke the function while you click the anchor link.

How to associate onClick with a dynamically generated div with dojo?

I am using dojo 1.9.2, and is trying to attach an onClick function on a piece of HTML code that I created on the fly, like this:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
and then I want to give it an onClick function after, so right below the code I putted:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
For some reason not only this wont work, when I refresh the page the alert "You Clicked It!" would pop up without me clicking anything...
I Have to use this dojo version, it's part of the requirement...
Any idea or suggestion on how I can go about doing this?
Well, dojo is part of javascript, so you can probably use some javascript function, for example:
clickableDiv = "<div id=\"testBtn\">Click Me!</div>";
self.racks.innerHTML = clickableDiv;
document.getElementById('testBtn').onclick=function(){alert("You Clicked It!");};
The code mentioned in the question is correct, except for one mistake. The "onclick" event needs a handler function, not the code directly. So, enclose that alert statement by a function.
connect(this.testBtn, "onclick", function(){alert("You Clicked It!")});
Or a separate function elsewhere can be linked here a handle by passing the function or just name of the function.
function abcd() {
alert('You clicked It');
}
connect(this.testBtn, "onclick", "abcd");//same as connect(this.testBtn, "onclick", abcd);
When providing an event handler (or a callback in general), you have to provide the function as reference. When you use:
connect(this.testBtn, "onclick", alert("You Clicked It!"));
You're actually saying that you want to connect the onClick event handler to the return value of that alert(). What you actually want is like the other answers already explained by wrapping it inside a function that is passed through by reference:
connect(this.testBtn, "onclick", function() {
alert("You Clicked It!")
});
However, since you're using data-dojo-attach-point which is generally used in widgets, you could also define your event handler in a similar way, for example:
clickableDiv = "<div data-dojo-attach-point=\"testBtn\" data-dojo-attach-event=\"onClick: myClickHandler\">Click Me!</div>";
Then you can just write a function called myClickHandler in your widget that shows the alert, for example:
myClickHandler: function() {
alert("You Clicked It!");
}
He's using dojo 1.9.2. connect is deprecated and he should be using on:
on(this.testBtn, "click", function(){
alert("You Clicked It!")
});
Your data-dojo-attach-point won't get picked up in dynamically placed HTML. You would put that in a custom widget template to provide the actual reference to your node/widget. If you did have that element in a template to begin with, you could simply use the attribute on your element:
data-dojo-attach-event="onClick: someFunction"

Javascript Syntax Error

var dayNumberCell = doc.createElement('td');
dayNumberCell.className = 'days_link';
dayNumberCell.setAttribute('onclick', function(scope) {
var bindScope = function() {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
};
return bindScope;
}(this));
The above code generates tds onclick event listener. and the generated code looks like
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
}">15</td>
By clicking on TD I get syntax error message.
How should I write my function that the specified code executes and also have no syntax error.
Thanks in advance.
You put your function definition inside a string literal. It's expecting code and all it has is text.
You should rewrite your onclick handler as follows:
dayNumberCell.onclick = function(e) {
var target = e.target || e.srcElement;
target.changeDate(target, target.id);
target.returnDate(target.month, target.year);
return false;
};
I don't understand why you would try to set the inline click handler from an external js file. You took the right step to remove inline click handlers from your html, but when you set the click handler from an external script, you should not be setting the onclick attribute.
In addition to the way I highlighted, you could use the w3c and microsoft event handlers so that you can attach multiple onclick events to the same element. However, this is a more complicated approach since different browsers handle it differently. This will suffice as long as you don't plan to have other onclick handlers attached to the same cell.
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);}">15</td>
Have you tried outside the function?
<td class="days_link" onclick="scope.changeDate(this, this.id);scope.returnDate(scope.month, scope.year);">15</td>
if that don't work, try it on your javascript file, and there, yes, with a function.
Perhaps you would prefer not to use any javascript libraries, but I would highly recommend using the YUI Event utility for this.
Dustin Diaz has a great article that explains how it would simplify this for you.
http://www.dustindiaz.com/yahoo-event-utility/

Changing the onclick event delegate of an HTML button?

How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event

Categories