I am using Bootstrap 5.2 and I have two buttons that can hide content, using the Bootstrap collapse plugin.
<div class="col-12 col-sm-auto">
<span class="pe-2">
<button id="show_movements_button" type="btn" class="btn btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#movements_id">
Show Movements
</button>
</span>
<span class="pe-2">
<button id="show_credits_button" type="btn" class="btn btn-outline-secondary" data-bs-toggle="collapse" data-bs-target="#credits_id">
Show All Credits
</button>
</span>
</div>
such as
<tr class="song_id collapse" id="movements_id">
<td class="col-1">
1
</td>
<td class="col">
</td>
<td class="col">
<div>
<label class="h6">
Piano Concerto no. 1 in E minor, op. 11: I. Allegro maestoso
</label>
</div>
<div class="collapse" id="credits_id">
<div class="lh-1">
<div>
<a href="/container.start?cid=0$=Instrument$708&title=Instruments+%2F+piano" class="small text-secondary">
piano
</a>
<label class="small">
by
</label>
<a href="/container.start?cid=0$=Performer_name$5540&title=Performers+%2F+Evgeny+Kissin" class="small text-secondary pe-1">
Evgeny Kissin
</a>
</div>
</div>
</div>
</td>
</tr>
This work correctly, but I want the name of the button to change to indicate if showing or hiding content so I also have this code
<script>
function listenForButtonCollapse(buttonId, collapseId, buttonShowText, buttonHideText)
{
let button = document.getElementById(buttonId);
let section = document.getElementById(collapseId);
if(section!=null)
{
section.addEventListener('show.bs.collapse',
function()
{
button.innerText=buttonHideText;
}
);
section.addEventListener('hide.bs.collapse',
function()
{
button.innerText=buttonShowText;
}
);
}
}
</script>
<script>
listenForButtonCollapse('show_credits_button','credits_id','Show All Credits','Hide Some Credits');
</script>
<script>
listenForButtonCollapse('show_movements_button','movements_id','Show Movements','Hide Movements');
</script>
Now toggling the Show/Hide Movements button works fine, but when I click on the Show/Hide Credits button for some reason it is also triggering the listenForButtonCollapse() call on the movements button as well as the credits button, so the Movement button is updated with the same (Hide/Show) value as the credits button even though it isn't actually been invoked (so it doesn't hide/show the movements div)
The credits div is within the movements div, so Im assuming that why one button works without problem and the other doesn't but I cant see what I am actually doing wrong.
In order to avoid the current behaviour you need to stop further event propagation. You can do this by using stopPropagation(). This method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.
function listenForButtonCollapse(buttonId, collapseId, buttonShowText, buttonHideText)
{
let button = document.getElementById(buttonId);
let section = document.getElementById(collapseId);
if (section != null)
{
section.addEventListener('show.bs.collapse',
function(event)
{
event.stopPropagation();
button.innerText=buttonHideText;
}
);
section.addEventListener('hide.bs.collapse',
function(event)
{
event.stopPropagation();
button.innerText=buttonShowText;
}
);
}
}
I've prepared a Code playground to illustrate that this solves your issue:
https://codesandbox.io/embed/bootstrap-5-playground-forked-b28j0g?fontsize=14&hidenavigation=1&theme=dark
Solution Explanation
The events show.bs.collapse and hide.bs.collapse are being triggered for both buttons when clicked. So when you add more than one event listener for those events, when the event occurs, all event listeners are being executed. This is why for example when you click "Hide Movements" and bootstrap triggers hide.bs.collapse
event then this executes all registered event listeners for it - in this case two - one for the show_credits_button and another for show_movements_button button - leading to changing both button texts. To prevent this you need to stop further event propagation with event.stopPropagation() method - this will stop notifying all other event listeners for this event other than the event target one.
Related
I'm creating my own autocomplete input in Blazor. (something like below)
function FocusOut()
{
document.getElementById("list-item-one").innerHTML = "Focus out";
}
function Click()
{
document.getElementById("list-item-one").innerHTML = "Click";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" onfocusout="FocusOut()" />
<ul class="dropdown">
<li id="list-item-one" onclick="Click()">List Item One</li>
</ul>
When I click on the list item, the onfocusout event fires instead of the onclick event. Is there a way to "push" the onclick event?
This isn't a parent child relation, so "stopPropagation" has no effect. Also I know there is a datalist tag, but i'm not using it because of the way it look, feels and behaves in the different browsers.
The problem is that the order of events is OnMouseDown, OnFocusOut, OnClick.
Because of this, your dropdown closes before the OnClick event, so the click is not registered.
A working solution is to replace OnClick with OnMouseDown.
Based on this answer by #DuncanLuk.
I had a similar issue and I added a await Task.Delay(250) in my #onfocusout handler and it worked. You can find the live demo by clicking three vertical dots at top right in ilovedotnet site.
<section id="social">
<div class="dropdown is-right #(MenuCollapsed ? null : "is-active")" #onclick="ToggleMenu" #onfocusout="FocusOutHandler">
<div class="dropdown-trigger">
<button class="button" aria-haspopup="true" aria-controls="social-menu">
Social
</button>
</div>
<div class="dropdown-menu" id="social-menu" role="menu">
<div class="dropdown-content">
<a href="https://ilovedotnet.org/" target="_blank" class="dropdown-item">
I Love DotNet
</a>
</div>
</div>
</div>
</section>
#code {
internal bool MenuCollapsed { get; private set; } = true;
internal void ToggleMenu()
{
MenuCollapsed = !MenuCollapsed;
}
internal async Task FocusOutHandler()
{
// to avoid race between mouse click of anchor tag Navigation. without this delay Navigation
// is not getting executed when item is clicked from mouse
await Task.Delay(250);
MenuCollapsed = true;
}
}
I cannot get a nested variable value to populate outside a nested function within a button's click event function even though I believe I am using a global variable.
What am I doing wrong to pull value into a console log outside the nested function?
I am creating a shopping cart utilizing jquery pop-up with ajax and php. I am able to add items to the cart as well as add a name & email input field.
When I go to console log in Chrome for the focusout event for the fields they show the values but when trying to use a Checkout button, I am not able to pass the data within the Checkout click outside of a nested function even with a global variable.
--JS--
var formname;
$(document).ready(function() {
...
$(document).on('click', '#check_out_cart', function(){
$('#cart-popover').popover({
html : true,
container: 'body',
content:function(){
return $('#popover_content_wrapper').html();
}
});
$(document).on('click', '#cart-popover', function(){
$('input#namef').focus();
});
$('input#namef').on('focusout', function(){
formname= $('input#namef').val();
console.log(formname);
});
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
console.log("Name is "+formname);
...
});
});
--HTML--
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Menu</span>
<span class="glyphicon glyphicon-menu-hamburger"></span>
</button>
</div>
<div id="navbar-cart" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
<span class="glyphicon glyphicon-shopping-cart-2x"></span>
<span class="badge"></span>
<span class="total_price">$ 0.00</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="popover_content_wrapper" style="display: none">
<span id="cart_details"></span>
<div>
<form method="POST">
Name: <input type="text" id="namef" >
Email: <input type="text" id="emailf" >
<input type="hidden" name="scart_add" value="1" /><br><br>
</div>
<div align="right">
<button type="button" class="btn btn-primary" id="check_out_cart">
<span class="glyphicon glyphicon-shopping-cart"></span> Check out
</button>
<button type="button" class="btn btn-default" id="clear_cart">
<span class="glyphicon glyphicon-trash"></span> Clear
</button>
</div>
</form>
</div>
</div>
<div id="display_item">
</div>
...
</div>
I am expecting the value from the input#namef text to appear in the console.log ...formname variable but it just shows as "".
The event for focusout isn't added to the input until you click the button:
Also, I don't know if it is how you copied and pasted your HTML and Javascript, but it was throwing errors when I put it into a fiddle.
Move this outside of the button click handler as Rory pointed out:
var formname;
$(document).ready(function() {
//Now focusout handler is added on DOM Ready instead of when you click the button
$('input#namef').on('focusout', function(){
formname= $('input#namef').val();
console.log(formname);
});
$(document).on('click', '#check_out_cart', function(){
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
console.log("Name is "+formname);
});
});
Here is a working fiddle: https://jsfiddle.net/hqgv7zsa/
This is a race condition, of sorts.
On document.ready event, you are setting a click event handler
Inside the click handler, you are setting the focusout event handler
Since the click handler is still executing,
immediately, the code runs to show value of scart and formname.
At that time, formname is still empty because the current function
(click event handler) is still executing, and the focusout event, even
if it fires, will fire after that code is executed.
You should move the focusout handler declaration code outside of the click handler code, which will then set both handlers on document.ready() event.
Here's a breakdown of what's happening and when:
var formname;
$(document).ready(function() {
This fires when DOM is loaded (document.ready event)
$(document).on('click', '#check_out_cart', function(){
This fires when user clicks on some element with ID check_out_cart
$('input#namef').on('focusout', function(){
This event handler is only being set once user clicks on cart, but it is not yet executed!
formname= $('input#namef').val();
console.log(formname);
});
This code fires once the event handler has been set for focusout, but still has not executed. Even if a focusout event is fired, it will only execute when the current function exits.
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
Correctly, you will see that formname is empty at this point.
console.log("Name is "+formname);
...
});
});
Hope this explains the flow you're seeing;
Quick fix as in Ryan Wilson's answer, move the focusout handler declaration to the scope of the document.ready handler, outside the click handler.
Using the solution from Unable to fetch values from an input element in Bootstrap's popover, I was able to adjust my JS code to fetch the values with a .find within the .popover-content class that was added by the popover JS.
var formname;
var formemail;
$(document).ready(function() {
//shopping cart
/*load functions*/
load_product();
load_cart_data();
$('#cart-popover').popover({
html : true,
container: 'body',
content:function(){
return $('#popover_content_wrapper').html();
}
});
$(document).on('click', '#cart-popover', function(){
$('input#namef').focus();
});
$(document).on('focusout', '#namef', function(){
formname = $('.popover-content').find('#namef').val();
});
$(document).on('focusout', '#emailf', function(){
formemail = $('.popover-content').find('#emailf').val();
});
$(document).on('click', '#check_out_cart', function(){
var scart_add = $("input[name='scart_add']").val();
var nameval = $("input#namef").val();
alert("Scart value is "+scart_add);
alert("Name is "+formname);
alert("Email is "+formemail);
});
});
When clicking button on elements, overlay box only works with first one, not the rest
I tried already to add 2 classes but not working as I read that that might be the issue, but I am not able to make it work properly.
<div class="container">
<input type="button" value="Contactar ahora" id="Overly" class="overly"
/>
</div>
<div id="ogrooModel" class="modalbox ogroobox" >
<div class="dialog">
<button title="Close" onClick="overlay()" class="closebutton" id="close">close</button>
<div style="min-height: 150px;">
</div>
</div>
</div>
<script>
//only javascript
document.getElementById("Overly").addEventListener("click", function(){
var e =document.getElementsByClassName("modalbox");
e[0].style.display = 'block';
}) ;
document.getElementById("close").addEventListener("click", function(){
var e =document.getElementsByClassName("modalbox");
e[0].style.display= 'none';
});
</script>
What exactly to change in that code so the rest of elements display the box after clicking on button?
You don't need onClick="overlay()" for your close button, as you are already binding it with a click event listener in your script.
when user click - 'booking' container, 'open_contents' have to show.
when user mouseout of 'open_contents' container, it have to hide or click outside 'open_contents' or anywhere on 'body' of the page.
with present below code, above point 1 works ok. But, i have increment/decrement button on 'open_contents' container. When user click button, 'open_contents' getting hide on every click. it should not get hide when i click button element on 'open_contents' container.
Please let me know your available comments.
HTML:
<div class="booking">
<div class="head">Ticket Booking</div>
</div>
<div id="open_contents" class="open_contents">
<div class="c_class">
<button type="button" class="btn btn-default minus" id="group-btn-minus" disabled="disabled" data-type="minus" data-field="quant[1]">
<span class="glyphicon glyphicon-minus"></span>
</button>
<input type="text" name="quant[1]" class="form-control group-input minus-plus-input" value="1" min="1" max="10">
<button type="button" class="btn btn-default plus" id="group-btn-plus" data-type="plus" data-field="quant[1]">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
JS:
$(document).mouseup(function (e)
{
var $nonGroupBooking = $('.open_contents');
if (!$nonGroupBooking.is(e.target)
&& $nonGroupBooking.has(e.target).length === 0);
{
$nonGroupBooking.hide();
}
});
If you have bound the onclick event to $(document), all elements inside $(document) on click will also be considered as $(document).clicked
To stop the event bubbling up the event, you could use e.stopPropagation, read more on https://api.jquery.com/event.stoppropagation/
Here please try my example - https://jsfiddle.net/w07gnzgg/1/
I changed the $(".booking").on("click") behavior to show the .open_contents and also disabled $(".open_contents").on("mouseleave") event by default
Bind a click handler to the document to hide the contents, but also add a click handler to the contents that stops propagation (prevents the click event from reaching the document handler).
$(document).on('click', function(e) {
$('.open_contents').hide();
});
$('.open_contents').on('click', function(e) {
e.stopPropagation();
});
I'm having a problem with jQuery .not() not working.
I've got a pricing table with 3 products, when you mouse over each of the products a description appears and then disappears on mouse out so far everything works fine.
The problem however is that on page load one of the three products (each held in an <aside>) will have a .selected class applied to it and I need the mouseenter/leave function to not run on this <aside>.
The only caveat is that clicking any of the <button>'s in each <aside> will remove the .selected class from it's current <aside> and apply to the <button>'s <aside> parent (I've not included the JQ for this as it's just a dead simple .addClass).
Code example of what I currently have is below, thanks in advanced.
jQuery
$(".pricing3 aside").not('.selected').mouseenter(function() {
$(".desc", this).stop().slideDown('slow');
})
.mouseleave(function() {
$(".desc", this).stop().slideUp('slow');
});
HTML
<div class="pricing3">
<aside>
<i class="fa fa-clock-o"></i>
<h3>1 Hour Pass</h3>
<p class="desc">Description</p>
<p class="pricing">£XX</p>
<button type="submit">BUY NOW</button>
</aside>
<aside class="selected">
<i class="fa fa-clock-o"></i>
<h3>8 Hour Pass</h3>
<p class="desc">Description</p>
<p class="pricing">£XX</p>
<button type="submit">BUY NOW</button>
</aside>
<aside>
<i class="fa fa-clock-o"></i>
<h3>24-7-365 Access</h3>
<p class="desc">Description</p>
<p class="pricing">£XX</p>
<button type="submit">BUY NOW</button>
</aside>
</div>
Need to use event delegation as the target element selection is based on a dynamic state
$(".pricing3").on('mouseenter', 'aside:not(.selected)', function () {
$(".desc", this).stop().slideDown('slow');
}).on('mouseleave', 'aside:not(.selected)', function () {
$(".desc", this).stop().slideUp('slow');
});
It can be written slightly differently as
$(".pricing3").on({
mouseenter: function () {
$(".desc", this).stop().slideDown('slow');
},
mouseleave: function () {
$(".desc", this).stop().slideUp('slow');
}
}, 'aside:not(.selected)')
As the class is shifting you'd be better off checking for the class inside the event handler
$(".pricing3 aside").on('mouseenter mouseleave', function() {
if ( !$(this).hasClass('selected') ) {
$(".desc", this).stop().slideToggle('slow');
}
});
If I understand you correctly, the problem is that you want the .selected to be removed, and then the mouseenter() to run on it as if it hadn't had the .selected on it in the first place?
If this is the case, you should attach your event handler higher up the DOM tree, and use on() to filter down to the <aside>s This way you can flip/flop the class all you want, and the event handler will work as expected. As it's coded, you are only applying the filter at page load, so the state change of the class has no effect.