I am new to jQuery and am having a few issues. This jsFiddle shows what I am experiencing: http://jsfiddle.net/rE2FH/5/ Note how the button does nothing.
What I am trying to do is set a click listener to the button and have it do an alert();. However, the neither the click event or the alert() is working.
I have tried the click event as .click(), .on(), .delegate(), and .live() none of which seem to work. As for the alert, I cannot find anything other than the equivalent to "It automagically works if you do 'alert([sting]);'!" I am aware the .click() is for 1.7+, .live() is depreciated and even then .delegate() is preferred over it.
In my current project I am using jsp with the script
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> HOWEVER, it does not work in the jsFiddle either. This version works fine on some of our other pages (alert and .click events), but for some reason the one I'm currently working on has issues. I have done everything I can see to emulate those other pages as well, but I may be missing something. The guy who wrote that jQuery is no longer with our company.
I have already searched SO, and none of these results have worked for me:
jQuery .click() not functioning
jQuery .click() problem
jquery button not respond to click method
jquery click event issues
+others that are all along the same lines.
Any insight would be appreciated.
You had several issues. Make sure you check the javascript console for errors. Here's a working version:
http://jsfiddle.net/LxuVy/
$(document).ready(function(){
$(document).delegate('#but', 'click', buttonClick);
function buttonClick() {
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}
});
To break down the issues with yours:
$(document).ready(function(){
$.delegate('#but', 'click', buttonClick());
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}; // this semi-colon shouldn't be here
}; // missing closing paren for ready()
delegate is used like this:
$('selector').delegate(...)
Though delegate() has been replaced by on(), which should be used instead.
Also, buttonClick() should be buttonClick. When you add the parentheses, you are executing the function. What you want to do in this case is pass the function as a parameter.
You are missing the closing ) from the document.ready:
$(document).ready(function(){
$.delegate('#but', 'click', buttonClick());
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
};
});
I would also suggest using .on() like this: http://jsfiddle.net/rE2FH/23/
Multiple probleme.
First you need to select an element with delegated (closest static parent)
$(document).delegate(...)
The function in the parameter should not finish with braket
$(document).delegate('#but', 'click', buttonClick);
And you are missing a closing parenthesis.
Fiddle : http://jsfiddle.net/rE2FH/18/
But since your button is static, you can use click directly :
$('#but').click(buttonClick);
Also, delegated is deprecated, you should use .on().
I see three problems:
.delegate is also deprecated, you should be using .on. You are also calling it wrong, directly on $. Finally, you're not actually delegating the event to any ancestor, so you could very well be using .click directly.
Instead of passing a function reference when binding the event, you're calling the function (you're passing buttonClick() instead of buttonClick).
You forgot to close a parentheses at the end, causing a syntax error (always check you browser's console, it will show this kind of error).
Fixing all that, your code would be:
$(document).ready(function(){
// using .click instead of .delegate
// .on('click', buttonClick) would work too
$('#but').click( buttonClick );
// no calling parentheses -^
function buttonClick(){
$('#res').hide().html("BUTTON!!!").fadeIn('fast');
alert("Hello!");
}
});
// added missing ) at the end
Related
I have seen a bunch of questions on this but im still stumped. I could realy use some help understanding what im doing wrong here.
(my terminology may not be correct below)
I have a textarea and a .keyup function bound to it by class name
This first textarea fires the function fine
I then add a second textarea dynamically which is intended to fire the same function
My .keyup function
$('.trans').keyup(function() {
alert("Working");
});
I understand that the above doesnt work on the newly created textarea because it wasnt part of the DOM when the function was bound. I have tried several ansers to other questions but cant seem to get this working:
Other things Ive tried:
// I also tried this
// Neither textarea responds if this is used
$('.trans').on('keyup', '.newTrans', function() {
alert("Working");
});
// I also tried this
// Only the first textarea responds
$('.trans').delegate('.newTrans', 'keyup', function(){
alert("Working");
});
Here is a JSfiddle with more of the code im using if needed:
jSfiddle
The .on() method isn't going to work in your fiddle at all because you have specified an old version of jQuery from before .on() was introduced.
If you upgrade to a newer version of jQuery (at least 1.7) you can do this:
$(document).on('keyup', '.trans', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/4/
If you need to keep using v1.6.4 for some reason then use the .delegate() method instead:
$(document).delegate('.trans', 'keyup', function() {
alert("Working");
});
Demo: http://jsfiddle.net/VFt6X/5/
Note that either way the '.trans' selector for the elements you care about is passed as a parameter to the function. The $(...) part on the left has to specify some container that already exists. I've used document, but it is better to specify something closer to the elements in question if possible, so in your case you could use $("#centerNotes").
Try this:
$('.trans').live('keyup', function() {
alert("Working");
});
http://jsfiddle.net/VFt6X/3/
If you want to click a link with jQuery, you can use one of the following methods:
$('a').click();
$('a').trigger('click');
Which is better? (performance, browser support, i.e.)
There seems to be none, performance wise.
See: http://forum.jquery.com/topic/a-trigger-click-vs-a-click
This method is a shortcut for .bind('click', handler) in the first
variation, and.trigger('click') in the second.
Except you can extend the trigger command.
Seems like i was mistaking.
Since click is actually calling trigger, if no function is called.
See: jQuery advantages/differences in .trigger() vs .click()
And for performace results, #VisioN linked to this: http://jsperf.com/click-vs-trigger-click
So, basicly using trigger is the fastest way, also i think it actually tells what you are doing, instead of just doing it.
http://forum.jquery.com/topic/a-trigger-click-vs-a-click
In this form they are the same. As the api reference states:
This method is a shortcut for .bind('click', handler) in the first variation, and .trigger('click') in the second.
The second can also be used to attach a function to the event.
Exactly the same. But I prefer $('a').bind('click', function(){});
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.
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().