Stop a dynamic bound eventhandler to fire immediately - javascript

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.

Related

how to click on a button after popup windows loaded completely

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() {

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

removing a placed jquery click event listener after initial click

Got some simple functionality set up on a page. Initially I want to replace default action of a hyperlink click with some functionality which will display an overlay.
After the overlay is displayed I want to remove the event listener I have placed on the hyperlink so it reverts to what it was previously (i believe there is another event listener on here, I dont want to remove this one while removing mine). Within the overlay is another button which when clicked, should trigger the initial functionality of the button.
Ive tried the .off() jquery method, however this seems to prevent the ".mmclose" button from working.
Not quite sure where i am going wrong with this..
// placing event listener on initial link
$("#utility_0_HyperLinkLogout").click(function() {
// removing event listener(?)
$("#utility_0_HyperLinkLogout").off("click");
// preventing default button behavior
event.preventDefault();
//overlay replacing original content
I62originalContent.hide();
$("#mmi62wrapper").fadeIn("slow", function() {
// new event listener placed on button within overlay (as callback)
$(".mmclose").click(function() {
//new button should now trigger original buttons original functionality?
$("#utility_0_HyperLinkLogout").trigger("click");
})
})
});
You can use jQuery .one method to attach a handler which will be executed only once. You don't need to worry about removing this handler anymore.
Check this example:
$(".myClass").click(function() {
this.innerText += "!";
});
$("#myId").one('click', function() {
this.innerText += "?";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="myClass" id="myId">Click me twice</button>
In this example, clicking the button keeps adding "!", while "?" is only added once. Other handlers are not affected.

<a> tag only working on double click and not single click

Hi I have a <a> tag that is working on double click but not on single click.
I have a javascript function called on the tag.
Can someone help on same.
Below is the tag and the javascript function
function ShowPopup() {
$("#lnkAttachment").on("click", function () {
$('#divProjectAttachment').modal('toggle');
});
}
<a>href="javascript:void(0);" id="lnkAttachment" onclick="ShowPopup();">Click here to View Attachments!</a>
You're attaching event listener inside your ShowPopup function. Just update it to be like
function ShowPopup() {
$('#divProjectAttachment').modal('toggle');
}
And it will work fine.
Edit:
Why this happens?
Well, first of all, this works on 2nd click, not on double click.
Next,
You have attached onclick event handler in your <a></a> tag. Which triggers ShowPopup function.
And inside your ShowPopup function you're re attaching click event listener to the same element.
So first time when you click on your anchor tag, the ShowPopup will attach event listener to the #lnkAttachment. An important thing to note here is that that your ShowPopup function gets called on the first click. But it won't show you the popup because you're attaching the event listener to the element and that's it. Now the event listener is attached after the ShowPopup is called for the first time.
Next time when you click on the lnkAttachment the event listener is already present so it wil lshow the popup. Additionally, it will re-attach the click event listener again (and everytime the ShowPopup is called - which is unnecessary).
You can either keep your code as this answer demonstrates
OR
You can decide to follow good programming ethos and separate event attachment (JavaScript) from your display markup (HTML)
The way to do it is as follows.
Keep your anchor tag as
href="javascript:void(0);" id="lnkAttachment">Click here to View Attachments!
(Notice, no onclick event handler here)
and in your javascript you take care of event handling.
$(document).on('ready', function(){
$("#lnkAttachment").on("click", function () {
$('#divProjectAttachment').modal('toggle');
});
}
When you are using jQuery, you can wire up the events without onclick in html.
<a>href="javascript:void(0);" id="lnkAttachment">Click here to View Attachments!</a>
You can remove the onclick in markup and write your jQuery script in DOM ready.
$(function(){
$("#lnkAttachment").on("click", function () {
$('#divProjectAttachment').modal('toggle');
});
});

Open new window on background div click

I am using CSS to apply a background image to a div tag that wraps all of the content on a website.
<div id="mainBack">
<%-- All other content goes here --%>
</div>
And the CSS id with the background property...
#mainBack
{
background: url(../images/background.jpg) repeat-x top;
padding: 15px 0 20px 0;
}
PROBLEM:
I'm trying to figure out how to open a new browser window to a different URL whenever the background image is clicked upon. I have tried doing this using jQuery, but the manner in which I implemented it actually causes every click on anything in the website to open a new window. The jQuery click event that does this - although incorrectly - is below:
$('#mainBack').click(function () {
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
});
Any suggestions on how I can go about implementing this behavior in a fashion that actually works?
You can stop the propagation of click events for elements on top of your #mainBack element.
For example:
<div id="mainBack">
Some Link
</div>
<script>
$('a').on('click', function (event) {
event.stopPropagation();
});
</script>
This will make it so any link clicked on will not allow the event to bubble up to any ancestor elements. Which in turn will make detecting a click on the #mainBack element possible.
You will have to stop the propagation of the event on any element you want to be clickable without opening the popup window.
Also, note that .on() is new in jQuery 1.7 so if you're using an older version, change .on() to .bind().
Update
You can also use the event object inside your event handler to check if the targeted element is the #mainBack element:
$('#mainBack').click(function (event) {
if (event.target.id == 'mainBack') {
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
}
});
Here is a demo of using event.target: http://jsfiddle.net/j5NuW/ (notice the event handler is attached to the body element but the alert only shows if you click the #mainBack element)
You can check if the clicked element was the div or something else by adding one line of code, and the event parameter to the function:
$('#mainBack').click(function (event) {
if(event.target==this)
window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
});

Categories