The Questions of if/else statements and other alike codes
Hi, currently I am using this code to call an if/else statement, to add and/or remove the class ".hide" whenever the different tables are clicked on. This code is working all fine, no trouble with it at all.
Example 1
$(document).ready(function() {
$('#Year_Table').click(function() {
if ($('#Month_Table').hasClass("hide")) {
$('#Month_Table').removeClass('hide');
} else {
$('#Month_Table').addClass('hide');
$('#Day_Table').addClass('hide');
}
});
});
But what I am wondering about, is if there is anyway to make the code shorter? but with the same outcome. That the class is add or removed.
I had another question a few days ago, where a guy shortened my if/else statement to this code below. Thank you
Example 2
$( document ).ready(function(){
var games_month = 0;
var month_games = "Games";
$("#Games_Month").html(games_month);
$('#January').click(function(){
$('#Games_Month').html(function(_, html) {
return html === month_games ? games_month : month_games;
});
});
The shortened code works perfectly too, but gives me a couple of question marks.
Now, what I would like to know is:
1:
What is this type of code that was shortened for me? I mean, what is it called?
I have been told it might be a callback function.
2:
What is different from a standard if/else statement and the shortened code?
is it the same, just cleaned up? or is there any important difference?
3:
What does the different parts of the shortened code mean? what do they do?
To me it just seem like another kind of an if/else statement?
4:
is there any way to make such a code with classes instead of variables?
Simply instead of changing the variable, I would like to add or remove the class ".hide" and is it possible to add and remove several classes within this function?
5:
Is there any other ways to code an if/else statement or code which gives the same result?
I am very new at using both javascript and jQuery, but I'm trying to learn as much as possible. I appreciate all the help I can get to understand all this, everything will help me getting further into my knowlegde of coding.
Thank you very much.
$(document).ready(function() {
$('#Year_Table').click(function() {
$('#Month_Table').toggleClass("hide");
$('#Day_Table').toggleClass('hide');
});
});
.hide {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='Year_Table'>click me</span>
<span id='Month_Table'>Month_Table</span>
<span id='Day_Table'>Day_Table</span>
Use .toggleClass()
You can shorten your example 1 code using toggleClass like this:
$(document).ready(function() {
$('#Year_Table').click(function() {
$('#Month_Table').toggleClass('hide');
$('#Day_Table').toggleClass('hide');
});
});
And in your example 2, you are using ternary operator instead of if/else statement which takes three operands.
condition ? expr1 : expr2
Related
I'm new to javascript and I'm trying to make a program to continuosly click one button unless another button is present. (I'd also love to get an alert when the second button appears but I don't know how to do that.)
This is what I got:
Do {Let button=document.getElementById("find");
Let want= document.getElementById("bba");
setInterval(function(){
button.click();
}, 10000); }
while (want.click=false)
I keep getting errors (unidentified syntex). I'm not sure how to fix it.
Any help will be greatly appreciated!
What you should do is use a single setInterval :
window.setInterval(function() {
if (!document.getElementById("button2")) {
document.getElementById("button1").click();
} else {
document.getElementById("button2").click();
alert("second button appeared");
}
}, 100);
Sorry for formatting, I'm on mobile.
Just from looking over your code I see two main errors. The first is that you used a capital do and let, JavaScript is case sensitive so you need to use lowercase. The second is that in you wrote
while (want.click=false)
What you wrote is an assignment not a equality check.
while (want.click == false)
That's the correct way to write it.
Your do and let keywords are capitalized. They should be lower case.
Let want= document.`getElementById`("bba");
You should use a triple equal sign here rather than an assignment operator.
it should be: let want === document.getElementById("bba");
I'm trying to have a navBar that generates automatically by looping through an array of "Page" objects. Unfortunately, I seem to be falling into the loops/closure trap. I have read several threads related to this and in some cases have copy and pasted solution code and passed in my own variables but I'm struggling to make it assign onclicks correctly.
I know I'm close. In the below code are two options that I have tried.
Am I getting something wrong with the paremeter in parenthesis in the self-calling function? - the ()(divId)? I don't really understand this part.
Could I also be struggling because this is being done as an object method?
Any help much appreciated but go easy on me, I'm learning all this in my spare time! ;)
Thanks in advance.
EDIT: Jsfiddle: https://jsfiddle.net/mcgettrm/fs0mtz6n/
var navBar = {
display: function(){
for(i=0;i<pages.length;i++){
document.getElementById('navBar').innerHTML += pages[i].token;
var divId = pages[i].unique;
// code works fine up to here.
// option one(below): when navBar.display() is called the following code only adds
// the onclick to the final navbar link
document.getElementById(divId).onclick=(function(divId) {
return function() {
alert(divId);
};
})(divId);
//option two(below): when navBar.display() is called the following code logs
// the individual div id's correctly. But, it does it without being clicked. Then,
// only the last item in the loop is clickable.
(function(divId){
document.getElementById(divId).onclick= function(){
console.log(divId);
}
}
)(divId);
}
}
};
I've got it working here - https://jsfiddle.net/pqu9kr85/ it doesn't seem to have been to do with the binding of i more that you needed to build up the navigation html first, making sure it was in the DOM before binding the event. I put two separate loops, one to generate the nav, the second to bind the events. Also updated the page.display() to use this as that will have been affected by the value of i.
I have a Jquery function in MVC View that check if at least one checkbox is clicked. Function is working properly if I use hardcoded string. But when I add
#Resources.myString into, it stops working, I can't figure out why
$('.form-horizontal').on('submit', function (e) {
if ($("input[type=checkbox]:checked").length === 0) {
e.preventDefault();
alert("This is working");
alert(#Resources.myString); //with this the function is not working anymore
return false;
}
});
I need to add the the string for multilingual purpose.
I tried diferent aproches
alert(#Resources.myString);
alert(#Html.Raw(Resources.myString))
var aaa = { #Html.Raw(Resources.myString)} //and calling the aaa
I think I am missing some basic knowlage of how this should work together
During page rendering, #Resources.myString will be injected as is in the code. For instance, if myString == "abc";, you'll end up with alert(abc); which is not what you want.
Just try to enclose your string in quotes:
alert("#Resources.myString");
As an aside, putting Razor code in Javascript logic is usually considered bad practice, as it prevents you from putting Javascript code in separate files (and therefore caching), and makes the code less readable.
Take a look as this question and the provided answer which gives a simple way to deal with that.
As ASP.NET dynamically generates HTML, CSS, JS code, the best way to find the error is to read the generated sources (Ctrl + U in most modern browsers).
You will see that your code
alert(#Resources.myString);
produces
alert(yourStringContent);
and should result in a console error yourStringContent is not defined.
You need to use quotes as you are working with a JavaScript string:
alert('#Resources.myString');
It will produce a correct JavaScript code like:
alert('yourStringContent');
I am using the following code
function xhi(aax)
{
var aby=document.getElementById(aax);
aby.style.bottom=(parseInt(aby.style.bottom)+(screen.height-42)/10)+'px';
if(parseInt(aby.style.bottom)<(screen.height-42))setTimeout('xhi("'+aax+'")',25);
}
When i run this code the function calls itself only two times . second time aby.style.bottom becomes Null.Why?
Check the bottom value. It might be crazy, but if the value is something like 008, 010, etc.
parseInt treats the number as octal. In order to avoid this, use :
parseInt(aby.style.bottom,10)
Why are you using bottom? I believe the best approach is the top attribute.
If everything else fails, jQuery has some nice functions to animate and to grab those style attributes.
I am not sure but try after removing from your code +'px' .
At the moment I'm learning jQuery and I hit the topic about if/else statements. As I have no background in programming this topic is something that I need to practice a bit more to get a thorough understanding of it.
The book I'm studying gave me the advice of just writing different blocks of if/else statements. I just had an idea and wanted to know if its valid:
$(morningWakeup).ready(function() {
$('#arms').reaction(function() {
if($'#kid').is(':nagging')) {
$('#kid').slap();
} else {
$('#kid').hug();
}
});
});
Let me make it clear that this is a joke of course, but I want to know if this is valid code and if you can supply me with some more examples? Thank you!
The basic form is perfectly fine, though you've misplaced some parentheses on this line: if($'#kid').is(':nagging')) {. It should be if ($('#kid').is(':nagging')) { instead. Also, note that you'll have better luck setting $('#kid').attr('behaving') to true if you just ignore() him/her for a while instead of slap()ing them. Negative reinforcement sucks. :)
You're mixing up Javascript and jQuery here: The if/else is basically valid, but the jQuery part (.is etc.) will strongly depend on whether the DOM elements exist, whether they have that property etc.
I would recommend starting with real live HTML to go along.
That, and of course the syntax error #bcat points out...