how to display alert message only once? - javascript

This is my code to make when click close button then save at localStorage to don't display again:
$('#myAlert .close').on('click', function() {
$('#myAlert').fadeOut(300);
if (typeof localStorage !== 'undefined') {
localStorage.setItem('alert-closed', true);
localStorage.removeItem("hidden");
}
});
The problem that I can't make it display only once, How can make this?

Rearrange if statements, check if localStorage is undefined, also if localStorage.getItem("alert-closed") is equal to null before attaching click event to element.
$(function() {
if (typeof localStorage !== undefined) {
if (localStorage.getItem("alert-cosed") === null) {
$('#myAlert .close').on('click', function() {
$('#myAlert').fadeOut(300);
localStorage.setItem('alert-closed', true);
localStorage.removeItem("hidden");
});
}
} else {
alert("`localStorage is `undefined`")
}
});

Related

JS a div is not showing after page refresh

In registration form I have a 2 radio button, when one button is selected a dropdown list appears. But after register fails, the selected radio button remains but the dropdown list is not shown anymore, I want the dropdown list to be shown after register fail. There should be a solution with local storage but I dont know exactly how to write it.
here is the code, what I should add to make it happen?
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
});
});
So I found the solution finally, I tried and made it :
<script>
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
localStorage.removeItem("last");
});
});
function fix(){
var check = localStorage.getItem("last");
console.log(check);
if (check === 'a') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
else{
$('#cityClient').show();
$('#cityLawyer').hide();
}
}
function save(){
// rdAttorney is a id of the selected radio
if (document.getElementById('rdAttorney').checked) {
localStorage.setItem('last', 'a');
}
else{
localStorage.setItem('last', 'b');
}
}
window.onload = fix();
</script>

Trigger an event when the browser back button is clicked

I am trying to run some code when the browser back button is clicked.
How can i found out browser's back button with out changing the browser history?
I tried the code below.
I got an exception in the else block saying: "event is not defined".
window.onunload = HandleBackFunctionality();
function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Browser back button is clicked…");
} else {
alert("Browser refresh button is clicked…");
}
} else {
if(event.currentTarget.performance.navigation.type == 1)
{
alert("Browser refresh button is clicked…");
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Browser back button is clicked…");
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
use
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});
Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event-argument I checked the code in the browser.
currentTarget is empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.
Please debug the code by yourself by using this and fit it to your needs:
window.onunload = HandleBackFunctionality;
function HandleBackFunctionality(event)
{
console.log(event, window.event);
}
You will see that currentTarget is not set (while event is).
This is the only solution that works for me with IOS safari.
<script>
window.addEventListener( "pageshow", function ( event ) {
var pagehistory = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( pagehistory ) {
// back button event - Do whatever.
}
});
</script>

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.

JQuery Check if input is empty not checking onload?

I am using this code to check if an inputbox is empty or not and it works fine but it only checks check a key is press not when the page loads.
It's does what it should but I also want it to check the status when the page loads.
Here is the current code:
$('#myID').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
Try the following:
$(function() {
var element = $('#myID');
var toggleClasses = function() {
if (element.val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
};
element.on('keyup keydown keypress change paste', function() {
toggleClasses(); // Still toggles the classes on any of the above events
});
toggleClasses(); // and also on document ready
});
The simplest way to do is trigger any of the keyup,keydown etc event on page load. It will then automatically call your specific handler
$(document).ready(function(){
$("#myID").trigger('keyup');
});
try checking the value on a doc ready:
$(function() {
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
EDIT: just as an update to this answer, a nicer approach might be to use toggle class, set up in doc ready then trigger the event to run on page load.
function check() {
var $status = $('#status');
if ($(this).val()) {
$status.toggleClass('required_ok').toggleClass('ok');
} else {
$status.toggleClass('required_ok').toggleClass('not_ok');
}
}
$(function () {
$('#myID').on('keyup keydown keypress change paste', check);
$('#myID').trigger('change');
});
Well then why dont just check the field after the page is loaded?
$(document).ready(function(){
if ($('#myID').val() == '') {
$('#status').removeClass('required_ok').addClass('ok');
} else {
$('#status').addClass('required_ok').removeClass('not_ok');
}
});
$(document).ready(function(){
var checkVal = $("myID").val();
if(checkVal==''){
$('#status').removeClass('required_ok').addClass('ok');
}
else{
$('#status').addClass('required_ok').removeClass('not_ok');
}
});

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