Click anchor, and be brought to linked page - javascript

I have a anchor on which I trigger a click with JavaScript. Please see this fiddle.
$(function() {
$('a').click();
});
For some reason, triggering the click does not bring me to the page specified by the href attribute of the anchor.
How can I have the click event also bring me to the page linked by the anchor?

It will not work like that, the call $('a').click(); is a short cut for $('a').trigger('click'); which tries to simulate a click action on the anchor element.
But the simulation is not absolute, though it will fire the registered event handler it will not completely simulate a use click trigger the default action.
As per the jquery doc for trigger
Description: Execute all handlers and behaviors attached to the
matched elements for the given event type.
and
Although .trigger() simulates an event activation, complete with a
synthesized event object, it does not perfectly replicate a
naturally-occurring event.
So I don't think it is possible to completely simulate a user action and trigger a redirection using this method

Seems to be something to do with jQuery and the trigger method, works fine when you change [object object] to [object]. Here is the fiddle. Enjoy!
$(function() {
$('a').get(0).click();
});

Related

How to trigger an event on a group of elements?

I have a listener on a group of elements:
$('a.menu__link').on('click',function() {alert('function was triggered');});
One element of which is:
<a class="menu__link menu__link--submenu Main" id="Events" href="#">Events</a>
I want to manually trigger a click on the element. Using Chrome dev tools, the event handler is:
a#Events.menu__link.menu__link--submenu.Main
However, the following code does not trigger the listener:
$('a#Events.menu__link.menu__link--submenu.Main').trigger('click');
I have tried every variation that I can think of, but I cannot find the correct reference to trigger the alert function.
What am I doing wrong?
You can use instead click instead of trigger like this to trigger a click :
$('#div').click();
Read more about click here
Here is a JsFiddle
I encased the trigger in a $(document).ready(function()) and that fixed it.
Kudos to Blazemonger for implying that it was a timing issue.
<script>$(document).ready(function() {
$('#Events').trigger('click');
$('#PastSeminars').addClass('menu__link--current');
});</script></body></html>
The lesson? Just because it is the last thing on the page, when in doubt, use document.ready.
Chrome blocks the click event from being programmatically fired. I'd come up with a new solution such as just calling the needed function wherever you need to trigger it.
You can read more about it here: https://teamtreehouse.com/community/why-does-my-onclick-event-not-fire-on-chrome

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/

jQuery Simulate onClick

I am trying to simulate an onclick event on a drop down.
I have an IE object that is going to a page and I need to change a dropdown which has an onchange event:
$('select[name="blah"]').val(3).trigger('change');
$('select[name="blah"]').change(function(){
alert('changed');
});
When I try this, I would expect the alert to fire as it's technically an onchange.
http://jsfiddle.net/3y5hmyf0/
Is there a way to acomplish this?
More Details
My tool is controlling another IE page through an object. It navigates to the page and finds the select drop down on the page. From there, if you did it manually it has an onchange event when making a selection.
I am trying to get jQuery to simulate as if it was being clicked by a person to it triggers that on change event.
I have tried .trigger and .change and couldnt get either of them to work.
The only reason your code does not work is the order you are executing it. You need to connect the handler before triggering it:
JSFiddle: http://jsfiddle.net/3y5hmyf0/1/
// Wire up event handler
$('select[name="blah"]').change(function(){
alert('changed');
});
// Now generate the event
$('select[name="blah"]').val(3).trigger('change');
Note: Your manual change trigger is still required as a change event must normally be triggered by user interaction. Setting the value is not enough.
$('select[name="blah"]').change(function(){
NotifyChanged();
});
function NotifyChanged() {
alert('changed');
}
If you want to test the logic in the changed function, just call it.

JavaScript Click event fires via the Enter Key but not via the Mouse

Some code that looks like the following is firing the click event via the Enter key, but is not responding to the mouse click.
//a is an anchor element
a.addEventListener('click', function (e)
{
//Do Stuff...
});
This page demonstrates the problem. The relevant bit of code is at line 176. This is in the middle of development and currently only (sort of) works in Chrome.
Also, I just verified that it works if I use mousedown, so it's not just the case of an invisible element sitting in front of the anchor.
Any ideas?
Edit: Now that you've shown us the actual code you're using, the problem is related to the fact that the autoSuggest() function has it's own click handler and in that click handler, it is clearing the container which removes all <a> elements in the container so your link object gets destroyed (probably before your click event gets to process). So, you can get events that happen before the click (like mousedown), but after a click, the element is removed from the DOM.
If you tell us what you're trying to actually do when an auto-suggest item is clicked that is different than the default behavior of the autoSuggest() function and you point to any documentation for that function, then perhaps we could offer a better way to solve your issue.
The link may be firing and taking you off to a new page (or reloading the current page), thus preventing you from seeing the click code run. Usually when you process a click event on a link element, you need to prevent the default behavior:
//a is an anchor element
a.addEventListener('click', function (e) {
e.preventDefault();
//Do Stuff...
});
Another possibility is that you are trying to install the event handler too soon either before the DOM has been loaded or before this particular link has been created and thus no actual click event handler is attached to the DOM object. You can verify whether the event handler is even getting called by temporarily putting an alert("Click handler called"); in the event handler and see if that pops up or not.

Locating an element in a 'Facebox' box

Heres my link:
http://tinyurl.com/6j727e
If you click on the link in test.php, it opens in a modal box which is using the jquery 'facebox' script.
I'm trying to act upon a click event in this box, and if you view source of test.php you'll see where I'm trying to loacte the link within the modal box.
$('#facebox .hero-link').click(alert('click!'));
However, it doesn't detect a click and oddly enough the click event runs when the page loads.
The close button DOES however have a click event built in that closes the box, and I suspect my home-grown click event is being prevented somehow, but I can't figure it out.
Can anyone help? Typically its the very last part of a project and its holding me up, as is always the way ;)
First, the reason you're getting the alert on document load is because the #click method takes a function as an argument. Instead, you passed it the return value of alert, which immediately shows the alert dialog and returns null.
The reason the event binding isn't working is because at the time of document load, #facebox .hero-link does not yet exist. I think you have two options that will help you fix this.
Option 1) Bind the click event only after the facebox is revealed. Something like:
$(document).bind('reveal.facebox', function() {
$('#facebox .hero-link').click(function() { alert('click!'); });
});
Option 2) Look into using the jQuery Live Query Plugin
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.
jQuery Live Query will automatically bind the click event when it recognizes that Facebox modified the DOM. You should then only need to write this:
$('#facebox .hero-link').click(function() { alert('click!'); });
Alternatively use event delegation
This basically hooks events to containers rather than every element and queries the event.target in the container event.
It has multiple benefits in that you reduce the code noise (no need to rebind) it also is easier on browser memory (less events bound in the dom)
Quick example here
jQuery plugin for easy event delegation
P.S event delegation is pencilled to be in the next release (1.3) coming very soon.

Categories

Resources