How to trigger an event on a group of elements? - javascript

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

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/

jQuery .click() is clicking, but it shouldn´t

while testing my JavaScript I have the following problem:
$('#idOfMyElement').click();
is executed. But I want to verfiy with my test, that is is not executed, because it has the following CSS:
<span style="cursor: not-allowed; pointer-events: none;" id="idOfMyElement"></span>
I debugged it and it is sure, that when the .click() is executed, it has DEFINITELY the mentioned CSS-attributes. In my normal program it works (means that the click doesn´t work), but in my test the click works, even if it shouldn´t.
I have no clou, what might be the problem.
Thanks for your help!
Looks like in your test you are triggering the event programmatically by using $('#idOfMyElement').click();; in that case it is not bound by the CSS mouse rules, and thus the click handlers will get executed.
You need to check the mouse pointer rules before triggering the click event in your test suite.
Prevent the default click event using jQuery:
$('#idOfMyElement').on('click', function(e) {
e.preventDefault(); });
* UPDATE *
Now that I know what you're trying to do, I highly recommend using javascript over CSS for this because CSS does not work the way you're trying to use it – Javascript does. Instead of using CSS attributes, use Javascript variables.
When you want the element to be clickable,
$('#idOfMyElement').prop('disabled', false);
When it should be unclickable,
$('#idOfMyElement').prop('disabled', true);
The browser takes care of the cursor without needing CSS, and click events should react appropriately. Hope that was helpful!
Pointer events only respond correctly to a real pointer event. If you trigger click() function it fires in all times that you make it. Just add a condition reading if pointer events is active or replace it by a disabled attribute

Click anchor, and be brought to linked page

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();
});

Jquery global events and dynamically added content

I'm trying to trigger my own custom events as global events, so that anything on my page can listen to them and react, however, for dynamically added content it's not working. See my fiddle at: http://jsfiddle.net/6TMkG/8/
As far as I understand, the event is triggered for any element in the page that jQuery knows has a handler for it, and it seems it doesn't trigger the event for the li's even though they do have a handler.
Anyone know how to get around this behaviour?
try this
$("#b2").click(function() {
//$.event.trigger("randomEvent");
$('li').trigger('randomEvent');
});
If you want global event, then you could bind the event handler on document, and trigger it on any element in the document.
$(document).on('randomEvent', callback);
$('ul').click(function() {
$(this).trigger("randomEvent");
});
Sorry I completely missed that.. I did not see the first part of your question.. Custom events.. Looks like you are associating the randomEvent but you are not triggering that event when that is associated with it..
Make sure you add the trigger Event in the Document.Ready function so that the evnet handler is associated with as and when the element is available.

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