I have a checkbox with the following code:
<input type="checkbox" id="check" onclick="function(this);" checked="checked" />
But in same cases I want the call to be made on page load.
How do I replicate the "this" manually?
I tried adding onload="function(this);" to the input, but that didn't work.
And if I just call "function();" on page load then the function naturally doesn't work.
So it'd be great if I could manually call a function like: function(htmlElement[check]); or whatever "this" constitutes.
Hope I've made myself clear :)
In your case, this will refer to the input element. Since that element has an ID, you can easily get a reference to it with the getElementById method):
yourFunction(document.getElementById("check"));
You can place that in the onload attribute of the body element, but ideally, stop using inline event handlers and use the addEventListener method instead.
Try with:
onload="function(document.getElementById('check'));"
You could get the element via id, and do it in the window.onload callback function.
window.onload = function () {
yourFunction(document.getElementById('check'));
}
to the extent of my understanding, onload only works on <body> tag
What you might want to try, is this:
$(document).ready(function() {
// Handler for .ready() called.
});
source:http://api.jquery.com/ready/
You can use something like this:
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
yourFunction(document.getElementById("check"));
}, false );
You must avoid using:
window.onload = function() {
}
because in this way you will overide attached to onload functions (if there is already attached to onload with this way). This method is very good when you want to have JavaScript in separate file (the best solution).
Related
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.
I am binding a click event with an elementid like this:
$("#a").bind({click : dosomestuff });
After that when I am trying to trigger it with the .trigger() function like this:
$("#a").trigger("click");
The function is not triggering. Can anybody tell me the problem?
A few things that could be wrong in order of likelihood:
You didn't put this code inside $(function() { ... });, so the element wasn't ready yet.
The element doesn't exist (you can check this via your developer console)
jQuery isn't loaded
You're deliberately creating the element later; use .on() instead of .bind().
You may don't put you code within
$(function() {
});
or
if your #a in dynamic then try
$('document').on('click', '#a', dosomestuff); // it would be better to
// replace document with
// `#a`'s parent
if you are trying to bind click event to an anchor tag then you should use
$("a").bind('click',function(){
//do your stuff here
} );
I have a simple click handler that will alert its link's href as in:
<a id="link" href="http://www.google.com">Google</a>
$('a#link').on('click', function() {
alert($(this).attr('href'));
});
How can I separate the function (and how to call it) so that it can be called by another click handler?
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
// I'd like a#another-link to be able to call that same function above.
<a id="another-link" href="http://www.microsoft.com">Microsoft</a>
$('a#another-link').on('click', /* How to call showHref? */);
Thanks.
You could do something like this:
function showHref() {
alert($(this).attr('href'));
}
$('a#link').on('click', showHref);
$('a#another-link').on('click', showHref);
In this code, this inside the showHref will refer to the link being clicked, since jQuery makes sure that the link being clicked is the calling context (using .call() which you may want to read up on). If, however, you were to manually call showHref, this would not refer to your link.
If you want a definition of showHref that you could both call manually, and bind through jQuery, it would probably be neatest to pass the reference as a parameter:
function showHref(link) {
alert($(link).attr('href'));
}
In that case, you'd have to adjust your listeners as follows:
$('a#link').on('click', function() {
showHref(this);
});
But it is also possible to combine selectors:
$('a#link, a#another-link').on('click', function() {
alert($(this).attr('href'));
});
You can put the function logic into a reference like this:
var handler = function () {
alert($(this).attr('href'));
};
Then you can use that reference to initialize event listeners:
$('#link').on('click', handler);
Of course, you can reuse that.
$('#some_other_link').on('click', handler);
Or call that yourself outside of an event handler context (which normally wouldn't make sense if you're fashioning an event handler function --- but it can be done with lambdas in general).
handler();
But if you want to just trigger the event on an element, you should call the corresponding event trigger function.
$('#link').click();
// or
$('#link').trigger('click');
You wrote:
function showHref() {
/* What to do here because $(this) won't resolve to <a> anymore. */
}
Umm, actually, yes it will. That's exactly the promise made by DOM events and also event handlers registered with jQuery.
FWIW, the content should just be:
alert(this.href)
There's really no need to invoke jQuery just to get the element's href attribute.
I'm a bit confused with jQuery's .click() event. I'm trying to use the event on an image inside a span. This is the line of HTML containing the span and image.
<span class="content-message-element"><img class="content-message-icon" src="./images/icon_close.png" alt="Close Message" /></span>
As you can see, the image has the class 'content-message-icon'. I've used this in my jQuery code (by the way - I have jQuery 1.7.1 included) but nothing happens ; the event is not triggered at all.
Is the .click() event limited to certain types of elements?
<script type="text/javascript">
$(".content-message-icon").click(function() {
alert("Handler for .click() called.");
});
</script>
This is my jQuery, any help is appreciated.
The click event should work fine. Try putting in the document ready code, like so:
$(function() {
$(".content-message-icon").click(function() {
alert("Handler for .click() called.");
});
});
Example with jsFiddle: http://jsfiddle.net/vGPfu/1/
it may happen that u r firing click event before the DOM is ready. Use this ans
$(document).ready(function(){
$('.content-message-icon').click(function(){
//add click logic here
});
});
you are not using
$(document).ready()
Other answers have mentioned using jQuery's document ready, but nobody (yet) has explained why, or what the other way to do it is. So: you can't reference an element from JavaScript (with or without jQuery) if the element has not been parsed yet. To assign an event handler (or do any other element manipulation from JS) the two ways to be sure the element has been parsed are:
Put the script block after the element in the page source - anywhere after will work, but after all elements and just below the closing </body> tag is reasonably standard.
Put the relevant code in a $(document).ready() handler (if using jQuery) or in an onload handler.
(The document ready handler is created at the point where that code is included, even before the elements it manipulates have been parsed, but it doesn't get executed until the whole document is ready.)
Try taking out the empty tag. The behavior of might be interfering here.
This should work working..
Possible cause..
Jquery version = try other
Browser Problem = try all browser
enclose into this jquery
$(document).ready(function()
{
...click event
});
Try this
<script type="text/javascript">
$(".content-message-icon").live("click", function () {
alert("Handler for .click() called.");
});
</script>
I am trying to use SimpleBox jQuery plug-in on my website. I have the code such that everytime the user clicks on a div of class "link", a SimpleBox is invoked.
I also have another button that uses javascript to dynamically create divs of class "link" to my page. However, when I try to click these divs, the SimpleBox is not invoked.
<script type="text/javascript">
function createLinkDiv()
{
var parentDiv = document.getElementById ("right");
var linkDiv = document.createElement("div");
numDivs++;
linkDiv.setAttribute("class","link");
linkDiv.setAttribute("id",numDivs);
parentDiv.appendChild(linkDiv);
}
$().ready(function() {
$(".link").click(function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
$(".close_dialog").click(function() {
event.preventDefault();
$("#simplebox").simplebox('close');
});
});
</script>
Any idea why? Any help would be appreciated! Thanks!
For Dynamically added items use .live() or .delegate() to attach event handlers
$(".link").live("click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Or
$("#right").delegate(".link","click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Out of context
I suppose you've placed the the createLinkDiv function since you're calling it through inline javascript. Calling functions via inline javascript is a bit of out of fashion these days. Binding those events in code helps to keep your javascipt code easily maintainable.
$("#createLink").click(function(){
$('<div/>').attr({"class":"link","id":"link_" + $(".link").size() })
//Id shouldn't start with a number (not in HTML5)
.click(linkClick)
//Now you don't have to use live
.appendTo("#right");
});
As a side note, the $().ready() syntax is deprecated; it's better to use $(document).ready or just call $ with a function as a parameter.
To answer your main question, the .click method only binds to elements that exist when it's called. So when you add elements to the DOM later, you're not launching the simplebox on click because the handler hasn't been bound. You could either use .delegate to attach event handlers, or you could add the onclick directly in the creation of the DOM element.
The accepted answer is out of date now. The live() method has been removed from jQuery 1.9 and replaced with the on() method.
The syntax for on() is
$(element).on(event, selector, handler)
So in #jnfr's case, one of his handlers could be re-written as
$(document).on("click",".link",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Hopefully this will be of use to anyone arriving here and getting errors when using live().