How to close an alert box when clicking on it? - javascript

Made this custom alert box:
<script type="text/javascript">
$(function () {
var $alert = $('#alert');
if ($alert.length) {
var alerttimer = window.setTimeout(function () {
$alert.trigger('click');
});
$alert.animate({ height: $alert.css('line-height') || '80px' }, 200).click(function () {
window.clearTimeout(alerttimer);
$alert.animate({ height: '0' }, 200);
});
}
});
</script>
I want it to be open until the user chooses to click on it or anywhere else on the screen. How do I make this happen?

Assuming that clicking anywhere (in, or out, of the alert box itself) is supposed to hide/remove the alert:
$('body').click(
function(){
if ($alert.is(':visible')){
$alert.hide();
}
});
should work, I think.

If you want to justs get rid of it, try calling the hide() function when an onclick event is triggered.
$.click(function() {
$alert.hide();
});

The top answer here is excellent IMO. It covers the part about anywhere else on the screen.
The way to do it is to bind a click event to the body and stop propagation on any event that happens inside the area that isn't supposed to trigger closing the alert.

Related

Can you stop the jQuery focusout from firing when losing focus?

I've got an input box that I want to have save its value when it loses focus.
Pretty straightforward stuff and I'm able to get that done via jQuery's focusout event.
The problem however, is that I want to NOT fire the focusout event when the user clicks on an "X" icon next to the input box (example shown below)
So when the user tabs out of this input box, or clicks outside of the box or they click the green checkbox it should fire the focusout event... but if they click the red "X", it should NOT fire the focusout.
Is this possible to do with JavaScript / jQuery?
EDIT:
Some of you have recommended using event.relatedTarget, but it seems like that's returning null. I'll include my code in question for clarity:
// This is the cancel button with the red X
$("body").on("click", "span[id*='Cancel']", function(e)
{
showLabel($(this));
});
// this is the code to trigger the blur / focusout event
// trouble is that the "e.relatedTarget" is null
$("body").on("focusout", "input, textarea", function (e) {
if($(e.relatedTarget).is("span[id*='Cancel']")){
return false;
}
$(this).siblings("span[id*='OK']").trigger("click");
return false;
});
Here's a screen grab of me debugging this in JS (you'll see that the $(e.relatedTarget) selector returns nothing):
You can cancel de event returning the focus to previous element.
$('#inputText').focusout(function(event) {
setTimeout(function(){
if (document.activeElement.id == "btnCancel") {
$(event.target).focus();
return false;
}
},1);
});
This jsFiddle shows how to do it: https://jsfiddle.net/mpervh3t/
Hope it helps
You must use relatedTarget like this :
$(document).ready(function(){
$(".btn").on("focusout",function(e){
if($(e.relatedTarget).hasClass("red")) {
alert("You clicked on X button");
}
else {
alert("Fire Focus out")
}
})
})
Final code :
<!DOCTYPE html>
<html>
<head>
<style>
.gr {
color: green;
}
.red {
color: red;
}
</style>
</head>
<body>
<input type="text" class="btn"><button class="gr">Ok</button><button class="red">X</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".btn").on("focusout",function(e){
if($(e.relatedTarget).hasClass("red")) {
alert("You clicked on X button");
}
else {
alert("Fire Focus out")
}
})
})
</script>
</body>
</html>
As per my comment:
"I have had to do a similar type of thing with a blur event. Basically what I had to do was call a setTimeout on the blur to execute my function to save the data, and then on the click event of the X, cancel the timeout. That way, unless the X is clicked, the save function will fire. The delay can be pretty negligable, too."
I found the relevant code
var sliderTimeout = null;
$(".slider-trigger").on("blur", function () {
sliderTimeout = setTimeout(function () {
$(".slider").hide();
}, 100);
});
$(".ui-slider-handle").on("focus", function () {
clearTimeout(sliderTimeout);
});
Here is the full demo of the code in action. It does much more than demonstrate this, but if you examine the behavior of focusing/blur on the "margin" input, you will see that if you blur the margin input, the slider hides, but if you click on the slider, it cancels the hide and stays shown. It's the exact same concept, just a slightly different application.
Here, I did the thing.
https://jsfiddle.net/kowmLf2a/1/
In the blur event I target the related target. See if that related target is the item that I don't want to blur with. If it is then return false.
Code for reference:
$('#input').blur(function(event){
if($(event.relatedTarget).is('#bt2')){
return false;
}
alert($(this).val());
});

