triggering a controls event via javascript - javascript

im trying to figure out how to trigger a control's event from a javascript function (without touching the actual control itself)
say i have this textbox...
<input type="text" value="" id="my_textbox" onclick="alert('!');" />
then say i was trying to call its onclick event via javascript...
function TriggerTextboxOnClick()
{
//... call the onclick event of 'my_textbox'
}
p.s. I'm not actually trying to pop-up an alert box, I've simplified it for illustrations sake

You could just call document.getElementById("my_text_box").onclick(), see also: http://jsbin.com/ixuwo4.

Bouke's solution works.
In general, you may want to do somthing like this instead as a good practice:
<input id="my_textbox" onclick="my_textbox_onClick()" />
...
function commonLogic() {
// Logic that's common to both the onclick event and the *other* code
}
function my_textbox_onClick() {
// This function should only contain logic that is triggered by a click on the textbox
commonLogic();
}

couple of things:
doing someting via the inline onclick attribute as you've got in your example is not the best way. Attaching event handlers in script blocks is better for accessibility and cleaner, maintainable code.
if you're using a library like jQuery already then let the library handle it for you. see code below:
//assuming using jQuery
$('#my_textbox').click(function(){
//do stuff here
});
//firing the event in some other function
function TriggerTextBoxOnClick(){
//do stuff here
$('#my_textbox').click();
}
Ref: More info on inline click handlers: http://www.quirksmode.org/js/events_early.html
You can do the same as the jQuery code with plain old js too:
element.onclick = doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);
Read this for more info on doing this with plain JS: http://www.quirksmode.org/js/introevents.html

Related

Can we name an event handler in Javascript?

I was messing around with jQuery and event handlers, when I noticed this:
That uses jQuery, and without it:
How does the popup get a bar saying jQuery? Do browsers have integrated jQuery support to detect that? Or is there some way to name event handlers? I want to have my event display some other text, like how jQuery does.
NOTE: I don't want to use jQuery, as I want to know how jQuery does it.
I am not sure about what you are trying to do, but in Javascript you can always name functions
Example:
function myEventHandler(event) {
alert('event handler');
}
myEventHandler is the name of the function.
Hope this helps a little,
best,
Carsten
You can have custom names for your events if you want. We can use the trigger function for the same purpose.
Suppose you want to raise myEvent on <div id="my_div">.
We can simply
$("#my_div").trigger('myEvent');
and have a listener for the event:
$("#my_div").on('myEvent', function(event){
//Event handler
});
You can find some good documentation here -
https://learn.jquery.com/events/introduction-to-custom-events/
And this SO answer covers it thoroughly -
Custom events in jQuery?

Simulate click in javascript [duplicate]

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.
I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.
I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.
EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined.
You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Why not just the good ol' javascript?
$('#element')[0].click()
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
Easy! Just use jQuery's click function:
$("#theElement").click();
Try this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

How to use same jquery fuunction on a multiple buttons that are created in a loop?

Im creating the same button in a loop as long as there is a certain condition, and I want to run the same jquery event handler for those buttons.
The problem is that the event handler only works for the first button generated.
My button is generated like this:
<?php while($row_c= mysqli_fetch_array($result_comments))
{ ?>
<button name="comment" id="comment" class="button_comment" value="Post">Post</button>
<?php } ?>
and the jquery im using is this:
$('.button_comment').click(function()
{
//some staff thats done here
});
What should do, so that the event handler works for all buttons that are generated?
Thank you
Your jQuery should work. Note that your buttons form invalid HTML/DOM: The id on an element must be unique. But since you're also using a class (which doesn't have to be unique), and that's what you're using in your jQuery selector, that works: Live Example | Source
Perhaps when you were trying it and it wasn't working, you were using $("#comment").click(...), which would not work, because of the id issue.
Check in firebug:
var buttoncomments = $('.button_comment');
console.log(buttoncomments);
Bind the control in question to a variable so you're certain that it's that one you're working with.
$('.button_comment').click(function()
{
var that = $(this);
"What should do, so that the event handler works for all buttons that are generated?"
A Fiddle would be a good way to show us the context of your problem ;)
Your code is valid because it will attach a handler to every element having 'button_comment' as a css class
Did you put this code inside a dom ready function ?
$(function(){
/* code here */
});
You can use event delegation
This mean you have to attach the event listener to the first common ancestor of those buttons. This is a good choice when many elements have to trigger the same routine an even more if some of them may be added to the DOM in the futur via AJAX (This keep the page from having to many event handlers attached to it)
Delegation syntax
// Event delegation
$( "#Ancestor").on("click", '.button_comment', function() {
alert( $( this ).val() );
});
Take the ID off from your php code. Remember ID's should be unique elements. Also, change your jquery from:
('.button_comment').click(function()
{
//some staff thats done here
});
to
('.button_comment').on('click', function()
{
//some staff thats done here
});
The on event will perform what you tell it to do at the time you tell it to do, so it does it pretty much at runtime. If you use your previous code, the element must exist at page load time for it to work.

how to call onclick on an external JS file? w/o jquery

I'm working on some web very simple drag and drop game using html5 and javascript. After they drag the elements I have a button that verifies either the arrange is correct or not. My verify function is on an external JS file and I'm calling it using onclick inside the input tag. It works, however my boss doesnt want event handlers to be shown on the html. I'm just starting with javascript so is there a way to call an onclick event without using the onclick on a tag in the html file?
Ive read you can do it easily with jquery, but can you use it without jquery?
You can bind a click event to the button like they do in jquery:
document.onclick = function(event) {
var targetElement = event.target;
if ( targetElement.className == "myButton" ) {
// do something
alert("my button clicked");
}
};
This example works on a class name but you can change that to any attribute you want on the button or something else.
There are two meanings I got from your question.
1) You want to call onclick event of an item on particular thing.
For this you can directly call the methods you want to call onclick.
2) not showing on html that it has onclick. For this you can use something like this:
document.getElementById('id').onClick = "yourMethod()";
Hope it helps.

Is there any way to use javascript (jquery) to make an element behave **exactly** as if it was clicked (a unique situation)

I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.

Categories

Resources