jQuery's click() is not clicking? - javascript

I thought jQuery's click() can let us add a handler or just click on an element?
However, I tried:
$(function() {
setTimeout(function() {
$('a').first().trigger('click'); // or click(), the same
}, 3000);
});
and waited 3 seconds and it won't click on the first <a> element in the page... how come?
Update: this is related to What is the best way to make the Yahoo media player autostart, jQuery? and so there should already be event handler for clicking on a media, so how come .click(), which is the same as trigger('click'), not firing off that event handler?

Calling the click() method does not simulate clicking the link. It calls any click() handlers on the affected element(s). That's a subtle yet important difference. If you want to simulate clicking the link, there is no realiable cross-browser way of doing this.

I very recently ran into a similar problem. The reason nothing happens is because anchor tags don't have a "click" method for jquery to call. If you change the anchor tag to a <button></button> tag for instance, the .click() will simulate a user clicking as expected.
There are a few "hacky" workarounds for this, but it would depend how the event handler for the anchor tag is set up. For instance, if there was some javascript inside the anchor tags href attribute, this would work (which happened to be the solution to my problem):
var lnk = $('a.mylink');
window.location = lnk.attr('href');

I'm not sure, if .first() is a possible way to use this function. Have you tried
$('a:first').click();
instead? If .first() doesn't exist, it throws an error, the .click() is never reached, and since it lives in an anonymous function, you even might not see the error at all (failing silently).

Here's what you could do to simulate a click on a link (as long as these are normal links):
location.href = $('a').first().get(0).href;

If you already have an event-handler for the link, you can use the trigger() method:
$('a:first').trigger('click');

What exactly do you want to do? A link is usually used to redirect to a new page. So if you need a redirection, use something like this:
$(function() {
setTimeout(function() {
window.location.replace("linkToNewPage.html");
}, 3000);
});

"There is an option for this. Plz check
at this page
http://mediaplayer.yahoo.com/api/#example_usage
If u set autoplay=true, the first song
will be started automatically.."
-Kai
In Relation to:
What is the best way to make the Yahoo media player autostart, jQuery?
Else for a click attach a click handler to what you want e.g:
$('#MyElementID').click(function() {
//How you want it to behave when you click it.
});
window.setTimeout(YourFunction, 3000);
function YourFunction {
//Your function that runs. Maybe fire the onclick handler?
}
?

You're trying to use click() method for something else than its purpose. click() is used so you can catch the click on a specific element, not for simulate it.
Read more here

Related

Triggering button click in jQuery not working

Using dot.js I'm adding a button to a specific web page that, when clicked, should add some text to a text field and then trigger another button to also be clicked. I simulate this by adding a click handler to my button which has this code:
var button = $('.some-class').find('button')[0];
console.log(button); // element I expect
button.click();
However, this doesn't work and I'm not sure why. If instead of .click() I perform .remove(), the button is removed from the page. If I use the console to execute the same code, the button does get clicked. This tells me I do have the right element, but there is something wrong with the click() event specifically.
Can someone explain why this isn't working in either Safari or Chrome? I've tried a lot of different things, but I'm new to jQuery so I'm probably missing some detail in how that works.
We went to the bottom of this in the chat. What probably caused the problem was another event-handler attached to (possibly) body, that undid the click.
So the solution was to stop the event from propagating:
event.stopPropagation();
While assigning the click event handler to the button you should use jquery on
This should ensure that whenever a new button with added with same selector (as in when event was assigned), event handled will be assigned to that button
Some examples here
The problem is the click() function is from jquery and you're attempting to fire the click function from the DOM object.
Try
$(button).click();
Here's a plunk.
http://plnkr.co/edit/2pcgVt
You can use the following statement.
var button = $('.some-class').find('button')[0].trigger('click');
try jquery's trigger() function:
$(button).trigger('click');
see jsfiddle: https://jsfiddle.net/665hjqwk/

How to disable e.preventDefault for some elements

