I know that there are many similar questions, but I can't understand what is the mistake in my if statement.
So basically I want to stop clicking nextBtn once I hover over timeoutArea,
but this: timeoutArea.mouseover != true doesn't seems to work.
const timeoutArea = document.getElementById("slider");
var time = 1;
let interval = setInterval(function() {
if (time <= 20 && window.pageYOffset < 393) {
if (timeoutArea.mouseover != true) {
nextBtn.click();
};
time++;
}
else {
time = 1;
}
}, 2000);
if u are using jquery u can use $('#slider').is(':hover') in if statement.
if u use only pure javascript u can use with one function
example fiddle https://jsfiddle.net/9x5hjpk3/
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
so change
if (timeoutArea.mouseover != true) {
nextBtn.click();
};
to
if (!isHover(timeoutArea)) {
nextBtn.click();
};
Related
I have very little to no knowledge when it comes to using JavaScript. I have 24 of the same image given an id from q1 - q24. my code allows for the 24 images to be changed to image2 one at a time, but I need for it to stop and display a text/alert when image2 is clicked.
<script>
{
let num = 1;
function sequence()
{
let back = 1;
while (back < 25)
{
if(back == 1)
{
document.getElementById("q24").src = "question.jpg";
}
else
{
document.getElementById("q" + (back-1)).src = "question.jpg";
}
back++
}
document.getElementById("q" + num).src = "question2.png";
num = num + 1;
if(num > 24){num = 1;}
}
setInterval(sequence, 500);
}
</script>
Save the interval timer to a variable. Then add a click listener to all the images that stops the timer if the current image is the one showing question2.jpg.
{
let num = 1;
for (let i = 1; i <= 24; i++) {
document.getElementById(`q${i}`).addEventListener("click", function() {
if (i == num) {
clearInterval(interval);
}
});
}
let interval = setInterval(sequence, 500);
function sequence() {
for (let i = 1; i <= 24; i++) {
if (i == num) {
document.getElementById(`q${i}`).src = "question2.jpg";
} else {
document.getElementById(`q${i}`).src = "question.jpg";
}
num = num + 1;
if (num > 24) {
num = 1;
}
}
}
}
While I don't fully understand your use case, you could create a click event listener on the document and check the target's src in it.
document.addEventListener('click', function(e) {
if (e.target.src === 'question2.png') {
alert('Clicked question 2');
}
});
Im new to Javascript and im trying to do a calculation which changes depending on the number that is typed into the input.
However the functions make the output into a NaN, so Im wondering if I can transform the NaN in a normal number(So that I can add hUeCalc and massCalc together and display it as a number) to use or if I have to use another option to do the calculations.
Maybe switch and case might be an option but im not quite sure if they would have the effect I need.
In the Code below you can see the function which is executed when pressed on a button. Right now when I click the button that activates the function calc I get NaN in tax.innerHTML instead of a number.
Thanks in advance.
function calc() {
let hubraum = Number(hubraumComponent.value);
let emission = Number(emissionComponent.value);
let masse = Number(masseComponent.value);
let hUeCalc = Number(function (){
if (Diesel.checked == true) {
((Math.ceil((hubraum/100)))*9.5)+((emission-95)*2);
}
else if (Benzin.checked == true) {
((Math.ceil((hubraum/100)))*2)+((emission-95)*2);
};
});
let masseCalc = Number(function (){
let masseValue;
if (masse <= 2000) {
masseValue = (Math.ceil((masse/200)*5.625));
}
else if (masse >= 3000) {
masseValue =(Math.ceil((masse/200)*6.01));
}
else if (masse >= 3500) {
masseValue = (Math.ceil(masse/200)*6.39);
};
});
// let masseValue = (Math.ceil (masse/200));
let berechnung = (hUeCalc + masseCalc);
tax.innerHTML = (berechnung) + "€";
console.log('Calc has been done');
console.log('hubraum value is ' + hubraum);
console.log('emission value is ' + emission);
console.log('masse value is ' + masse);
console.log('hubraumcalc value is ' + hUeCalc);
console.log('massecalc value is ' + masseCalc);
}
Also here is the HTML incase you want to see the button that activates all of this
<div class="input-field-second-calc" onclick="calc()">
<input type="button" class="btn btn-outline-primary" value="berechnen">
<br>
<a id="tax"></a>
</div>
You need to return a value in your two functions !
When you do :
let hUeCalc = Number(function (){
if (Diesel.checked == true) {
((Math.ceil((hubraum/100)))*9.5)+((emission-95)*2);
}
else if (Benzin.checked == true) {
((Math.ceil((hubraum/100)))*2)+((emission-95)*2);
};
})
You're basically saying please convert the return value of the function to a number and assign it to hUeCalc. But as the function return nothing. It is trying to convert undefined to a number. which give NaN as a result.
The same goes for :
let masseCalc = Number(function (){
let masseValue;
if (masse <= 2000) {
masseValue = (Math.ceil((masse/200)*5.625));
}
else if (masse >= 3000) {
masseValue =(Math.ceil((masse/200)*6.01));
}
else if (masse >= 3500) {
masseValue = (Math.ceil(masse/200)*6.39);
};
});
By the way, with :
if (masse <= 2000) {
masseValue = (Math.ceil((masse/200)*5.625));
}
else if (masse >= 3000) {
masseValue =(Math.ceil((masse/200)*6.01));
}
else if (masse >= 3500) {
masseValue = (Math.ceil(masse/200)*6.39);
};
You'll never get to the last else if as if we try it with 3700 for example. It will not match on the first if but on the second as 3700 is greater than 3000. You need to invert the order of the two else if.
And you need to add a else too for the number between 2000 and 3000 (If it's a accepted value)
A code refactoring should separate both current calculations each into a part that provides/implements a single specialized calculation function and a part which invokes the calculation with the correct values including valid fallback values in case some conditions could not be met.
In addition I suggest to fix the naming. Don't mix the languages. Skip the German part since most of the code (including the logging) is named and commented in English.
function getCalculatedHUeValue(displacement, emission, fuelFactor) {
return (Math.ceil(displacement / 100) * fuelFactor) + ((emission - 95) * 2);
}
function getCalculatedMassValue(mass, massFactor) {
return Math.ceil(mass / 200 * massFactor);
}
function calc() {
const displacement = Number(displacementComponent.value);
const emission = Number(emissionComponent.value);
const mass = Number(massComponent.value);
const hUeCalc = getCalculatedHUeValue(displacement, emission,
(Diesel.checked && 9.5) ||
(Benzin.checked && 2) ||
0 // default/fallback value needs to be provided/known.
);
const massCalc = getCalculatedMassValue(mass,
((mass <= 2000) && 5.625) ||
((mass >= 3500) && 6.39) ||
((mass >= 3000) && 6.01) ||
// what is the factor for the uncovered
// mass range in between 2001 and 2999?
0 // this fallback value has to be provided/known.
);
const result = (hUeCalc + massCalc);
tax.innerHTML = (result + "€");
console.log('Calculation is done');
console.log('displacement value is ' + displacement);
console.log('emission value is ' + emission);
console.log('mass value is ' + mass);
console.log('hUeCalc value is ' + hUeCalc);
console.log('massCalc value is ' + massCalc);
}
If you try the following code I think it should work. As you see if you want to use a function to assing a value the function has to return something, if it doesn't there's no value to assign. You also need to make sure the function is excecuted, if you don't the let hUeCalc = function(){} just becomes the function identifier.
function calc() {
let hubraum = Number(hubraumComponent.value);
let emission = Number(emissionComponent.value);
let masse = Number(masseComponent.value);
let hUeCalc = Number(function (){
if (Diesel.checked == true) {
return ((Math.ceil((hubraum/100)))*9.5)+((emission-95)*2);
}
else if (Benzin.checked == true) {
return ((Math.ceil((hubraum/100)))*2)+((emission-95)*2);
};
}());
let masseCalc = Number(function (){
let masseValue;
if (masse <= 2000) {
return masseValue = (Math.ceil((masse/200)*5.625));
}
else if (masse >= 3000) {
return masseValue =(Math.ceil((masse/200)*6.01));
}
else if (masse >= 3500) {
return masseValue = (Math.ceil(masse/200)*6.39);
};
}()); // using () right after the function makes it so it get excecuted immediately
// let masseValue = (Math.ceil (masse/200));
let berechnung = (hUeCalc + masseCalc);
tax.innerHTML = (berechnung) + "€";
console.log('Calc has been done');
console.log('hubraum value is ' + hubraum);
console.log('emission value is ' + emission);
console.log('masse value is ' + masse);
console.log('hubraumcalc value is ' + hUeCalc);
console.log('massecalc value is ' + masseCalc);
}
I'm creating a simple task where the text shows up after a user clicks the button 3 times. However, the code does not appear to work as I expected.
I've tried adding double bracket inside the if statement as outlined in the MDN guide without luck and also checked similar questions in Stack Overflow like this one, but they're using jquery, so I have no idea how it works.
Here's my codes:
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
}
if (currentval = 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
I'm sure I'm missing something important here and I will be appreciated for your guidance.
if (currentval = 0) { it should be if (currentval == 0) { and your if condition is outside of countDown() function.
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
console.log(currentval);
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!";
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
The errors you made have already been mentioned, I just wanted to add an answer with a little more modern and concise code. You really shouldn't use inline eventlisteners like onclick, instead use HTMLElement.prototype.addEventListener:
countDownBtn.addEventListener('click', () => {
if (Number(countDownBtn.textContent)) {
countDownBtn.textContent -= 1;
}
if (!Number(countDownBtn.textContent)) {
countDownBtn.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>
count = 0
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
if (count < 3) {
count = count+1
}else{
alert("hi")
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
You have missed "=" operator(currentval == 0)
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;"
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
Adding to the above answer a more concise code would be:
countDownBtn.addEventListener('click', (e) => {
if (Number(e.target.innerHTML)) {
e.target.innerHTML -= 1;
}else{
e.target.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>
I can't get this working:
var x = 1;
while (x == 1) {
}
function changeX(val) {
if (val == 1) {
x = 1;
} else if (val == 0) {
x = 0;
break;
}
}
and no matter what I do, I can't get this working. What I want to do is: I want the loop to stop working when I choose "0" or type it or anything. I have to use break/continue .
No matter what I do, I get wrong use of break or my browser crashes.
PS. In HTML part I put
<input type="text" value="1" onchange="changeX(this.value)">
Making your code work:
While will block the browsers thread. Therefore, you cannot click.
Do:
var x=false;
function react(){
if(x){return;}
//your code
console.log("sth");//e.g.
setTimeout(react,0);
}
react();
Now you can do your UI stuff
function changeX(val) {
if (val == 0) {
x = true;
}
}
What you really want:
var timer=false;
function input(val){
if(timer){
clearInterval(timer);
timer=false;
}
if(val){
timer=setInterval(function(){
val++;
alert(val);
if(val==10){
clearInterval(timer);
timer=false;
}
}, 1000);
}
<input oninput="input(this.value)">
<h3>Break Statement</h3>
<script>
let num=0;
while(num<5){
num++;
if((num==3)){
break;
}else{
document.write("num is: "+num+"<BR/>")
}
}
document.write("When if condition is true: while Loop Terminated");
</script>
<h3>Continue Statement</h3>
<script>
let val=0;
while(val<5){
val++;
if(val==3){
// skip the current loop iteration and jump to the next iteration
continue;
}
document.write("val = "+val+"<BR/>");
}
</script>
I wrote this javascript to make an animation. It is working fine in the home page. I wrote a alert message in the last.
If I go other then home page, this alert message has to come, but I am getting alert message, if I remove the function, alert message working on all pages, any thing wrong in my code?
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined){
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
}
alert('hi');
}
DEMO: http://jsbin.com/enaqu5/2
var yellows,signUp;
window.onload = function() {
yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
signUp = document.getElementById('signup-link');
if (yellows !== undefined && signUp !== undefined) {
for (var i = 0; i < yellows.length; i++) {
animeYellowBar(i);
}
}
alert('hi')
}
function animeYellowBar(num) {
setTimeout(function() {
yellows[num].style.left = "0";
if (num == yellows.length - 1) {
setTimeout(function() {
signUp.style.webkitTransform = "scale(1)";
},
num * 250);
}
},
num * 500);
}
DEMO 2: http://jsbin.com/utixi4 (just for sake)
$(function() {
$("#magazine-brief h2").each(function(i,item) {
$(this).delay(i+'00').animate({'marginLeft': 0 }, 500 ,function(){
if ( i === ( $('#magazine-brief h2').length - 1 ) )
$('#signup-link')[0].style.webkitTransform = "rotate(-2deg)";
});
});
});
For starters you are not clearing your SetTimeout and what are you truly after here? You have 2 anonymous methods that one triggers after half a second and the other triggers a quarter of a second later.
So this is just 2 delayed function calls with horribly broken syntax.
Edited Two possibilities, one fixes your current code... the latter shows you how to do it using JQuery which I would recomend:
var yellows, signUp;
window.onload = function(){
yellows = document.getElementById('magazine-brief');
if(yellows != null){
yellows = yellows.getElementsByTagName('h2');
}else{
yellows = null;
}
signUp = document.getElementById('signup-link');
if (yellows != null && signUp != null && yellows.length > 0)
{
for(var i = 0; i < yellows.length; i++)
{
animeYellowBar(i);
}
}
alert('hi');
}
function animeYellowBar(num)
{
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num*250);
}
}, num * 500);
}
The below approach is a SUMMARY of how to use JQuery, if you want to use JQuery I'll actually test it out:
//Or using JQuery
//Onload equivelent
$(function(){
var iterCount = 0,
maxIter = $("#magazine-brief").filter("h2").length;
$("#magazine-brief").filter("h2").each(function(){
setTimeout(function(){
$(this).css({left: 0});
if(iterCount == (maxIter-1))
{
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},iterCount*250);
}
}, iterCount++ * num );
});
});