Javascript - Hide a tooltip after N seconds, but on my script - javascript

I'm trying to show a tooltip at the same time that my current script shows a div (gift) if a condition is met:
if(total > 999 && total < 2999) { $('#gift-1').show();
The same goes for #gift-2 :
if(total > 3000 && total < 4500) { $('#gift-2').show();
At that moment the corresponding tooltip should be visible:
#gift-1 = .tooltip-1
#gift-2 = .tooltip-2
And these should be shown only for 9 seconds, then disappear until the div ( #gift -1 or the div #gift-2 ) is shown again:
I tried something like this, but it has not worked for me:
if(total > 999 && total < 2999) { $('#gift-1').show();
$('.tooltip-1').fadeOut('slow');},9000);
I am learning JS (novice, level 0) and the truth is that I do not know
how I should approach this issue.
Any ideas...?
Thank in advance!
//-------------
HTML
<div class="tooltip-1"></div>
<div class="tooltip-2"></div>
<div id="gift-1"></div>
<div id="gift-2"></div>
CSS
.tooltip-1,.tooltip-2 {display:none}
Script
$(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-1').show();
}
else{
$('#gift-1').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();
});
// -------------------------------------------------
$(document).ready(function(){
function manageRegaloDos() {
var totalStorage = Number(localStorage.getItem("total"));
var total = Number($("#total").val().replace(".",""));
if(totalStorage != null && total === 0) {
total = totalStorage;
}
if(total > 3000 && total < 4500) {
$('#gift-2').show();
}
else{
$('#gift-2').hide();
}
}
$(document).on('click', function (event) {
const target = event.target;
if (target.matches('.comp-clone') || target.matches('.bbp')) {
manageRegaloDos();
localStorage.setItem('total', Number($("#total").val().replace(".","")));
}
});
manageRegaloDos();
});

it is a bit difficult to exactly grasp all of your question. A fiddle (jsfiddle.net) is always helpful so maybe next time you can make one.
However, if I understand your question correctly the problem is not showing the tooltip but fading it out after 9 seconds, right?
I think you can change this code:
if(total > 999 && total < 2999) {
$('#gift-1').show();
$('.tooltip-1').fadeOut('slow');
},9000);
... to this code: (actually your code probably will produce a syntax error?):
if(total > 999 && total < 2999) {
$('#gift-1').show();
$('#tooltip-1').show(); // Maybe you did this already then you don't need this line.
window.setTimeout(function(){
$('.tooltip-1').fadeOut('slow');
},9000);
}
EDIT: To respect the additional info that a tooltip should only show once there are various ways to go. One would be to store the tooltips in eg. a window. variable. The other would be via CSS classes. I use CSS classes here (this is untested code):
if(total > 999 && total < 2999) {
$('#gift-1').show();
if (!$('#tooltip-1').hasClass('alreadyShown')) {
$('#tooltip-1').show().addClass('alreadyShown');
window.setTimeout(function(){
$('.tooltip-1').fadeOut('slow');
},9000);
}
}

Related

Add classes to div on 12 different pages

I need to add a class to a div on 12 different pages. Bellow is the code I've tried to use that don't work.
<script>
window.onload = init;
var divsWithClass = null;
function init() {
if (window.location.href.indexOf("page1") >= -1 &&
window.location.href.indexOf("page2") >= -1 &&
window.location.href.indexOf("page3/") >= -1 &&
window.location.href.indexOf("page4") >= -1 &&
) {
this.divsWithClass = document.getElementsByClassName("sub-menu");
var index = 0;
while (index < divsWithClass.length) {
divsWithClass[index].className += "et_pb_slide_dropdown_opened";
index++;
}
}
console.log(divsWithClass);
}
</script>

add multiple numbers to count jquery

this is the dead script for my shooter game (the buttons are just for testing)
but for some reason i cant figure out how to add 10 instead of 1
this is what i have now:
(function(){
const buttons = document.querySelectorAll('.counterBtn')
let count= 0
//Add event listeners and functionailty to each button
buttons.forEach(function(button){
button.addEventListener('click', function(){
//buttons
if (button.classList.contains('-1')){
count--
} else if (button.classList.contains('+1')){
count++
} else if (button.classList.contains('+10')){
}
//Select the counter text
const counter = document.querySelector('#counter')
counter.textContent = count
//dead / alive
if (count <= 0 ){
counter.style.color = 'red'
console.log("dead")
} else if (count > 0){
counter.style.color = 'lightgreen'
console.log("alive")
} else {
counter.style.color = '#000000'
}
if (count <= 0) {
alert ("you died")
} else if (count > 100 ) {
alert ("u r ful health")
} else {
return
}
})
})
})()
can someone please help me?
Use +=, for example:
count += 10
Of course this also works, but is more verbose:
count = count + 10
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment

Show a div only when a value = 0