Clicking to see the dropdown menus

<script>
$(document).ready(function() {
$("#services").click( function() {
$(".subMenus").fadeToggle("slow")
});
});
</script>
This is my code. I can hide and show the dropdown(subMenus) with this code. I want to show the dropdown in my first click which it works but I want to go to a link when I clicked to services for the second time. How can I do?
There is a perfect way for you
$("#services").one('click', function() {
$(".subMenus").fadeToggle("slow")
});
You can do this be checking the visibility of your element. When it's not visible show it, when it is move to your link:
$("#services").click( function() {
if($(".subMenus").is(":visible"))
window.location = "yourLinkHere";
else
$(".subMenus").fadeToggle("slow");
});

Javascript function interacts with other function

I am completely new to javascript (and jquery) and have been experimenting with drop down menus the past couple of days. I found this one fancy notification menu, and I tried to see what happens when I have two of them on the page. Anyways, I made a quick example of my problem here:
http://jsfiddle.net/rgt03mu4/24/
The problem is that I can have both notification containers open up if I click on both.
If I am already clicked on one of the bells, then I click on the other, it should close the other one. Instead it keeps it open, and even when you click on the other container one, it still doesn't close it. You have to click off the page or click the notification bells. I am trying to make it to where you can only have one open at a time. So in order to do this, I tried changing the names of the functions:
As you can see:
$(function() {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function() {
nContainer.fadeToggle(300);
return false;
});
//page click to hide the popup
$(document).click(function() {
nContainer.hide();
});
//popup notification bubble on click
nContainer.click(function() {
return false;
});
});
I added the next function to be called test(), which you would think, since it's an entirely new function it would work differently. Instead, the error still persists.
What am I doing wrong? I even gave the the new bell it's own divs and link name. I also renamed container to container2.
Set the global variable for your container:
var nContainer = $(".notification-popup-container");
var nContainer2 = $(".notification2-popup-container");
$(function() {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function() {
nContainer.fadeToggle(300);
nContainer2.hide(); //hide the second container
return false;
});
//page click to hide the popup
$(document).click(function() {
nContainer.hide();
});
//popup notification bubble on click
nContainer.click(function() {
return false;
});
});
And you can do same with other function.
DEMO
There is no need to give the popup containers different classnames.
I would give the a-tags a common classname instead of an id. The href can be used to identify the target popup, so the binding between the link and the target popup is set in the origin of action. The JS part would be abstracted and could be reused.
<a class='notification-link' href='#firstpopup'>X</a>
<a class='notification-link' href='#secondpopup'>X</a>
<div class='notification-popup-container' id="firstpopup">
... firstpopup
</div>
<div class='notification-popup-container' id="secondpopup">
... secondpopup
</div>
The click handler first hides all the popups before opening a new one.
$(".notification-link").click(function () {
$(".notification-popup-container").hide();
var targetId = $(this).attr('href');
$(targetId).fadeIn(300);
return false;
})
working example: http://jsfiddle.net/qyLekdwk/
The problem here is how the event propgation is handled
$(function () {
var nContainer = $(".notification-popup-container");
//notification popup
$("#notification-link").click(function () {
nContainer.fadeToggle(300);
});
//page click to hide the popup
$(document).click(function (e) {
if (!$(e.target).closest('#notification-link, .notification-popup-container').length) {
nContainer.hide();
}
});
});
$(function test() {
var nContainer2 = $(".notification2-popup-container");
//notification popup
$("#notification2-link").click(function test() {
nContainer2.fadeToggle(300);
});
$(document).click(function (e) {
if (!$(e.target).closest('#notification2-link, .notification-popup-container').length) {
nContainer2.hide();
}
});
});
Demo: Fiddle

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

Hiding Bootstrap Popover on Click Outside Popover

