Adding a click event to hide a popup - javascript

I have a popup with an id of myPopup.
show is a class that changes the display from none to block.
This is my first time using event handlers and I was looking to get some information on the different types and how to use them.
var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
}

var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
So first of all your if statement will only run once and since the class is only toggled during the function, then the if statement will never be run and so the event won't actually happen.
To fix this maybe try this approach:
var popup_v = document.getElementById("myPopup");
var trueorfalse = false;
function popup() {
if (trueorfalse === false) }
trueorfalse = true; // popup is there
popup_v.classList.toggle("show");
} else {
popup_v.classList.remove("show");
}
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
OR
var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
var trueorfalse = false;
document.addEventListener('click', function(event) {
if (trueorfalse === false) }
trueorfalse = true; // popup is there
popup_v.classList.toggle("show");
} else {
popup_v.classList.remove("show");
}
}
};
I did it these ways because the event listener just checks if the event is happening for how long the application (site) is run.
So you can just check if the class is there or not and then decide depending on that.
Tell me if anything is wrong.

I don't see a need to add the if condition specifically to check if it contains class and it it has remove it.
the toggle method should do both for you, i.e.
on toggle add show class,
on toggle again if show class is present remove it
check this example for reference - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_class

Related

Still struggling with this... Why can't I get fade on mouse out to work?

let icon = document.getElementById('loginIcon');
let content = document.getElementById('loginField');
let head = document.getElementById('header');
let contentVisible = content.style.visibility='visible';
icon.onclick = function() {
if (content.style.visibility='visible') {
content.classList.toggle('fade');
}
else {
content.classList.toggle('fade');
}
}
head.mouseleave = function hideLogin() {
if (contentVisible) {
content.classList.toggle('fade');
}
}
The CSS (fade) works when I click the login icon, but the login field does not disappear when I leave the header as I've instructed. Is my code garbage or is there something I'm missing here?
You'd need to use onmouseleave, whereas you're only using mouseleave.
Try this:
head.onmouseleave = function hideLogin() {
if (contentVisible) {
content.classList.toggle('fade');
}
}
A preferable way to do this would be attach an event listener explicitly like this:
head.addEventListener('mouseleave', e => {
if (contentVisible) {
content.classList.toggle('fade');
}
});
https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event
in your code contentVisible isn't a boolean since you are assign to it the value of the style, about the onClick function it does almost the same in the if and the else part. for this reason it can be generalized as content.classList.toggle('fade');, about the function in mouseover, it do almost the same as the "click" function, so, you can generalize this separated function in just one.
About the way you add the listeners, it's ok, but it's better if you add it with addEventListener because in this way you can add more than one event of the same type to one element.
I made a little refactor to your code for the reasons I write above.
let icon = document.getElementById('loginIcon');
let content = document.getElementById('loginField');
let head = document.getElementById('header');
let contentVisible = content.style.visibility === 'visible';
head.onmouseenter = function hideLogin() {
if (contentVisible) {
content.classList.toggle('fade');
}
}
// Another way
icon.addEventListener("click", toggleContentVisibility);
head.addEventListener("mouseenter", toggleContentVisibility);
function toggleContentVisibility(event) {
if(event.type === "click") {
content.classList.toggle('fade');
}
if(event.type === "mouseenter" && contentVisible) {
content.classList.toggle('fade');
}
}
<div id="loginIcon">
Login icon
</div>
<nav id="header">
<div id="loginField">
Login field
</div>
</nav>

Call a onkeyup function when click on other button jQuery

I have function which has keyup event on input field which is working fine.
I want to trigger this function also upon click on other button.
Here is my function
function validateChild(el) {
var validated = {};
console.log('Remove button clicked');
var dateOfBirthField = $(el).find('.date_of_birth');
$(dateOfBirthField).on("keyup", function () {
var dateOfBirthValue = $(el).find('.date_of_birth').val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
});
}
I'm calling this function on document load
function validateForms() {
$(document).find(".child-form").each(function () {
validateChild(this);
});
}
Here i have click event
.on('click', '.removeButton', function (event) {
validateForms();
});
When i click on this remove button it trigger but stop working after this
console.log('Remove button clicked');
How can i trigger keyup event also on this remove button, or there is better way to do this in javascript.
Can anyone help me with this?
Thanks
I have reviewed your three code blocks. Please try following three code blocks respectively.
Your function
function validateChild(dateOfBirthField) {
var validated = {};
var dateOfBirthValue = $(dateOfBirthField).val();
console.log('Check DoB');
if(validateDateOfBirth(dateOfBirthValue, dateOfBirthField)){
console.log('True');
validated.dateOfBirth = true;
} else {
validated.dateOfBirth = false;
}
validateButton(validated);
}
Call this function on document load
function validateForms() {
$('.child-form').on('keyup', '.date_of_birth', function() {
validateChild(this);
});
}
Click event
.on('click', '.removeButton', function() {
console.log('Remove button clicked');
$('.child-form .date_of_birth').each(function() {
validateChild(this);
});
});

button toggle event onkeyup from body

I need help with this function. Clicking a button, the onkeyup event present in the body tag must be deactivated, and then pressing it again must reactivate
<body onkeyup="NoPreview()">
...
</body>
function NoPreview() {
var preview = true;
if (preview == true) {
document.body.onkeyup = null;
preview = false;
} else {
return true; }
}
the function was deactivated, but clicking again on the button, does not reactivate.
You can keep a global variable and store the status of your setting, like this
<body onkeyup="NoPreview()">
<button onClick="toggleKeyup()">Toggle</button>
</body>
and the js:
var enableKeyup = true;
function toggleKeyup() {
enableKeyup = !enableKeyup;
}
function NoPreview() {
if(enableKeyup) {
// Your code here...
document.body.appendChild(document.createTextNode("."));
}
}
this way you don't have to add and remove events and you can have more settings for your NoPreview function.
Here's a pen: https://codepen.io/wyzix33/pen/bXBPbz
Hope it helps :)
Happy codding!

JQuery trigger element itself in a bind

Can someone explain me why this snippet can't work ?
I can't use specific features like window.location, submit(), (instead of trigger()), because this function is bound to elements that are very differents.
$('a, button').bind('click', function(oEvent, oData) {
var oButton = $(this);
var bSkip = (oData && oData.skip);
if(true === bSkip) {
return true;
} else {
oEvent.preventDefault();
//oEvent.stopPropagation();
if(confirm('This is a confirm box')) {
$(oButton).trigger('click', { skip: true });
}
}
});
Thanks in advance ! ;)
In your case even though the click event gets fired the default behavior of the links may not be triggered because of the constraints imposed by the browser
If I understand what you are trying to do correctly(if the action s not confirmed then cancel the default behavior), then you can achieve it by the below... there is no need to fire the event again
$('a, button').bind('click', function (oEvent, oData) {
if (confirm('This is a confirm box')) {
return true;
} else {
oEvent.preventDefault();
}
});
Demo: Fiddle

jQuery trigger event when click outside the element

$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});

Categories

Resources