I have a problem with this script.
The script shows to me the hidden div #regalo if #total is between 99.99 and 299.99 ... ok, but (now), I also need to show the hidden div #alert when #total is 0 (zero), and be available to show if values ​​of #total more than 1 , and only when the screen is in landscapeand mode...
Truth is that I can't find a way to modify the code.
Any ideas?
$(document).ready(function() {
function manageRegalo() {
var totalStorage = Number(localStorage.getItem("total"));
var total = parseFloat($("#total").val());
if (totalStorage != null && total === 0) {
total = totalStorage;
}
if(total > 99.99 && total < 299.99) {
console.log("PASS");
$('#regalo').show();
//if(total === 0) {
//if(total == 0) {
//if(total < 1) {
//$('#alert').hide();
//}
//else{
//$('#alert').show();
//};
if (localStorage.getItem('suppress_gift_tooltip_1') == null) {
$('.tooltip').show();
window.setTimeout(function() {
$('.tooltip').fadeOut('slow');
}, 9000);
//--------------------
if (!$("#notify")[0].paused) { //play audio
$("#notify")[0].pause(); //play audio
$("#notify")[0].currentTime = 0; //play audio
} else { // play audio
setTimeout(function() { //play audio
$("#notify")[0].play(); //play audio
})}; //play audio
//--------------------
localStorage.setItem('suppress_gift_tooltip_1', 'true')
}
} else {
console.log("FAIL");
$('#regalo').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()));
}
});
manageRegalo();
});
#alert {
display: none
}
#media screen and (max-width:999px) and (orientation:landscape) {
#alert {
display: block !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="regalo"></div>
<div id="alert"></div>
<!-- I need to show this div when the #total equals zero -->
This is where consistent and sensible indentation is important. All of the conditions you're trying are all valid:
if (total === 0)
if (total == 0)
if (total < 1)
Any one of them by itself will work just fine. But the problem is that they're not by themselves. They're inside another condition:
if (total > 99.99 && total < 299.99)
When that condition is true, none of your above conditions can possibly be true. The same variable (total) can not be greater than 99.99 and equal to 0 at the same time.
Don't put the test for zero inside of that if block:
if (total > 99.99 && total < 299.99) {
if (total === 0) {
//...
}
}
Put it outside of that if block:
if (total > 99.99 && total < 299.99) {
//...
}
if (total === 0) {
//...
}
Have a try with this
function manageRegalo() {
var totalStorage = Number(localStorage.getItem("total")) || 0;
var total = parseFloat($("#total").val());
if (totalStorage && total === 0) {
total = totalStorage;
}
$('#regalo').toggle(total > 99.99 && total < 299.99);
$("#alert").toggle(!total);
if ($('#regalo').is(":visible") && localStorage.getItem('suppress_gift_tooltip_1')!="true") {
$('.tooltip').show();
localStorage.setItem('suppress_gift_tooltip_1',"true");
window.setTimeout(function() {
$('.tooltip').fadeOut('slow');
}, 9000);
}
}

Dynamically changing images in the DOM

I'm trying to add a health meter representation to a game I'm working on and stuck on a DOM manipulation problem. The idea is that there is an image that deteriorates in various stages as the player loses health. Here is an example of what I have so far.
var healthDisplay = document.getElementById('healthDisplay');
if (heroHealth > 75) {
healthDisplay.src = 'image1.png';
} else if (heroHealth < 75 || heroHealth > 30){
healthDisplay.src = 'image2.png';
} else {
healthDisplay.src = 'image3.png';
};
That's just the basics of it. My question is about the next step. What do I add to make it so the script is constantly checking to see if these parameters are true or false? Would it be best to put it in a while loop, or add an event listener?
You'd want to put it in a setinterval.
//this is assuming that heroHealth, and healthDisplay
//are available to this function already
//either through closure or they are global
//variables etc.
function checkHealth () {
if (heroHealth > 75) {
healthDisplay.src = 'image1.png';
} else if (heroHealth < 75 && heroHealth > 30){
healthDisplay.src = 'image2.png';
} else {
healthDisplay.src = 'image3.png';
};
}
setInterval(checkHealth, 100);
The setInterval calls a function repeatedly at certain intervals. This example is set to 100 milliseconds. This way as the hero's health goes up and down, the image src will change as the function fires.
Depending on how your game is set up and how the health is stored, you could wire up the function to an on change event:
<input type="textbox" id="heroHealthCheckBox"
onchange="checkHeroHealth(this.value)"/>
function checkHeroHealth(health) {
var heroHealth = parseInt(health);
if (heroHealth > 75) {
healthDisplay.src = 'image1.png';
} else if (heroHealth < 75 && heroHealth > 30){
healthDisplay.src = 'image2.png';
} else {
healthDisplay.src = 'image3.png';
}
}
I also changed the second conditional from
heroHealth < 75 || heroHealth > 30
to this
heroHealth < 75 && heroHealth > 30

Trying to debug a custom .sort in a JS array