I'm trying to hide the Bootstrap Popover when the user clicks anywhere outside the popover. (I'm really not sure why the creators of Bootstrap decided not to provide this functionality.)
I found the following code on the web but I really don't understand it.
// Hide popover on click anywhere on the document except itself
$(document).click(function(e) {
// Check for click on the popup itself
$('.popover').click(function() {
return false; // Do nothing
});
// Clicking on document other than popup then hide the popup
$('.pop').popover('hide');
});
The main thing I find confusing is the line $('.popover').click(function() { return false; });. Doesn't this line add an event handler for the click event? How does that prevent the call to popover('hide') that follows from hiding the popover?
And has anyone seen a better technique?
Note: I know variations of this question has been asked here before, but the answers to those questions involve code more complex than the code above. So my question is really about the code above
I made http://jsfiddle.net/BcczZ/2/, which hopefully answers your question
Example HTML
<div class="well>
<a class="btn" data-toggle="popover" data-content="content.">Popover</a>
<a class="btn btn-danger bad">Bad button</a>
</div>
JS
var $popover = $('[data-toggle=popover]').popover();
//first event handler for bad button
$('.bad').click(function () {
alert("clicked");
});
$(document).on("click", function (e) {
var $target = $(e.target),
var isPopover = $target.is('[data-toggle=popover]'),
inPopover = $target.closest('.popover').length > 0
//Does nothing, only prints on console and wastes memory. BAD CODE, REMOVE IT
$('.bad').click(function () {
console.log('clicked');
return false;
});
//hide only if clicked on button or inside popover
if (!isPopover && !inPopover) $popover.popover('hide');
});
As I mentioned in my comment, event handlers don't get overwritten, they just stack. Since there is already an event handler on the .bad button, it will be fired, along with any other event handler
Open your console in the jsfiddle, press 5 times somewhere on the page (not the popover button) and then click bad button you should see clicked printed the same amount of times you pressed
Hope it helps
P.S:
If you think about it, you already saw this happening, especially in jQuery.
Think of all the $(document).ready(...) that exist in a page using multiple jquery plugins. That line just registers an event handler on the document's ready event
I just did a more event based solution.
var $toggle = $('.your-popover-button');
$toggle.popover();
var hidePopover = function() {
$toggle.popover('hide');
};
$toggle.on('shown', function () {
var $popover = $toggle.next();
$popover.on('mousedown', function(e) {
e.stopPropagation();
});
$toggle.on('mousedown', function(e) {
e.stopPropagation();
});
$(document).on('mousedown',hidePopover);
});
$toggle.on('hidden', function () {
$(document).off('mousedown', hidePopover);
});
short answer
insert this to bootstrap min.js
when popout onblur will hide popover
when popout more than one, older popover will be hide
$count=0;$(document).click(function(evt){if($count==0){$count++;}else{$('[data-toggle="popover"]').popover('hide');$count=0;}});$('[data-toggle="popover"]').popover();$('[data-toggle="popover"]').on('click', function(e){$('[data-toggle="popover"]').not(this).popover('hide');$count=0;});
None of the above solutions worked 100% for me because I had to click twice on another, or the same, popover to open it again. I have written the solution from scratch to be simple and effective.
$('[data-toggle="popover"]').popover({
html:true,
trigger: "manual",
animation: false
});
$(document).on('click','body',function(e){
$('[data-toggle="popover"]').each(function () {
$(this).popover('hide');
});
if (e.target.hasAttribute('data-toggle') && e.target.getAttribute('data-toggle') === 'popover') {
e.preventDefault();
$(e.target).popover('show');
}
else if (e.target.parentElement.hasAttribute('data-toggle') && e.target.parentElement.getAttribute('data-toggle') === 'popover') {
e.preventDefault();
$(e.target.parentElement).popover('show');
}
});
My solution, works 100%, for Bootstrap v3
$('html').on('click', function(e) {
if(typeof $(e.target).data('original-title') !== 'undefined'){
$('[data-original-title]').not(e.target).popover('hide');
}
if($(e.target).parents().is('[data-original-title]')){
$('[data-original-title]').not($(e.target).closest('[data-original-title]')).popover('hide');
}
if (typeof $(e.target).data('original-title') == 'undefined' &&
!$(e.target).parents().is('.popover.in') && !$(e.target).parents().is('[data-original-title]')) {
$('[data-original-title]').popover('hide');
}
});

Categories

Resources