Anchor text that triggers onClick of a different element? - javascript

I have a page where content is spread over several tabs. The user clicks each tab (anchor inside an <li>) in order to switch. I would like to anchor some other text to trigger the onClick of a tab in order to also switch the content.
Is this possible with javascript/jquery?

Yes. You can invoke a click event on another element using jQuery's .click();
Trigger tab click
Where #tablink is the ID of the tab you want to trigger.
More info: http://api.jquery.com/click/

You can achieve that with Jquery which is simple and easy to use. what you can actually do is that , you can attach a event eg., click to a event handler, which would do the stuff like loading appropriate content on to your current tab.
well this can be achieved by attaching the event to the event handler using a selector. .on() function is used as per the latest jquery lib although .click() also would work but its advisable to use .on() as it handles event delegation as well.
Example:
$( ".tab a" ).on( "click", function() {
// load the appropriate content to the current clicked tab
});
REF:
http://api.jquery.com/on/
Jsfiddle to play with :
http://jsfiddle.net/dreamweiver/h4JXs/1732/
Happy Coding :)

Related

Manually click a child link (and navigate) when clicking parent [duplicate]

Recently I found jQuery cannot trigger the native click event on an anchor tag when I'm clicking on other elements, the example below won't work:
html
<a class="js-a1" href="new.html" target="_blank">this is a link</a>
<a class="js-a2" href="another.html" target="_blank">this is another link</a>
javascript
$('.js-a1').click(function () {
$('.js-a2').click();
return false;
});
And here is the jsfiddle - 1. Click on the first link won't trigger native click on the second one.
After some searches, I found a solution and an explanation.
Solution
Use the native DOM element.
$('.js-a1').click(function () {
$('.js-a2').get(0).click();
return false;
});
And here is the jsfiddle - 2.
Explanation
I found a post on Learn jQuery: Triggering Event Handlers. It told me:
The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.
Question
So here comes my question:
How to understand 'there is no event handler attached using jQuery's event system that corresponds to these events'?
Why is there not such corresponding event handler?
EDIT
I update my jsfiddles, it seems there's and error on the class name.
there is no event handler attached using jQuery's event system that corresponds to these events
This means, at this point of the learning material, no jQuery event handlers has been attached to these elements using .click(function() {} or .bind('click', function () {}), etc.
The no-argument .click() is used to trigger (.trigger('click')) a "click" event from jQuery's perspective, which will execute all "click" event handlers registered by jQuery using .click, .bind, .on, etc. This pseudo event won't be sent to the browser.
.trigger()
Execute all handlers and behaviors attached to the matched elements for the given event type.
Check the updated jsFiddle example, click on the two links to see the difference. Hope it helps.
First of all you need to prevent the default behaviour of link
$('.js-a1').click(function (e) {
e.preventDefault();
$('.js-a2').get(0).click();
return false;
});
And to trigger the click event you can also use .trigger('click') better way
And the event handler is used like this:
$(document).on('click', '.js-a1',function(){//code in here});
// here now .js-a1 is event handler
i think you forgot to read documentation.
Document says :
// Triggering a native browser event using the simulate plugin
$( ".js-a2" ).simulate( "click" );
Old question, but here's a nifty and simple solution:
You can basically "register" a native JS event with jQuery by assigning the DOM element's onEvent handler to be the native event. Ideally, we would check first to ensure the onEvent handler has not already been set.
For example, 'register' the native JS click event so it will be triggered by jQuery:
$('.js-a1').click(function (e) {
$('.js-a2').click();
e.preventDefault();
});
var trigger_element = $('.js-a2')[0]; // native DOM element
if (!trigger_element.onclick) {
trigger_element.onclick = trigger_element.click;
}
Here is a fiddle: http://jsfiddle.net/f9vkd/162/
You have to use $("selector").trigger('click')

Jquery: How to associate onready for divs created after page load

I have few divs which will be created by a script not in my control on the web page. These divs will be created after page has completely loaded, based on AJAX data. How can I associate onready event with these divs.
It sounds like you are looking for event delegation. jQuery's .on() method has a very simple approach to attaching event handlers to dynamically created elements. For example:
$( "#dataDiv" ).on( "click", "div", function() {
$( this ).fadeOut();
});
That code will listen for click events on all current and future div elements within #dataDiv and then hide whatever was clicked on.
You can delegate all standard jQuery event types in this manner. Hope that helps!
You cannot but you can use event delegation if its about clicks/hovering etc. See http://api.jquery.com/on/#direct-and-delegated-events
If you have no control on the scripts, what you can do is use ajaxComplete() to check if your divs are present after each ajax request completes.

Click on dynamically added link on KeyUp with jQuery

I use jQuery to add some HTML to the DOM. After the insertion I would like to create an eventhandler which is called on keyup and clicks on the link added to el. However, jQuery does not find the a element as it was added after loading the page.
var el = $("#name");
// add content to el
$(document).keyup(function(e) {
el.find('a').click();
});
How can I update the DOM in el? I know that there is on() (and its predecessors) in jQuery. However, they do not help me as the event is not registered on the added element itself, but on the document and another event just happens on the newly added element. Any ideas on how to solve this?
Thanks to the response of #Johan I was doing further debugging and found the solution:
el.find('a')[0].click();
So the real problem was not the changing DOM but the click() event that apparently can only be applied to a single element and not to a list of only one element.
Some further discussion about click() not firing can be found here: Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Registering an existing event to ajax loaded DOM?

In my homepage , I have this button.
<button class="test">test</button>
And in my current code I have this script
$('.test').on('click',function(){
alert("YOU CLICKED ME");
});
Now, my application is ajaxified, so everytime I click a new page it is loaded as ajax, the problem is that the loaded page also has this button. and its markup is likethis
<div id ="firstDiv>
<div id ="secondDiv">
<button class="test">test</button>
</div>
</div
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
var $bdy=$(document.body);
$bdy.on('click','.test',function(){
alert("YOU CLICKED ME");
});
now append your .test anytime you like
So the new content also has "#test" but how come when I click that button it does not execute the event handler I created?
Because the handler is attached to the actual element. So if the element is removed and a new element with the same class is created, the event is not associated with that new element.
You could use event delegation to handle this:
$(document.body).delegate('.test', 'click', function(){
alert("YOU CLICKED ME");
});
or
$(document.body).on('click', '.test', function(){
alert("YOU CLICKED ME");
});
(They do the same thing, note the order of arguments is different. I prefer delegate for the clarity, but I think most people use the delegating version of the far-too-overloaded on method instead.)
What that does is watch for the click on document.body, but only fire your handler if the click passed through an element matching that selector (.test, in this case).
As you said that the content is loaded through data you get in AJAX this is the possible scenario that is happening.
<button class="test">test</button> is drawn
Then it is binded to to click event
You load the new data through ajax
Try to bind that it does not.
This is because when you first bind the click event to "test" element with that class are part of the DOM. Now that you add some markup after ajax call the elements become the part of DOM, but now after you wrote the new markup you need to first unbind the click event See Here. And then re-bind the click event. This will bind the event to all elements having class "test".
P.S. I don't know the specifications of your implementation but as others have suggested you should bind events to id and not class.
I finally found out the solution. all I needed to do was define a static container which is this
$('#staticdiv').on('click','.test',function(){
alert("YOU CLICKED ME");
});
and that fixed the issue

How to call JS to click a table element

Assume I get a table element with ID="emTab", how do I call JS to click it?
Thanks.
document.getElementById("emTab").onclick = function() {
// your code goes here
};
See element.onclick
To trigger click event
document.getElementById("emTab").click();
See element.click
The click method is intended to be
used with INPUT elements of type
button, checkbox, radio, reset or
submit. Gecko does not implement the
click method on other elements that
might be expected to respond to
mouse–clicks such as links (A
elements), nor will it necessarily
fire the click event of other
elements.
Non–Gecko DOMs may behave differently.
When a click is used with elements
that support it (e.g. one of the INPUT
types listed above), it also fires the
element's click event which will
bubble up to elements higher up the
document tree (or event chain) and
fire their click events too. However,
bubbling of a click event will not
cause an A element to initiate
navigation as if a real mouse-click
had been received.
Cross browser way
If you can use jQuery then it would be
$("#emTab").trigger("click");
Firing events cross-browser - http://jehiah.cz/archive/firing-javascript-events-properly
its simple using JQuery
$('#emTab').click(functionToCall);
while in JS
document.getElementById('emTab').onclick = function() {};
for details on DOM events:
http://www.howtocreate.co.uk/tutorials/javascript/domevents

Categories