I am using a OnePage template of bootstrap, I can not click a link, or can not switch a radio button, someone says I am using e.preventDefault()
Open this page http://abi.maxinrui.com/, you will see what I mean when you click "Click me" on that page.
I check the js file, there are lots of e.preventDefault() and I don't know how to modify them.
Is there a way to disable e.preventDefault()?
I want to have some hyperlink to another websites in my OnePage templete, so here is what I am think: I give some particular elements an ID or class, then I write some js, to disable e.perventDefault() only for these elements.
Does anybody know how to do that?
Thanks!
If you're using jQuery to handle your events, then it's possible!
First, a fiddle (shell for full effect): http://fiddle.jshell.net/UN5WE/show/
Here's the actual fiddle to edit: http://jsfiddle.net/UN5WE/
Basically, we're modifying jQuery's Event object, and specifically, the preventDefault method found on the prototype. We maintain a reference to re-enable preventDefault.
EDIT
For your specific use case, here's a way to disable preventDefault (based on a class). Just run this script after jQuery has loaded:
jQuery.Event.prototype.preventDefault = (function(){
var originalFunc = jQuery.Event.prototype.preventDefault;
return function(){
if($(this.target).hasClass('disableDefault')) {return;}
originalFunc.call(this);
}
}())
Prior to calling preventDefault, this will check to see if the target has a disableDefault class. If it does, it returns immediately (allowing the default to happen). To test your page, copy that code into your console and then run: $('h1').addClass('disableDefault').
I don't think is possible, or at least not on an easy way that i can think of, you can unbind the handlers if they were setted using bind, but that will also remove any behavior that they have, but you can use a workaround, add a new event handler for your links, i recommend that you add a special class to external anchors and then get the href attribute from it and open a new tab using window.open like this:
http://jsfiddle.net/yV78E/2/
The html
Hey
The js
// Similar behavior that might be on your site
$('a').click(function(e){
e.preventDefault();
// some code
});
// Use the code below as a workaround
$('.externalLink').click(function(e){
var targetLink = $(this).attr('href');
window.open(targetLink, '_blank');
});
You only need the second part of the script above, since the first one is just to emulate your problem.

jQuery Adds Extra '#' to URL?

I noticed sometimes that when I use jQuery, a extra '#' gets added to the end of my URL after a jQuery function is called. For example, the URL 'www.mywebsite.com' will change to 'www.mywebsite.com/#' once a jQuery function is initialized. The same for 'www.testsite.com/users.php', is changed to 'www.testsite.com/users.php#'.
Why does jQuery add the '#'?
If your function is running from a link onclick, you need to use event.preventDefault()
See http://api.jquery.com/event.preventDefault/
Probably you're getting this when handling a click event. If you don't want that happens, just add event.preventDefault() or return false at the end in event handler function.
Usually this is because you have a dummy link with a jQuery click handler. It's common to see links with an href of # that are only used to trigger some JavaScript.
Go
Resolve this easily by making a habit of calling e.preventDefault() in your click handlers:
$(function() {
$(".button").click(function(e) {
e.preventDefault();
...
});
});
You can also use return false, but that has the added effect of stopping event propagation. I like to add e.stopPropagation() explicitly if I also want that effect. It makes the code and it's intended effect more explicit and clear for future developers (or myself in 6 months).

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.

<a href="javascript:foo(this)"> passes Window, I want the tag element itself

I expect this to print "a" because when I call foo(this), the argument seems to be the link tag.
<script type="text/javascript">
function foo (e) {
alert (e .tagName);
}
</script>
click
Instead, it prints "undefined". If I alert(e) it says "object Window". How do I make foo know which element launched it? Without passing/looking up ids.
You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.
click
You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.
It is better to attach the event with Unobtrusive JavaScript
You can do this directly too
click​
The this object is not handled the same in all browsers. This is one of the many items that libraries like Prototype and jQuery try to normalize. That said, however, most browsers will pass the appropriate this during on onclick handle (rather than the href) as many other answers have pointed out. If you want to handle the this appropriately, you'll need to do things like those detailed in this question.
click
function foo(obj) {
alert(obj.tagName);
}​
Don't call the element e it's a standard for the event object.
JSfiddle DEMO

Categories

Resources