how to click on a button after popup windows loaded completely - javascript

I want to click on some html element pragmatically.
I use Jquery selector to select a button and click it.
$('span.firstBtn').click();
after clicking this button a popup window will show and then I want to click a button in the popup windows.
$('div.BtnOnPopupWindows').click();
but I get null pointer because there is no popup windows when code run. so i need to wait till completion of loading the popup window. how can I do this? how can I wait till completion of loading of the popup window?

Use the jQuery's .on() method with delegated event handlers:
// DELEGATED EVENT HANDLERS
// Delegate event for existing or future elements using .on() with delegation:
$(document).on("click", ".BtnOnPopupWindows", function() {
console.log("BtnOnPopupWindows CLICK");
});
// DIRECT EVENT HANDLERS
// Define button click:
$('.firstBtn').on("click", function() {
console.log("firstBtn CLICK")
$('#popup').html(`<div class="BtnOnPopupWindows">TEST</div>`);
});
// Dynamically trigger stuff
$('.firstBtn').click();
$('.BtnOnPopupWindows').click();
<span class="firstBtn">BUTTON</span>
<div id="popup"><!--will be dynamically populated--></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Tip: Instead of using $(document) try always to delegate to a first static (non-dynamic) Element parent. For the above example it would be like:
// Static parent - on click - dynamic child
$("#popup").on("click", ".BtnOnPopupWindows", function() {

Related

Simulate User Click Event with JavaScript on Bootstrap Button

How can i simulate with Javascript the click Event of a Bootstrap Button to perform the default actions that binded on the Button ?
I need this for automated Testing of a website.
Bootstrap add no Event on the Button himself, the events a bubbled to the body element and the work is done their.
$("btn.btn-outline-danger").click() is not working
$("btn.btn-outline-danger").trigger("click") is not working
Try with this.
$(document).on('click', '.btn',function(){
alert('click');
});
Since Bootstrap uses jQuery as a dependency you can simulate a click event in jQuery way.
$('.btn').click(function(){
console.log('Event Triggered');
});
Excluding jQuery, Vanillajs.
var button = document.getElementByClassName('.btn');
button.onclick = console.log('Event Triggered');
Events should bubble up to the parent (unless explicitly prevented). Consider this simple html structure:
<div class="parent">
<div class="child"></div>
</div>
With the code below the parent has a function attached to the click event. When the child click event is triggered, the parent's event responds.
$(".parent").click(function() {alert("hello")}); // attach event
$(".child").click(); // trigger event
https://jsfiddle.net/epqdz2a1/
This should be the same in Bootstrap.
Vanilla js version:
document.querySelector(".parent").addEventListener("click", function(){alert("hello")});
document.querySelector(".child").click();

Stop a dynamic bound eventhandler to fire immediately

I'm using jQuery 2.1.3. I try to build a button that will show/hide content on click. I also want to hide the content when there's a click on a wrapping container (in my application it's the document itself, but I used a regular div in my example below). As there is some more logic to handle I'm also making use of custom events that I fire via .trigger().
This works fine but I have a problem. When I show the hidden content I apply an eventlistener to document to hide the content when the user clicks anywhere on it. This eventhandler is fired straight after the content is shown resulting in my content gets hidden immediately.
I can only get around this by using $evt.stopPropagation() in my toggle buttons event handler. But that's no solution for me as I need the event to bubble up as other elements listen for that.
Heres the simplified HTML:
<div id="document">
<button id="btn" type="button">Toggle</button>
<div id="content" class="hidden">Hidden Content</div>
</div>
And heres the JS to this:
//trigger custom show event
var show = function () {
$("#document").trigger("show");
};
//trigger custom hide event
var hide = function () {
$("#document").trigger("hide");
};
//handle custom show event
$("#document").on("show", function () {
$("#content").removeClass("hidden");
$("#document").on("click", hide);//add listener to container, fires immediately
});
//handle custom hide event
$("#document").on("hide", function () {
$("#document").off("click", hide);//remove listener from container
$("#content").addClass("hidden");
});
//on toggle button click call custom events
$("#btn").click(function ($evt) {
//$evt.stopPropagation(); would work but event should propagate
$("#content").hasClass("hidden") ? show() : hide();
});
JSFiddle
What could I do about this? Stopping event propagation on toggle button click would show my content but i need this event to bubble up as there are other elements around waiting for that. How could I avoid that the applied event listener on document fires immediately?
PS: jQuerys .show()/.hide() functions are no alternative for me.

Anchor text that triggers onClick of a different element?

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 :)

Why document click listener triggers immediately?

I want to bind a click function to the document when open some menu via click.
The problem is that when trigger the first event 'click on the menu', the function attached to the document has been triggered by the same event and close the menu. How to solve that issue. My code is something like that:
$('#openMenu').bind('click touchend', function(e){
e.preventDefault();
$('.openMobMenu').removeClass('openMobMenu');//Close All elements
var _this=$('#headMenu')
_this.addClass('openMobMenu');
$(document).bind('click touchend',{elem:_this},hideElementMob);
});
// bind click event listner to the document
function hideElementMob(e){
var th=e.data.elem;//Get the open element
var target=$(e.target);//Get the clicked target
//Check the target and close the element if need
if(target.parents('.openMobMenu').length==0) {
th.removeClass('openMobMenu');//close the element if need
//Unbind listner after closing the element
$(document).unbind('click touchend');
}
}
Thank you in advance!
Try adding the close handler with a little delay:
setTimeout(function(){
$(document).bind('click touchend',{elem:_this},hideElementMob);
}, 10);
And as Jan Dvorak suggested, you should use .on() to attach events.
UPDATE
I realized I did not answer the whole question, so here is some improvement to the "why does it behave like this" part:
When the click event occurs on #openMenu, the associated handler is executed first. This binds a click event to the document body itself.
After this, the event gets bubbled, so the parents of the #openMenu also recieves a click event, and since document.body is a parent of the #openMenu, it also recieves a click event and closes the popup immediatley.
To cancel the event bubbling, you can also call e.stopPropagation(); anywhere in your event handler. (maybe its a cleaner solution compared to setTimeout)

Click event doesn't fire on element

I am building a Windows 8.1 Store application with WinJS. When the user queries some search results show up in a <p class="searchresults">content</p> tag.
I'd like to add an event handler to the .searchresults class. I've done the following:
$('.searchresults').on('click', function() {
console.log("clicked");
});
I've tried even without .on()
$('.searchresults').click(function() {
console.log("clicked");
});
However the event never gets fired. I've set up a breakpoint, so I can see when it fires - but that never happens
I've tried to add an event handler via the WinJS way:
Microsoft.Maps.Events.addHandler(document.getElementsByClassName("searchresults"), 'click', myfunc);
Without success.
Any ideas why this is happening?
I will guess that you are creating the <p class="searchresults">content</p> object AFTER you try to install the event handler (a common problem with dynamic content). That will not work with normal event handling because the DOM object does not exist when you try to add the event handler to it.
If this is the case, then you need to use delegated event handling like this:
$(document.body).on('click', '.searchresults', function() {
console.log("clicked");
});
This will allow you to dynamically create the searchresults content at any time and the event handler will still fire via event delegation (events propagate up to their parents).
You haven't shown the HTML around the search results content, but the most optimal way to do this is to select the closest static parent to the search results (a parent that is not dynamically created and already exists at the time you attach the event handler) and attach the event to that:
$(closest static parent selector).on('click', '.searchresults', function() {
console.log("clicked");
});

Categories