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...
Related
i am trying to add a tag (to custom javascript) to my google tag manager, but i get "Error at line 12, character 5: Parse error. primary expression expected". Can i please get help to correct my code?
<script>
var x=document.getElementById("ad"),
z=window.getComputedStyle(x,null),
y=z.getPropertyValue("display");
function showAdblockAlert()
{alert("You're missing ads, therefore turn off your AD-blocker!")
}function adBlockNotDetected()
{alert("Thank you for not using AD-blocker");
console.log
("no ad-blocker")}console.log(y);
"none",
==y?showAdblockAlert():adBlockNotDetected();
</script>
This code is odd. It combines some basic mistakes as well as advanced techniques if you can call that a ternary or using commas with a var.
Anyhow, your error is likely due to poor copying. The "none",== part, I think, got there from somewhere else.
Here, try this:
var x = document.getElementById("ad"),
z = window.getComputedStyle(x, null),
y = z.getPropertyValue("display");
function showAdblockAlert() {
alert("You're missing ads, therefore turn off your AD-blocker!")
} function adBlockNotDetected() {
alert("Thank you for not using AD-blocker");
console.log("no ad-blocker")
}
console.log(y);
y ? showAdblockAlert() : adBlockNotDetected();
You should know, however, that alerts in production is a very good way to get your site blacklisted one way or another.
Besides, declaring globals like that is a very bad idea.
Your code is unsafe. It relies on getComputedStyle to be there, as well as other elements. It throws errors otherwise.
Finally, the use of functions there seems to be a little excessive. They're not needed if you swap the ternary with a normal if, making the code much more readable.
I have the following code:
function periodClassMaker(period) {
$('.rsform-block-rsa-formaat-w' + period).parent().addClass('periodselected');
}
periodClassMaker(['1','2']);
I have also tried:
periodClassMaker('1','2');
But in both cases it fails to add the class periodselected to .rsform-block-rsa-formaat-w1 and .rsform-block-rsa-formaat-w2
And I don't understand why it fails.
This question was asked earlier but I asked it totally unrelated to my own code. As I did not know if it was at all possible. Everyone commenting me told me to put in my own code so that it was better to comment/reply on specific use cases.
Before asking this previous question I did some trial and error but did not receive an error message and also not the result I wished for. Upon which I went to SO and searched for "multiple arguments for one parameter" and similar search phrases. Many result came up and after reading about a dozen I still did not have a clear view if it was at all possible and if it was on how to do it. Therefore, I posted my own question.
I hope that after the edit the question is useful, clear and that it shows that I did a bit of research before posting.
function periodClassMaker(period) {
$(period.map(it => `.rsform-block-rsa-formaat-w${it}`).join(', ')).parent().addClass('periodselected');
}
periodClassMaker(['1','2']);
You can map the individual numbers to each selector string, and then join them by a comma for the logical OR selector.
I've noticed that you when writing jasmine unit tests usually the format is:
expect($('#foo')).toHaveValue('#bar');
But recently I've discovered by accident that the following also works:
expect('#foo').toHaveValue('#bar');
Is this expected behaviour? This seems like a better way to write my expects but I have never seen this notation before and I want to be sure I am not abusing something.
Could anyone confirm this is the way to go or direct me to any documentation of this?
(I am using the jasmine jquery library)
I've played around a bit with that. Looks like it really does work, having some peculiarities, though.
I've tried things like:
expect('.search-form').toBeInDOM();
expect('.search-form').toEqual('div');
expect('.search-form').toContainElement('.search-form__footer');
the first one passes and truely fails when changing to
.not.toBeInDOM();
the third one looks same -- it truely fails is changing to some
bad selector for toContainElement
the second one is a problem because of ambiguity: '.search-form' can be treated both as string and a selector.
Had a very brief look into source code, it looks likes matchers really do resolve expectation actual as a selector (example from):
toBeInDOM: function () {
return {
compare: function (actual) {
return { pass: $.contains(document.documentElement, $(actual)[0]) }
}
}
},
Although I could not find any sign of such abilities in their docs, too. Still, source code is source code ))) and it says what it says. And now it says it will treat the actual for expect as a selector.
When creating an if block, I was wondering if there was any reason beyond personal preference to use the standard bracket formatting vs the second one I listed.
I've run code in the second format without any obvious issues (no ASI or unexpected errors), just looking for some clarification or insight on if there could be any possible issues in the future if I permanently switch to this style.
// Standard formatting
if (true) {
} else {
}
// Other formatting
if (true) {
}
else {
}
Spaces and tabs are not considered to be significant in Javascript in most cases. (I believe all, but I can't find a source for that)
You can technically put all of your code on one line (as most minification algorithms do), but that won't be very readable. In your own code, it comes down to solely personal preference, it will not cause any errors or cause the code to run slower if there are spaces (though more spaces will take longer to load if the JS is not minified).
Best practice is to keep your code style consistent throughout your projects.
None, they are equivalent if you wanted you could put the code in one line as well and it would work. Usually people have personal preferences, as well as some companies require you to write the code in a specific way in order to standardize it and make it so anyone taking over your project knows what to expect.
You don't even need the brackets, it wil just work:
http://jsfiddle.net/4ywahnof/1/
(function () {
var t = 1;
if (t == 1) alert("hi");
else alert("no hi");
})();
Hei
I am going through the JavaScript tutorial on Codeacademy and I'm stuck on Introduction to Objects II lesson 2/30. The code that I have entered seems fine to me and the code prints the necessary line hello to the console.
But I get an error "Oops, try again. It looks like 'Hello!' wasn't logged to the console. Make sure that you properly defined the method and that you didn't change any of the provided code."
I cant seem to find anything wrong with this code that I have entered
function Person(job, married) {
this.job = job;
this.married = married;
// add a "speak" method to Person!
this.speak = function() {
console.log("Hello");
};
}
var user = new Person("Codecademy Student",false);
user.speak();
The problem is in your posted image, see the last line of the code editor:
user.speak();z //<-- z is not something what you have defined.
I went through several courses on Codeacademy. Codeacademy often has broken lessons, and if it's working on jsFiddle, it's likely two things.
1: Spelling and punctuation. Codeacademy is very specific with strings. One wrong letter, or one wrongly punctuated letter will show it as a fail.
2: Error. If this is the case, the codeacademy community usually has work arounds. If not, you can skip this particular lesson, and keep on going with the course. The 100% complete is more symbolic than anything else. As long as you're learning the concepts, it's find to skip whatever you have to.
Also, codeacademy has an excellent community that will give more specific advice tailored to the course. Here's the relevant forum for that course.
http://www.codecademy.com/forums/objects-ii/0