A link to the Plunker.
I've been working on a button and list system in jQuery for awhile now. Recently I decided to make my code more reproducible. I want to make it so I just have to add classes or IDs, and I don't have to add any additional code. I'm very close to doing that for my entire site. So if you go to this site specifically you will see it in action.
If you click on any buttons, in any order, it will arrange chronologically.
The bugs come from closing them.
If you click at least three, close the middle one, then click a new button, the sort function falls apart and that closed middle one is now floating with the wrong class.
Below is my current jQuery. On my site, ignore the "All Years" button. I'll work on that after I figure out this bug.
//the variables needed for the floating buttons
var groupArray = $(".yearGroup");
var buttonArray = $(".buttonGroup");
var hideGroupArray = $(".hideGroup");
var closeBarArray = $(".closeBar");
var closeBar = $("#allCloseBar");
var allButtonArray = [];
sortElements = function(a,b)
{
if (a.text() < b.text())
{
return -1;
}
else if (a.text() > b.text())
{
return 1;
}
else
{
return 0;
}
}
$.each(buttonArray, function(i, item) {
$(this).click(function(){
console.log($(buttonArray[i]).text())
console.log($(closeBarArray[i]).text())
//for removing the tooltip when the button is clicked. Mostly for Firefox bug
$(".ui-tooltip-content").parents('div').remove();
$(hideGroupArray[i-1]).slideToggle(slideToggleDuration, function(){
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top - 25}, {duration: timeDuration, easing: 'easeOutBack'});
$(buttonArray[i]).toggleClass("float", 1200);
if ($(groupArray[i-1]).height() > 0)
{
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
closeBar.addClass("floatCloseBar");
$(closeBarArray[i]).hide();
allButtonArray.splice(0, 0, $(buttonArray[i]));
var timer;
var delay = 1500;
$(buttonArray[i]).hover(function() {
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
var link = $(groupArray[i-1]);
var offset = link.offset();
var top2 = offset.top;
var left = offset.left;
var bottom = top2 + $(groupArray[i-1]).outerHeight();
//bottom = Math.abs(bottom - offset.top);
var right = $(window).width() - link.width();
right = Math.abs(offset.left - right);
var scrollDuration = 0;
if (inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
//console.log("fast");
scrollDuration = 500;
//$(group).addClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top <= $(groupArray[i-1]).offset().top && allButtonArray.length == 1)
{
//console.log("fast");
scrollDuration = 500;
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 495 && $(buttonArray[i]).offset().top < 1700 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1000;
//console.log("slow");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 1701 && $(buttonArray[i]).offset().top < 3000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1500;
//console.log("slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 3001 && $(buttonArray[i]).offset().top < 6000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2000;
//console.log("much slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 6001 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2500;
console.log("the slowest");
//$(group).removeClass("hoverYear");
}
else
{
scrollDuration = 500;
}
//to prevent the various hover states to take control when the button isn't floating
if (!($(buttonArray[i])).hasClass("float"))
{
scrollDuration = 0;
console.log("doesnt have class")
}
// on mouse in, start a timeout
timer = setTimeout(function() {
//the delay for the hover scroll feature
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top}, scrollDuration, 'easeInOutCubic');
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
$.each(allButtonArray, function(j, val){
$(allButtonArray[j]).appendTo(closeBar);
console.log(allButtonArray.length);
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
//Changes the width of the buttons based upon how many are on the screen
if (allButtonArray.length > 7)
{
$("float").css('width', '7%');
$(val).css('width', '7%');
$(allButtonArray[0]).css('width','7%');
allButtonArray.sort(sortElements);
//console.log(val);
}
else if (allButtonArray.length <= 7)
{
$(val).css("width", '10%');
$("float").css("width", '10%');
allButtonArray.sort(sortElements);
//console.log(val);
}
});
}
if ($(groupArray[i-1]).height() == 0)
{
$(buttonArray[i]).css("width", '50%');
allButtonArray.splice(allButtonArray.indexOf($(buttonArray[i])), 1);
console.log(allButtonArray.length);
$(closeBarArray[i]).show();
$(buttonArray[i]).appendTo($(closeBarArray[i]));
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
}
if (group2001.height() == 0 && group2002.height() == 0 && group2003.height() == 0 && group2004.height() == 0 && group2005.height() == 0 && group2006.height() == 0 && group2007.height() == 0
&& group2008.height() == 0 && group2009.height() == 0 && group2010.height() == 0 && group2011.height() == 0 && group2012.height() == 0)
{
$(closeBarArray[i]).removeClass("floatCloseBar");
htmlBody.animate({scrollTop: revealAllButton.offset().top - 75}, 500);
arrowDown.hide();
arrowUp.hide();
//console.log($(document).height() + " the current height");
}
});
$(buttonArray[i]).toggleClass("openClose");
$(buttonArray[i]).toggleClass("openClose2");
});
});
function inRange(x, min, max){
return (x >= min && x <= max);
}
If you would like a reference to what worked previously, I could post that code. It is much more bulky and much less organized. I've tried many different things to eliminate the bug but I'm at a loss. My knowledge of JS scope is limited.
And thanks for any help, it is very much appreciated.

Categories