Hide my tooltips with localStorage, but in my script - javascript

With some help in Stackoverflow (I'm novice level 0 in JS), I have achieved that a div gift is shown when it fulfills a condition:
if(total > 999 && total < 2999) {
$('#gift').show();
And then show a tooltip, which will be hidden after 6 secĀ“s:
if(total > 999 && total < 2999) {
$('#gift').show();
$('.tooltip').show();
window.setTimeout(function(){
$('.tooltip').fadeOut('slow');
},6000);
}
OK, work well, but my interest now is that the tooltip is shown only once to the user, for which I have tried to use localStorage, but it does not work for me:
const showTooltip1=localStorage.getItem('tooltip');
if(showTooltip1==='false'){
$('.tooltip').hide();
}
// The section below is not of my interest in the script, but it may be
/*
$('#gift').on('click',function(){
$('.tooltip').fadeOut('slow');
localStorage.setItem('tooltip','false');
});
*/
What am I doing wrong here...?
It will be that the master-script (in each click) is firing the .show (); for the tooltip...?
Thanks in advance!
//-----------------------
Full-Script: (Without local Storage for tooltip )
$(document).ready(function(){
function manageRegalo() {
var totalStorage = Number(localStorage.getItem("total"));
var total = Number($("#total").val().replace(".",""));
if(totalStorage != null && total === 0) {
total = totalStorage;
}
if(total > 999 && total < 2999) {
$('#gift').show();
$('.tooltip').show();
window.setTimeout(function(){
$('.tooltip').fadeOut('slow');
},6000);
}
else{
$('#gift').hide();
}
}
$(document).on('click', function (event) {
const target = event.target;
if (target.matches('.comp-clone') || target.matches('.bbp')) {
manageRegalo();
localStorage.setItem('total', Number($("#total").val().replace(".","")));
}
});
manageRegalo();
});

You haven't indicated what you're writing with setItem, so there's no way for us to know what getItem should be returning.
The logic you're after here is: If getItem returns null, show the tooltip and use setItem to put a value into localStorage so that subsequent checks will prevent the tooltip from showing.
You would need to modify your code along these lines:
if (localStorage.getItem('suppress_gift_tooltip') == null) {
// Your unaltered tooltip code
$('.tooltip').show();
window.setTimeout(function(){
$('.tooltip').fadeOut('slow');
},6000);
// Prevent subsequent display
localStorage.setItem('suppress_gift_tooltip', 'true')
}

The localstorage value will be null if you didn't assign the value. Better you can check with null and assign the boolean for further use.
if( !localStorage.getItem('toolTip') ) {
// operation
localStorage.setItem('toolTip',false);
}
The above condition will be true if toolTip item is not present in the localStorage and if the value of toolTip is false in the localStorage.

Related

Why javascript IF/ELSE doesn't work properly?

I'm new to JavaScript and I want to make username validation on registration form. I don't know what's wrong on my code but I think I have a problem with "IF ELSE" statement.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var usernameLength = $("#username").length;
$("#username").focusout(function() {
checkUser();
});
function checkUser() {
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
});
I expected that when I input more than 5 char until 20 char, the usernameErrorMsg will disappear. The actual result, no matter how many characters that I have input, the error message keeps coming up.
usernameLength is being computed only once, before checkUser() ever runs. You should re-calculate its value inside the callback each time; otherwise, changes to that value will not be visible inside the callback.
Furthermore, if you want to check the length of the test in the input, you need to check $("#username").val().length, not $("#username").length:
function checkUser(){
var usernameLength = $("#username").val().length;
if (usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
$("#username").length is not the length of the characters in the field. It's the amount of elements in the JQuery wrapped set returned from your query. Since only one element will have an id of username, the length is always 1 and your if condition will always be true.
What you'll have to do is get the length of the value in the field:
$("#username").val().length
You'll also want to move the line that gets the value into the focusout event handler so that you are always working with the most current data.
Lastly, it doesn't make much sense to have a function do nothing but call another function, so you can combine the checkUser function with the event callback and simplify the code.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var username = $("#username"); // Find the element just once
$("#username").focusout(function() {
// Each time the user leaves the field, get the current
// amount of characters in the input field
var usernameLength = username.val().length;
// See the difference between the length of the JQuery query and
// the length of the value of the first element in the results?
console.log(username.length, usernameLength);
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your name: <input id="username">
<span id="usernameErrorMsg">ERROR</span>
You need to get the length of input everytime the function checks it.
Currently you calculate the length only once.
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
//calculate the length everytime in the function
var usernameLength = $("#username").val().length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
try this
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
usernameLength = $("#username").length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
});

JavaScript greater than not working

I have a JavaScript snippet:
function verifyFrnds(){
var boxes=$(".matchFrnds:checked").length;
//alert(boxes); its value is 50 when you do alert
var call=1;
$(".matchFrnds").each(function(index){
if($(this).is(':checked')){
call++;
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
//alert(call); value is 1
// 1 >=50 should be false but all the time the condition gets true
if(call >= boxes)
{
window.location.reload();
}
}
});
}
The question is self explanatory. The conditions gets true even when it is not. Not sure if it is due to that it is not treating them as numbers and strings may be, but all the time the condition gets true.
I'm missing some context but try this:
function verifyFrnds() {
var boxes = $(".matchFrnds:checked").length;
$(".matchFrnds:checked").each(function(index) {
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
if(index >= boxes-1) {
window.location.reload();
return false;
}
});
}
use below code
if(parseInt(call) >= parseInt(boxes))
{
window.location.reload();
}
Doesn't window.location.reload() from your post callback resets your checkboxes thus none being checked ?
1 will always be greater than 0
Of course that this depends on how the form is initialized in HTML, but we don't know this from your example.
Maybe if you present to us a more detailed explanation of what you have and what you want to do, we can present you a better solution.

jQuery.css('display') only returns inline

I am trying to get checked options from a table which are set inline. There is a search function, which sets $(element).css('display','none') on objects in which there is no match with the search. Anyways, this piece of code will only return inline, no matter what the elements are set to. Even if I manually set all of them to display: none in the table itself, the alert will return inline for every single object in the table. Is there any solution to this?
JS code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
Fundamentally, css("display") does work, so something else is going on.
I suspect one of two things:
The checkboxes that you're making display: none are never checked, and so you don't see them in your each loop.
You're not making the checkboxes display: none, but instead doing that to some ancestor element of them. In that case, $(this).is(":visible") is what you're looking for.
Here's an example of #2: Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...which outputs:
display property is now: inline-block
visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
Side note: Every time you call $(), jQuery has to do some work. When you find yourself calling it repeatedly in the same scope, probably best to do that work once:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
try following:
$("input:checkbox:checked").each(function(i,o){
console.log($(this).css("display"));
});
working fiddle here: http://jsfiddle.net/BcfvR/2/

Modifying HTML elements using jquery

I am trying to use jquery to add and remove a class from <li> elements according to a variable's value ( i ).
Here is a jsfiddle of what I have done so far http://jsfiddle.net/LX8yM/
Clicking the "+" increments i by 1 ( I have checked this with chrome's javascript console ).
One should be able to click "+" and the class .active should be removed from and added to the <li> elements accordingly.
...I can get the first <li> element to accept the class, that's all...
No need for if statements:
$(document).ready(function (){
$('#add').click(function (){
$('.numbers .active').removeClass('active').next().addClass('active');
});
});
jsfiddle
Do note that I added an 'active' class to first list item. You could always do this via JS if you do not have control over the markup.
Your if..else.. is hanging in document.ready. Wrap the increment inside a function and call it respectively.
Like
$(document).ready(function (){
//variable
var i = 1;
//if statments
function incre(i){ // wrap into a function and process it
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
}
//change i
$('#add').click(function (){
incre(i++); // pass it as a parameter
});
});
Working JSFiddle
This would be easier:
$(document).ready(function(){
var i = 0; // set the first value
$('#something').click(function(){
i++; // every click this gets one higher.
// First remove class, wherever it is:
$('.classname').removeClass('classname');
// Now add where you need it
if( i==1){
$('#one').addClass('classname');
} else if( i==2){
$('#two').addClass('classname');
} else if( i==3){
$('#three').addClass('classname');
}
}):
});
See this code. Initially you have to add class to one.
$(document).ready(function (){
//variable
var i = 1;
$('#one').addClass('active');
//if statments
//change i
$('#add').click(function (){
i++;
if(i == 1){
$('#one').addClass('active');
$('#two').removeClass('active');
$('#three').removeClass('active');
}else if(i == 2){
$('#one').removeClass('active');
$('#two').addClass('active');
$('#three').removeClass('active');
}else if(i == 3){
$('#one').removeClass('active');
$('#two').removeClass('active');
$('#three').addClass('active');
}
});
});
It's being called only once, not in the click event function. This edit of your fiddle works: http://jsfiddle.net/LX8yM/2/
put it in the
'$('#add').click(function (){}'

How do I call this function on blur(), using JQuery?

I have this function, see below:
function checkStartPrice (){
if ($('#StartingPrice')[0].value.length == 0){
alert("The 'Starting Price' cannot be left empty!");
return false;
} else {
var BuyItNowPrice = parseFloat($('#BuyItNowPrice').val());
var StartingPrice = parseFloat($('#StartingPrice').val());
var Reserve = parseFloat($('#Reserve').val());
if((BuyItNowPrice <= StartingPrice) && (StartingPrice > 0)){
alert("The 'Buy It Now' price must be higher...");
return false;
}
if((Reserve <= StartingPrice) && (StartingPrice > 0)){
alert("Your 'Reserve Price' must be higher...");
return false;
}
return true;
}
}
Question: How do I call it on blur? I tried this code below but it doesn't seem to work:
$('#StartingPrice').blur(function(){
checkStartPrice();
});
This is the correct way to call it.
The only reason it may fail is that the #StartingPrice element does not exist at the time of the .blur() call.
If it is present in the page, use this:
$(document).ready(function() {
$('#StartingPrice').blur(checkStartPrice)
})
If it is dynamically added via AJAX, use this:
$(document).ready(function() {
$('#StartingPrice').live('blur',checkStartPrice)
})
Note that the second solution requires at least jQuery 1.4.1

Categories