Issue regarding javascript onclick - javascript

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.

Related

I'm trying to add an OnClick function to an element after page load and then make that OnClick function change the text of a separate element

I'm trying to add an OnClick function to 4 elements element on page load and then make those OnClick functions change the text of a separate element. I tried creating a function called AddClick that specified the elementID and then sets an OnClick attribute and seperate function. (I did this four times for each element I want to have the new function activated on click.
I then asked the AddClick to run on page load.
Then I created the functions that would replace the old text of the seperate element. (These should be set to run when the elements are clicked.
Sorry in advance if this was the wrong approach/If I'm not clear. First time posting on here, any help appreciated.
For the HTML the text I am trying to alter is within a div with an ID, but the h4 does not have a specific ID and I cannot add one.
Here is the JavaScript I tried to implement:
<script type="text/javascript">
function AddClick(){
//Name & Number
document.getElementById("o_5794738").setAttribute('onclick', "NewText()");
//Number
document.getElementById("o_5794733").setAttribute('onclick', "OldText()");
//Name
document.getElementById("o_5794723").setAttribute('onclick', "OldText()");
//None
document.getElementById("o_5794728").setAttribute('onclick', "OldText()");
};
window.onload = AddClick;
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>New Text</h4>";
}
function OldText() {
document.getElementById("pt_fc_775338").getElementsByTagName(h4).innerHTML = "<h4>Old Text</h4>";
}
Any help is much appreciated.
You can try this:
document.getElementById("demo").onclick = function() {myFunction()};
I found this example on https://www.w3schools.com/jsref/event_onclick.asp
No need to add click event using load you can directly add the click event using .addEventListener (by the way .setAttribute is not for adding any event)
Simply use .addEventListener like this :
document.getElementById("o_5794738").addEventListener('click', NewText);
Read this for more info about .addEventListener()
Here is the demo snippet below :
document.getElementById("o_5794738").addEventListener('click', NewText);
function NewText() {
document.getElementById("pt_fc_775338").getElementsByTagName("h4")[0].innerHTML = "New Text";
}
<button id="o_5794738">Click Me!</button>
<div id="pt_fc_775338">
<h4></h4>
</div>

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();
});

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"

Add Javascript function with 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>");

How to make an <a> tag element to trigger multiple functions with javascript/jquery

There is a link in my webpage, the link itself triggers a function that I could not modify, but I want to make the link, when clicked, also calls another JavaScript function at the same time or preferably after the first function is done. So one click to call two functions...could it be implemented? Thanks
<a title="Next Page" href="javascript:__doPostBack('Booklet1','V4504')">Next</a>
is the sample tag I want to modify, how could make it also call "myFunc" at the same time or preferably after _doPostBack is done.
P.S. the function parameter for _doPostBack such as V4504 is dynamically generated by the ASP user control. So I cannot simply treat it as a static function and bind it with another. I think I could only append some function to it? Unless I parse the whole page first and extract the function name with its current parameters...Since every time I click the link, the parameter such as V4504 changes its value....
Thanks!
You should be able to attach multiple event handlers to a single anchor tag, either with .onclick or .addEventListener('click', function)
https://developer.mozilla.org/en/DOM/element.addEventListener
You can attach a handler to an element click event using plain Javascript in such a way:
function hello()
{
alert("Hello!")
}
var element = document.getElementById("YourAElementID");
if (element.addEventListener)
{
element.addEventListener("click", hello, false);
}
else
{
element.attachEvent("onclick", hello);
}
It supprots all common browsers.
Yes, you can do this MANY ways (I use both $(this) and $('identifier') as you don't say how the functions are bound) :
$(this).click(function(){
my_function_1();
my_function2()
});
Or
$('my element').click(function(){
my_function_1();
});
$('my element').click(function(){
my_function_2();
});
Or, if the functions reside on another object:
$(this).click(function(){
my_function_1();
$('#other_element_id').trigger('click'); //there are a bunch of syntaxes for this
});
Sans JQuery, you can use:
var myObj = document.getElementById('element name');
myObj.addEventListener('click', function(){
alert('first!');
});
myObj.addEventListener('click', function(){
alert('second!');
});
Clicking will result in two sequential alert prompts

Categories